PPCISelLowering.cpp 706 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975
  1. //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the PPCISelLowering class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "PPCISelLowering.h"
  13. #include "MCTargetDesc/PPCPredicates.h"
  14. #include "PPC.h"
  15. #include "PPCCCState.h"
  16. #include "PPCCallingConv.h"
  17. #include "PPCFrameLowering.h"
  18. #include "PPCInstrInfo.h"
  19. #include "PPCMachineFunctionInfo.h"
  20. #include "PPCPerfectShuffle.h"
  21. #include "PPCRegisterInfo.h"
  22. #include "PPCSubtarget.h"
  23. #include "PPCTargetMachine.h"
  24. #include "llvm/ADT/APFloat.h"
  25. #include "llvm/ADT/APInt.h"
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/None.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/SmallSet.h"
  32. #include "llvm/ADT/SmallVector.h"
  33. #include "llvm/ADT/Statistic.h"
  34. #include "llvm/ADT/StringRef.h"
  35. #include "llvm/ADT/StringSwitch.h"
  36. #include "llvm/CodeGen/CallingConvLower.h"
  37. #include "llvm/CodeGen/ISDOpcodes.h"
  38. #include "llvm/CodeGen/MachineBasicBlock.h"
  39. #include "llvm/CodeGen/MachineFrameInfo.h"
  40. #include "llvm/CodeGen/MachineFunction.h"
  41. #include "llvm/CodeGen/MachineInstr.h"
  42. #include "llvm/CodeGen/MachineInstrBuilder.h"
  43. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  44. #include "llvm/CodeGen/MachineLoopInfo.h"
  45. #include "llvm/CodeGen/MachineMemOperand.h"
  46. #include "llvm/CodeGen/MachineModuleInfo.h"
  47. #include "llvm/CodeGen/MachineOperand.h"
  48. #include "llvm/CodeGen/MachineRegisterInfo.h"
  49. #include "llvm/CodeGen/RuntimeLibcalls.h"
  50. #include "llvm/CodeGen/SelectionDAG.h"
  51. #include "llvm/CodeGen/SelectionDAGNodes.h"
  52. #include "llvm/CodeGen/TargetInstrInfo.h"
  53. #include "llvm/CodeGen/TargetLowering.h"
  54. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  55. #include "llvm/CodeGen/TargetRegisterInfo.h"
  56. #include "llvm/CodeGen/ValueTypes.h"
  57. #include "llvm/IR/CallingConv.h"
  58. #include "llvm/IR/Constant.h"
  59. #include "llvm/IR/Constants.h"
  60. #include "llvm/IR/DataLayout.h"
  61. #include "llvm/IR/DebugLoc.h"
  62. #include "llvm/IR/DerivedTypes.h"
  63. #include "llvm/IR/Function.h"
  64. #include "llvm/IR/GlobalValue.h"
  65. #include "llvm/IR/IRBuilder.h"
  66. #include "llvm/IR/Instructions.h"
  67. #include "llvm/IR/Intrinsics.h"
  68. #include "llvm/IR/IntrinsicsPowerPC.h"
  69. #include "llvm/IR/Module.h"
  70. #include "llvm/IR/Type.h"
  71. #include "llvm/IR/Use.h"
  72. #include "llvm/IR/Value.h"
  73. #include "llvm/MC/MCContext.h"
  74. #include "llvm/MC/MCExpr.h"
  75. #include "llvm/MC/MCRegisterInfo.h"
  76. #include "llvm/MC/MCSectionXCOFF.h"
  77. #include "llvm/MC/MCSymbolXCOFF.h"
  78. #include "llvm/Support/AtomicOrdering.h"
  79. #include "llvm/Support/BranchProbability.h"
  80. #include "llvm/Support/Casting.h"
  81. #include "llvm/Support/CodeGen.h"
  82. #include "llvm/Support/CommandLine.h"
  83. #include "llvm/Support/Compiler.h"
  84. #include "llvm/Support/Debug.h"
  85. #include "llvm/Support/ErrorHandling.h"
  86. #include "llvm/Support/Format.h"
  87. #include "llvm/Support/KnownBits.h"
  88. #include "llvm/Support/MachineValueType.h"
  89. #include "llvm/Support/MathExtras.h"
  90. #include "llvm/Support/raw_ostream.h"
  91. #include "llvm/Target/TargetMachine.h"
  92. #include "llvm/Target/TargetOptions.h"
  93. #include <algorithm>
  94. #include <cassert>
  95. #include <cstdint>
  96. #include <iterator>
  97. #include <list>
  98. #include <utility>
  99. #include <vector>
  100. using namespace llvm;
  101. #define DEBUG_TYPE "ppc-lowering"
  102. static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
  103. cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
  104. static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
  105. cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
  106. static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
  107. cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
  108. static cl::opt<bool> DisableSCO("disable-ppc-sco",
  109. cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
  110. static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
  111. cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
  112. static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
  113. cl::desc("use absolute jump tables on ppc"), cl::Hidden);
  114. static cl::opt<bool> EnableQuadwordAtomics(
  115. "ppc-quadword-atomics",
  116. cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
  117. cl::Hidden);
  118. STATISTIC(NumTailCalls, "Number of tail calls");
  119. STATISTIC(NumSiblingCalls, "Number of sibling calls");
  120. STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
  121. STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
  122. static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
  123. static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
  124. static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
  125. // FIXME: Remove this once the bug has been fixed!
  126. extern cl::opt<bool> ANDIGlueBug;
  127. PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
  128. const PPCSubtarget &STI)
  129. : TargetLowering(TM), Subtarget(STI) {
  130. // Initialize map that relates the PPC addressing modes to the computed flags
  131. // of a load/store instruction. The map is used to determine the optimal
  132. // addressing mode when selecting load and stores.
  133. initializeAddrModeMap();
  134. // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
  135. // arguments are at least 4/8 bytes aligned.
  136. bool isPPC64 = Subtarget.isPPC64();
  137. setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
  138. // Set up the register classes.
  139. addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
  140. if (!useSoftFloat()) {
  141. if (hasSPE()) {
  142. addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
  143. // EFPU2 APU only supports f32
  144. if (!Subtarget.hasEFPU2())
  145. addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
  146. } else {
  147. addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
  148. addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
  149. }
  150. }
  151. // Match BITREVERSE to customized fast code sequence in the td file.
  152. setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
  153. setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
  154. // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
  155. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
  156. // Custom lower inline assembly to check for special registers.
  157. setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
  158. setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
  159. // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
  160. for (MVT VT : MVT::integer_valuetypes()) {
  161. setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
  162. setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
  163. }
  164. if (Subtarget.isISA3_0()) {
  165. setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
  166. setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
  167. setTruncStoreAction(MVT::f64, MVT::f16, Legal);
  168. setTruncStoreAction(MVT::f32, MVT::f16, Legal);
  169. } else {
  170. // No extending loads from f16 or HW conversions back and forth.
  171. setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
  172. setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
  173. setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
  174. setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
  175. setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
  176. setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
  177. setTruncStoreAction(MVT::f64, MVT::f16, Expand);
  178. setTruncStoreAction(MVT::f32, MVT::f16, Expand);
  179. }
  180. setTruncStoreAction(MVT::f64, MVT::f32, Expand);
  181. // PowerPC has pre-inc load and store's.
  182. setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
  183. setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
  184. setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
  185. setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
  186. setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
  187. setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
  188. setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
  189. setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
  190. setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
  191. setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
  192. if (!Subtarget.hasSPE()) {
  193. setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
  194. setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
  195. setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
  196. setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
  197. }
  198. // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
  199. const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
  200. for (MVT VT : ScalarIntVTs) {
  201. setOperationAction(ISD::ADDC, VT, Legal);
  202. setOperationAction(ISD::ADDE, VT, Legal);
  203. setOperationAction(ISD::SUBC, VT, Legal);
  204. setOperationAction(ISD::SUBE, VT, Legal);
  205. }
  206. if (Subtarget.useCRBits()) {
  207. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
  208. if (isPPC64 || Subtarget.hasFPCVT()) {
  209. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
  210. AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
  211. isPPC64 ? MVT::i64 : MVT::i32);
  212. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
  213. AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
  214. isPPC64 ? MVT::i64 : MVT::i32);
  215. setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
  216. AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
  217. isPPC64 ? MVT::i64 : MVT::i32);
  218. setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
  219. AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
  220. isPPC64 ? MVT::i64 : MVT::i32);
  221. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
  222. AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
  223. isPPC64 ? MVT::i64 : MVT::i32);
  224. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
  225. AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
  226. isPPC64 ? MVT::i64 : MVT::i32);
  227. setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
  228. AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
  229. isPPC64 ? MVT::i64 : MVT::i32);
  230. setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
  231. AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
  232. isPPC64 ? MVT::i64 : MVT::i32);
  233. } else {
  234. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
  235. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
  236. setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
  237. setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
  238. }
  239. // PowerPC does not support direct load/store of condition registers.
  240. setOperationAction(ISD::LOAD, MVT::i1, Custom);
  241. setOperationAction(ISD::STORE, MVT::i1, Custom);
  242. // FIXME: Remove this once the ANDI glue bug is fixed:
  243. if (ANDIGlueBug)
  244. setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
  245. for (MVT VT : MVT::integer_valuetypes()) {
  246. setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
  247. setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
  248. setTruncStoreAction(VT, MVT::i1, Expand);
  249. }
  250. addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
  251. }
  252. // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
  253. // PPC (the libcall is not available).
  254. setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
  255. setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
  256. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
  257. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
  258. // We do not currently implement these libm ops for PowerPC.
  259. setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
  260. setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
  261. setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
  262. setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
  263. setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
  264. setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
  265. // PowerPC has no SREM/UREM instructions unless we are on P9
  266. // On P9 we may use a hardware instruction to compute the remainder.
  267. // When the result of both the remainder and the division is required it is
  268. // more efficient to compute the remainder from the result of the division
  269. // rather than use the remainder instruction. The instructions are legalized
  270. // directly because the DivRemPairsPass performs the transformation at the IR
  271. // level.
  272. if (Subtarget.isISA3_0()) {
  273. setOperationAction(ISD::SREM, MVT::i32, Legal);
  274. setOperationAction(ISD::UREM, MVT::i32, Legal);
  275. setOperationAction(ISD::SREM, MVT::i64, Legal);
  276. setOperationAction(ISD::UREM, MVT::i64, Legal);
  277. } else {
  278. setOperationAction(ISD::SREM, MVT::i32, Expand);
  279. setOperationAction(ISD::UREM, MVT::i32, Expand);
  280. setOperationAction(ISD::SREM, MVT::i64, Expand);
  281. setOperationAction(ISD::UREM, MVT::i64, Expand);
  282. }
  283. // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
  284. setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
  285. setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
  286. setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
  287. setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
  288. setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
  289. setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
  290. setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
  291. setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
  292. // Handle constrained floating-point operations of scalar.
  293. // TODO: Handle SPE specific operation.
  294. setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
  295. setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
  296. setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
  297. setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
  298. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
  299. setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
  300. setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
  301. setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
  302. setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
  303. if (!Subtarget.hasSPE()) {
  304. setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
  305. setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
  306. }
  307. if (Subtarget.hasVSX()) {
  308. setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
  309. setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
  310. }
  311. if (Subtarget.hasFSQRT()) {
  312. setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
  313. setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
  314. }
  315. if (Subtarget.hasFPRND()) {
  316. setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
  317. setOperationAction(ISD::STRICT_FCEIL, MVT::f32, Legal);
  318. setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
  319. setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
  320. setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
  321. setOperationAction(ISD::STRICT_FCEIL, MVT::f64, Legal);
  322. setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
  323. setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
  324. }
  325. // We don't support sin/cos/sqrt/fmod/pow
  326. setOperationAction(ISD::FSIN , MVT::f64, Expand);
  327. setOperationAction(ISD::FCOS , MVT::f64, Expand);
  328. setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
  329. setOperationAction(ISD::FREM , MVT::f64, Expand);
  330. setOperationAction(ISD::FPOW , MVT::f64, Expand);
  331. setOperationAction(ISD::FSIN , MVT::f32, Expand);
  332. setOperationAction(ISD::FCOS , MVT::f32, Expand);
  333. setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
  334. setOperationAction(ISD::FREM , MVT::f32, Expand);
  335. setOperationAction(ISD::FPOW , MVT::f32, Expand);
  336. if (Subtarget.hasSPE()) {
  337. setOperationAction(ISD::FMA , MVT::f64, Expand);
  338. setOperationAction(ISD::FMA , MVT::f32, Expand);
  339. } else {
  340. setOperationAction(ISD::FMA , MVT::f64, Legal);
  341. setOperationAction(ISD::FMA , MVT::f32, Legal);
  342. }
  343. if (Subtarget.hasSPE())
  344. setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
  345. setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
  346. // If we're enabling GP optimizations, use hardware square root
  347. if (!Subtarget.hasFSQRT() &&
  348. !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
  349. Subtarget.hasFRE()))
  350. setOperationAction(ISD::FSQRT, MVT::f64, Expand);
  351. if (!Subtarget.hasFSQRT() &&
  352. !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
  353. Subtarget.hasFRES()))
  354. setOperationAction(ISD::FSQRT, MVT::f32, Expand);
  355. if (Subtarget.hasFCPSGN()) {
  356. setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
  357. setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
  358. } else {
  359. setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
  360. setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
  361. }
  362. if (Subtarget.hasFPRND()) {
  363. setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
  364. setOperationAction(ISD::FCEIL, MVT::f64, Legal);
  365. setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
  366. setOperationAction(ISD::FROUND, MVT::f64, Legal);
  367. setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
  368. setOperationAction(ISD::FCEIL, MVT::f32, Legal);
  369. setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
  370. setOperationAction(ISD::FROUND, MVT::f32, Legal);
  371. }
  372. // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
  373. // to speed up scalar BSWAP64.
  374. // CTPOP or CTTZ were introduced in P8/P9 respectively
  375. setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
  376. if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
  377. setOperationAction(ISD::BSWAP, MVT::i64 , Custom);
  378. else
  379. setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
  380. if (Subtarget.isISA3_0()) {
  381. setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
  382. setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
  383. } else {
  384. setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
  385. setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
  386. }
  387. if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
  388. setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
  389. setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
  390. } else {
  391. setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
  392. setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
  393. }
  394. // PowerPC does not have ROTR
  395. setOperationAction(ISD::ROTR, MVT::i32 , Expand);
  396. setOperationAction(ISD::ROTR, MVT::i64 , Expand);
  397. if (!Subtarget.useCRBits()) {
  398. // PowerPC does not have Select
  399. setOperationAction(ISD::SELECT, MVT::i32, Expand);
  400. setOperationAction(ISD::SELECT, MVT::i64, Expand);
  401. setOperationAction(ISD::SELECT, MVT::f32, Expand);
  402. setOperationAction(ISD::SELECT, MVT::f64, Expand);
  403. }
  404. // PowerPC wants to turn select_cc of FP into fsel when possible.
  405. setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
  406. setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
  407. // PowerPC wants to optimize integer setcc a bit
  408. if (!Subtarget.useCRBits())
  409. setOperationAction(ISD::SETCC, MVT::i32, Custom);
  410. if (Subtarget.hasFPU()) {
  411. setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
  412. setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
  413. setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
  414. setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
  415. setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
  416. setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
  417. }
  418. // PowerPC does not have BRCOND which requires SetCC
  419. if (!Subtarget.useCRBits())
  420. setOperationAction(ISD::BRCOND, MVT::Other, Expand);
  421. setOperationAction(ISD::BR_JT, MVT::Other, Expand);
  422. if (Subtarget.hasSPE()) {
  423. // SPE has built-in conversions
  424. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
  425. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
  426. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
  427. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
  428. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
  429. setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
  430. // SPE supports signaling compare of f32/f64.
  431. setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
  432. setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
  433. } else {
  434. // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
  435. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
  436. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
  437. // PowerPC does not have [U|S]INT_TO_FP
  438. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
  439. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
  440. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
  441. setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
  442. }
  443. if (Subtarget.hasDirectMove() && isPPC64) {
  444. setOperationAction(ISD::BITCAST, MVT::f32, Legal);
  445. setOperationAction(ISD::BITCAST, MVT::i32, Legal);
  446. setOperationAction(ISD::BITCAST, MVT::i64, Legal);
  447. setOperationAction(ISD::BITCAST, MVT::f64, Legal);
  448. if (TM.Options.UnsafeFPMath) {
  449. setOperationAction(ISD::LRINT, MVT::f64, Legal);
  450. setOperationAction(ISD::LRINT, MVT::f32, Legal);
  451. setOperationAction(ISD::LLRINT, MVT::f64, Legal);
  452. setOperationAction(ISD::LLRINT, MVT::f32, Legal);
  453. setOperationAction(ISD::LROUND, MVT::f64, Legal);
  454. setOperationAction(ISD::LROUND, MVT::f32, Legal);
  455. setOperationAction(ISD::LLROUND, MVT::f64, Legal);
  456. setOperationAction(ISD::LLROUND, MVT::f32, Legal);
  457. }
  458. } else {
  459. setOperationAction(ISD::BITCAST, MVT::f32, Expand);
  460. setOperationAction(ISD::BITCAST, MVT::i32, Expand);
  461. setOperationAction(ISD::BITCAST, MVT::i64, Expand);
  462. setOperationAction(ISD::BITCAST, MVT::f64, Expand);
  463. }
  464. // We cannot sextinreg(i1). Expand to shifts.
  465. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
  466. // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
  467. // SjLj exception handling but a light-weight setjmp/longjmp replacement to
  468. // support continuation, user-level threading, and etc.. As a result, no
  469. // other SjLj exception interfaces are implemented and please don't build
  470. // your own exception handling based on them.
  471. // LLVM/Clang supports zero-cost DWARF exception handling.
  472. setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
  473. setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
  474. // We want to legalize GlobalAddress and ConstantPool nodes into the
  475. // appropriate instructions to materialize the address.
  476. setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
  477. setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
  478. setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
  479. setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
  480. setOperationAction(ISD::JumpTable, MVT::i32, Custom);
  481. setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
  482. setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
  483. setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
  484. setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
  485. setOperationAction(ISD::JumpTable, MVT::i64, Custom);
  486. // TRAP is legal.
  487. setOperationAction(ISD::TRAP, MVT::Other, Legal);
  488. // TRAMPOLINE is custom lowered.
  489. setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
  490. setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
  491. // VASTART needs to be custom lowered to use the VarArgsFrameIndex
  492. setOperationAction(ISD::VASTART , MVT::Other, Custom);
  493. if (Subtarget.is64BitELFABI()) {
  494. // VAARG always uses double-word chunks, so promote anything smaller.
  495. setOperationAction(ISD::VAARG, MVT::i1, Promote);
  496. AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
  497. setOperationAction(ISD::VAARG, MVT::i8, Promote);
  498. AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
  499. setOperationAction(ISD::VAARG, MVT::i16, Promote);
  500. AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
  501. setOperationAction(ISD::VAARG, MVT::i32, Promote);
  502. AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
  503. setOperationAction(ISD::VAARG, MVT::Other, Expand);
  504. } else if (Subtarget.is32BitELFABI()) {
  505. // VAARG is custom lowered with the 32-bit SVR4 ABI.
  506. setOperationAction(ISD::VAARG, MVT::Other, Custom);
  507. setOperationAction(ISD::VAARG, MVT::i64, Custom);
  508. } else
  509. setOperationAction(ISD::VAARG, MVT::Other, Expand);
  510. // VACOPY is custom lowered with the 32-bit SVR4 ABI.
  511. if (Subtarget.is32BitELFABI())
  512. setOperationAction(ISD::VACOPY , MVT::Other, Custom);
  513. else
  514. setOperationAction(ISD::VACOPY , MVT::Other, Expand);
  515. // Use the default implementation.
  516. setOperationAction(ISD::VAEND , MVT::Other, Expand);
  517. setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
  518. setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
  519. setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
  520. setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
  521. setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
  522. setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
  523. setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
  524. setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
  525. // We want to custom lower some of our intrinsics.
  526. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
  527. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
  528. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
  529. // To handle counter-based loop conditions.
  530. setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
  531. setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
  532. setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
  533. setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
  534. setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
  535. // Comparisons that require checking two conditions.
  536. if (Subtarget.hasSPE()) {
  537. setCondCodeAction(ISD::SETO, MVT::f32, Expand);
  538. setCondCodeAction(ISD::SETO, MVT::f64, Expand);
  539. setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
  540. setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
  541. }
  542. setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
  543. setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
  544. setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
  545. setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
  546. setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
  547. setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
  548. setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
  549. setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
  550. setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
  551. setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
  552. setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
  553. setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
  554. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
  555. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
  556. if (Subtarget.has64BitSupport()) {
  557. // They also have instructions for converting between i64 and fp.
  558. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
  559. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
  560. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
  561. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
  562. setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
  563. setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
  564. setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
  565. setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
  566. // This is just the low 32 bits of a (signed) fp->i64 conversion.
  567. // We cannot do this with Promote because i64 is not a legal type.
  568. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
  569. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
  570. if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
  571. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
  572. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
  573. }
  574. } else {
  575. // PowerPC does not have FP_TO_UINT on 32-bit implementations.
  576. if (Subtarget.hasSPE()) {
  577. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
  578. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
  579. } else {
  580. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
  581. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
  582. }
  583. }
  584. // With the instructions enabled under FPCVT, we can do everything.
  585. if (Subtarget.hasFPCVT()) {
  586. if (Subtarget.has64BitSupport()) {
  587. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
  588. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
  589. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
  590. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
  591. setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
  592. setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
  593. setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
  594. setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
  595. }
  596. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
  597. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
  598. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
  599. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
  600. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
  601. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
  602. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
  603. setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
  604. }
  605. if (Subtarget.use64BitRegs()) {
  606. // 64-bit PowerPC implementations can support i64 types directly
  607. addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
  608. // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
  609. setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
  610. // 64-bit PowerPC wants to expand i128 shifts itself.
  611. setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
  612. setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
  613. setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
  614. } else {
  615. // 32-bit PowerPC wants to expand i64 shifts itself.
  616. setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
  617. setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
  618. setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
  619. }
  620. // PowerPC has better expansions for funnel shifts than the generic
  621. // TargetLowering::expandFunnelShift.
  622. if (Subtarget.has64BitSupport()) {
  623. setOperationAction(ISD::FSHL, MVT::i64, Custom);
  624. setOperationAction(ISD::FSHR, MVT::i64, Custom);
  625. }
  626. setOperationAction(ISD::FSHL, MVT::i32, Custom);
  627. setOperationAction(ISD::FSHR, MVT::i32, Custom);
  628. if (Subtarget.hasVSX()) {
  629. setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
  630. setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
  631. setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
  632. setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
  633. }
  634. if (Subtarget.hasAltivec()) {
  635. for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
  636. setOperationAction(ISD::SADDSAT, VT, Legal);
  637. setOperationAction(ISD::SSUBSAT, VT, Legal);
  638. setOperationAction(ISD::UADDSAT, VT, Legal);
  639. setOperationAction(ISD::USUBSAT, VT, Legal);
  640. }
  641. // First set operation action for all vector types to expand. Then we
  642. // will selectively turn on ones that can be effectively codegen'd.
  643. for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
  644. // add/sub are legal for all supported vector VT's.
  645. setOperationAction(ISD::ADD, VT, Legal);
  646. setOperationAction(ISD::SUB, VT, Legal);
  647. // For v2i64, these are only valid with P8Vector. This is corrected after
  648. // the loop.
  649. if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
  650. setOperationAction(ISD::SMAX, VT, Legal);
  651. setOperationAction(ISD::SMIN, VT, Legal);
  652. setOperationAction(ISD::UMAX, VT, Legal);
  653. setOperationAction(ISD::UMIN, VT, Legal);
  654. }
  655. else {
  656. setOperationAction(ISD::SMAX, VT, Expand);
  657. setOperationAction(ISD::SMIN, VT, Expand);
  658. setOperationAction(ISD::UMAX, VT, Expand);
  659. setOperationAction(ISD::UMIN, VT, Expand);
  660. }
  661. if (Subtarget.hasVSX()) {
  662. setOperationAction(ISD::FMAXNUM, VT, Legal);
  663. setOperationAction(ISD::FMINNUM, VT, Legal);
  664. }
  665. // Vector instructions introduced in P8
  666. if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
  667. setOperationAction(ISD::CTPOP, VT, Legal);
  668. setOperationAction(ISD::CTLZ, VT, Legal);
  669. }
  670. else {
  671. setOperationAction(ISD::CTPOP, VT, Expand);
  672. setOperationAction(ISD::CTLZ, VT, Expand);
  673. }
  674. // Vector instructions introduced in P9
  675. if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
  676. setOperationAction(ISD::CTTZ, VT, Legal);
  677. else
  678. setOperationAction(ISD::CTTZ, VT, Expand);
  679. // We promote all shuffles to v16i8.
  680. setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
  681. AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
  682. // We promote all non-typed operations to v4i32.
  683. setOperationAction(ISD::AND , VT, Promote);
  684. AddPromotedToType (ISD::AND , VT, MVT::v4i32);
  685. setOperationAction(ISD::OR , VT, Promote);
  686. AddPromotedToType (ISD::OR , VT, MVT::v4i32);
  687. setOperationAction(ISD::XOR , VT, Promote);
  688. AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
  689. setOperationAction(ISD::LOAD , VT, Promote);
  690. AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
  691. setOperationAction(ISD::SELECT, VT, Promote);
  692. AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
  693. setOperationAction(ISD::VSELECT, VT, Legal);
  694. setOperationAction(ISD::SELECT_CC, VT, Promote);
  695. AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
  696. setOperationAction(ISD::STORE, VT, Promote);
  697. AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
  698. // No other operations are legal.
  699. setOperationAction(ISD::MUL , VT, Expand);
  700. setOperationAction(ISD::SDIV, VT, Expand);
  701. setOperationAction(ISD::SREM, VT, Expand);
  702. setOperationAction(ISD::UDIV, VT, Expand);
  703. setOperationAction(ISD::UREM, VT, Expand);
  704. setOperationAction(ISD::FDIV, VT, Expand);
  705. setOperationAction(ISD::FREM, VT, Expand);
  706. setOperationAction(ISD::FNEG, VT, Expand);
  707. setOperationAction(ISD::FSQRT, VT, Expand);
  708. setOperationAction(ISD::FLOG, VT, Expand);
  709. setOperationAction(ISD::FLOG10, VT, Expand);
  710. setOperationAction(ISD::FLOG2, VT, Expand);
  711. setOperationAction(ISD::FEXP, VT, Expand);
  712. setOperationAction(ISD::FEXP2, VT, Expand);
  713. setOperationAction(ISD::FSIN, VT, Expand);
  714. setOperationAction(ISD::FCOS, VT, Expand);
  715. setOperationAction(ISD::FABS, VT, Expand);
  716. setOperationAction(ISD::FFLOOR, VT, Expand);
  717. setOperationAction(ISD::FCEIL, VT, Expand);
  718. setOperationAction(ISD::FTRUNC, VT, Expand);
  719. setOperationAction(ISD::FRINT, VT, Expand);
  720. setOperationAction(ISD::FNEARBYINT, VT, Expand);
  721. setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
  722. setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
  723. setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
  724. setOperationAction(ISD::MULHU, VT, Expand);
  725. setOperationAction(ISD::MULHS, VT, Expand);
  726. setOperationAction(ISD::UMUL_LOHI, VT, Expand);
  727. setOperationAction(ISD::SMUL_LOHI, VT, Expand);
  728. setOperationAction(ISD::UDIVREM, VT, Expand);
  729. setOperationAction(ISD::SDIVREM, VT, Expand);
  730. setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
  731. setOperationAction(ISD::FPOW, VT, Expand);
  732. setOperationAction(ISD::BSWAP, VT, Expand);
  733. setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
  734. setOperationAction(ISD::ROTL, VT, Expand);
  735. setOperationAction(ISD::ROTR, VT, Expand);
  736. for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
  737. setTruncStoreAction(VT, InnerVT, Expand);
  738. setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
  739. setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
  740. setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
  741. }
  742. }
  743. setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
  744. if (!Subtarget.hasP8Vector()) {
  745. setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
  746. setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
  747. setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
  748. setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
  749. }
  750. // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
  751. // with merges, splats, etc.
  752. setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
  753. // Vector truncates to sub-word integer that fit in an Altivec/VSX register
  754. // are cheap, so handle them before they get expanded to scalar.
  755. setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
  756. setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
  757. setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
  758. setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
  759. setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
  760. setOperationAction(ISD::AND , MVT::v4i32, Legal);
  761. setOperationAction(ISD::OR , MVT::v4i32, Legal);
  762. setOperationAction(ISD::XOR , MVT::v4i32, Legal);
  763. setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
  764. setOperationAction(ISD::SELECT, MVT::v4i32,
  765. Subtarget.useCRBits() ? Legal : Expand);
  766. setOperationAction(ISD::STORE , MVT::v4i32, Legal);
  767. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
  768. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
  769. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
  770. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
  771. setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
  772. setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
  773. setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
  774. setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
  775. setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
  776. setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
  777. setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
  778. setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
  779. // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
  780. setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
  781. // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
  782. if (Subtarget.hasAltivec())
  783. for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
  784. setOperationAction(ISD::ROTL, VT, Legal);
  785. // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
  786. if (Subtarget.hasP8Altivec())
  787. setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
  788. addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
  789. addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
  790. addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
  791. addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
  792. setOperationAction(ISD::MUL, MVT::v4f32, Legal);
  793. setOperationAction(ISD::FMA, MVT::v4f32, Legal);
  794. if (Subtarget.hasVSX()) {
  795. setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
  796. setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
  797. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
  798. }
  799. if (Subtarget.hasP8Altivec())
  800. setOperationAction(ISD::MUL, MVT::v4i32, Legal);
  801. else
  802. setOperationAction(ISD::MUL, MVT::v4i32, Custom);
  803. if (Subtarget.isISA3_1()) {
  804. setOperationAction(ISD::MUL, MVT::v2i64, Legal);
  805. setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
  806. setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
  807. setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
  808. setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
  809. setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
  810. setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
  811. setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
  812. setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
  813. setOperationAction(ISD::UREM, MVT::v2i64, Legal);
  814. setOperationAction(ISD::SREM, MVT::v2i64, Legal);
  815. setOperationAction(ISD::UREM, MVT::v4i32, Legal);
  816. setOperationAction(ISD::SREM, MVT::v4i32, Legal);
  817. setOperationAction(ISD::UREM, MVT::v1i128, Legal);
  818. setOperationAction(ISD::SREM, MVT::v1i128, Legal);
  819. setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
  820. setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
  821. setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
  822. }
  823. setOperationAction(ISD::MUL, MVT::v8i16, Legal);
  824. setOperationAction(ISD::MUL, MVT::v16i8, Custom);
  825. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
  826. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
  827. setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
  828. setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
  829. setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
  830. setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
  831. // Altivec does not contain unordered floating-point compare instructions
  832. setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
  833. setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
  834. setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
  835. setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
  836. if (Subtarget.hasVSX()) {
  837. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
  838. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
  839. if (Subtarget.hasP8Vector()) {
  840. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
  841. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
  842. }
  843. if (Subtarget.hasDirectMove() && isPPC64) {
  844. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
  845. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
  846. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
  847. setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
  848. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
  849. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
  850. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
  851. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
  852. }
  853. setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
  854. // The nearbyint variants are not allowed to raise the inexact exception
  855. // so we can only code-gen them with unsafe math.
  856. if (TM.Options.UnsafeFPMath) {
  857. setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
  858. setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
  859. }
  860. setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
  861. setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
  862. setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
  863. setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
  864. setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
  865. setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
  866. setOperationAction(ISD::FROUND, MVT::f64, Legal);
  867. setOperationAction(ISD::FRINT, MVT::f64, Legal);
  868. setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
  869. setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
  870. setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
  871. setOperationAction(ISD::FROUND, MVT::f32, Legal);
  872. setOperationAction(ISD::FRINT, MVT::f32, Legal);
  873. setOperationAction(ISD::MUL, MVT::v2f64, Legal);
  874. setOperationAction(ISD::FMA, MVT::v2f64, Legal);
  875. setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
  876. setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
  877. // Share the Altivec comparison restrictions.
  878. setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
  879. setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
  880. setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
  881. setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
  882. setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
  883. setOperationAction(ISD::STORE, MVT::v2f64, Legal);
  884. setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
  885. if (Subtarget.hasP8Vector())
  886. addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
  887. addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
  888. addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
  889. addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
  890. addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
  891. if (Subtarget.hasP8Altivec()) {
  892. setOperationAction(ISD::SHL, MVT::v2i64, Legal);
  893. setOperationAction(ISD::SRA, MVT::v2i64, Legal);
  894. setOperationAction(ISD::SRL, MVT::v2i64, Legal);
  895. // 128 bit shifts can be accomplished via 3 instructions for SHL and
  896. // SRL, but not for SRA because of the instructions available:
  897. // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
  898. // doing
  899. setOperationAction(ISD::SHL, MVT::v1i128, Expand);
  900. setOperationAction(ISD::SRL, MVT::v1i128, Expand);
  901. setOperationAction(ISD::SRA, MVT::v1i128, Expand);
  902. setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
  903. }
  904. else {
  905. setOperationAction(ISD::SHL, MVT::v2i64, Expand);
  906. setOperationAction(ISD::SRA, MVT::v2i64, Expand);
  907. setOperationAction(ISD::SRL, MVT::v2i64, Expand);
  908. setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
  909. // VSX v2i64 only supports non-arithmetic operations.
  910. setOperationAction(ISD::ADD, MVT::v2i64, Expand);
  911. setOperationAction(ISD::SUB, MVT::v2i64, Expand);
  912. }
  913. if (Subtarget.isISA3_1())
  914. setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
  915. else
  916. setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
  917. setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
  918. AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
  919. setOperationAction(ISD::STORE, MVT::v2i64, Promote);
  920. AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
  921. setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
  922. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
  923. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
  924. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
  925. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
  926. setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
  927. setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
  928. setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
  929. setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
  930. // Custom handling for partial vectors of integers converted to
  931. // floating point. We already have optimal handling for v2i32 through
  932. // the DAG combine, so those aren't necessary.
  933. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
  934. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
  935. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
  936. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
  937. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
  938. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
  939. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
  940. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
  941. setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
  942. setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
  943. setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
  944. setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
  945. setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
  946. setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
  947. setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
  948. setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
  949. setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
  950. setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
  951. setOperationAction(ISD::FABS, MVT::v4f32, Legal);
  952. setOperationAction(ISD::FABS, MVT::v2f64, Legal);
  953. setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
  954. setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
  955. setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
  956. setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
  957. // Handle constrained floating-point operations of vector.
  958. // The predictor is `hasVSX` because altivec instruction has
  959. // no exception but VSX vector instruction has.
  960. setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
  961. setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
  962. setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
  963. setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
  964. setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
  965. setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
  966. setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
  967. setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
  968. setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
  969. setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
  970. setOperationAction(ISD::STRICT_FCEIL, MVT::v4f32, Legal);
  971. setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
  972. setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
  973. setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
  974. setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
  975. setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
  976. setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
  977. setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
  978. setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
  979. setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
  980. setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
  981. setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
  982. setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
  983. setOperationAction(ISD::STRICT_FCEIL, MVT::v2f64, Legal);
  984. setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
  985. setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
  986. addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
  987. addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
  988. for (MVT FPT : MVT::fp_valuetypes())
  989. setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
  990. // Expand the SELECT to SELECT_CC
  991. setOperationAction(ISD::SELECT, MVT::f128, Expand);
  992. setTruncStoreAction(MVT::f128, MVT::f64, Expand);
  993. setTruncStoreAction(MVT::f128, MVT::f32, Expand);
  994. // No implementation for these ops for PowerPC.
  995. setOperationAction(ISD::FSIN, MVT::f128, Expand);
  996. setOperationAction(ISD::FCOS, MVT::f128, Expand);
  997. setOperationAction(ISD::FPOW, MVT::f128, Expand);
  998. setOperationAction(ISD::FPOWI, MVT::f128, Expand);
  999. setOperationAction(ISD::FREM, MVT::f128, Expand);
  1000. }
  1001. if (Subtarget.hasP8Altivec()) {
  1002. addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
  1003. addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
  1004. }
  1005. if (Subtarget.hasP9Vector()) {
  1006. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
  1007. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
  1008. // 128 bit shifts can be accomplished via 3 instructions for SHL and
  1009. // SRL, but not for SRA because of the instructions available:
  1010. // VS{RL} and VS{RL}O.
  1011. setOperationAction(ISD::SHL, MVT::v1i128, Legal);
  1012. setOperationAction(ISD::SRL, MVT::v1i128, Legal);
  1013. setOperationAction(ISD::SRA, MVT::v1i128, Expand);
  1014. setOperationAction(ISD::FADD, MVT::f128, Legal);
  1015. setOperationAction(ISD::FSUB, MVT::f128, Legal);
  1016. setOperationAction(ISD::FDIV, MVT::f128, Legal);
  1017. setOperationAction(ISD::FMUL, MVT::f128, Legal);
  1018. setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
  1019. setOperationAction(ISD::FMA, MVT::f128, Legal);
  1020. setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
  1021. setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
  1022. setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
  1023. setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
  1024. setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
  1025. setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
  1026. setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
  1027. setOperationAction(ISD::FRINT, MVT::f128, Legal);
  1028. setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
  1029. setOperationAction(ISD::FCEIL, MVT::f128, Legal);
  1030. setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
  1031. setOperationAction(ISD::FROUND, MVT::f128, Legal);
  1032. setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
  1033. setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
  1034. setOperationAction(ISD::BITCAST, MVT::i128, Custom);
  1035. // Handle constrained floating-point operations of fp128
  1036. setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
  1037. setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
  1038. setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
  1039. setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
  1040. setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
  1041. setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
  1042. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
  1043. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
  1044. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
  1045. setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
  1046. setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
  1047. setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
  1048. setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
  1049. setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
  1050. setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
  1051. setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
  1052. setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
  1053. setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
  1054. setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
  1055. setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
  1056. } else if (Subtarget.hasVSX()) {
  1057. setOperationAction(ISD::LOAD, MVT::f128, Promote);
  1058. setOperationAction(ISD::STORE, MVT::f128, Promote);
  1059. AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
  1060. AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
  1061. // Set FADD/FSUB as libcall to avoid the legalizer to expand the
  1062. // fp_to_uint and int_to_fp.
  1063. setOperationAction(ISD::FADD, MVT::f128, LibCall);
  1064. setOperationAction(ISD::FSUB, MVT::f128, LibCall);
  1065. setOperationAction(ISD::FMUL, MVT::f128, Expand);
  1066. setOperationAction(ISD::FDIV, MVT::f128, Expand);
  1067. setOperationAction(ISD::FNEG, MVT::f128, Expand);
  1068. setOperationAction(ISD::FABS, MVT::f128, Expand);
  1069. setOperationAction(ISD::FSQRT, MVT::f128, Expand);
  1070. setOperationAction(ISD::FMA, MVT::f128, Expand);
  1071. setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
  1072. // Expand the fp_extend if the target type is fp128.
  1073. setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
  1074. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
  1075. // Expand the fp_round if the source type is fp128.
  1076. for (MVT VT : {MVT::f32, MVT::f64}) {
  1077. setOperationAction(ISD::FP_ROUND, VT, Custom);
  1078. setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
  1079. }
  1080. setOperationAction(ISD::SETCC, MVT::f128, Custom);
  1081. setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
  1082. setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
  1083. setOperationAction(ISD::BR_CC, MVT::f128, Expand);
  1084. // Lower following f128 select_cc pattern:
  1085. // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
  1086. setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
  1087. // We need to handle f128 SELECT_CC with integer result type.
  1088. setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
  1089. setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
  1090. }
  1091. if (Subtarget.hasP9Altivec()) {
  1092. if (Subtarget.isISA3_1()) {
  1093. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
  1094. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal);
  1095. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal);
  1096. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
  1097. } else {
  1098. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
  1099. setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
  1100. }
  1101. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Legal);
  1102. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
  1103. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
  1104. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Legal);
  1105. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
  1106. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
  1107. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
  1108. }
  1109. }
  1110. if (Subtarget.pairedVectorMemops()) {
  1111. addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
  1112. setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
  1113. setOperationAction(ISD::STORE, MVT::v256i1, Custom);
  1114. }
  1115. if (Subtarget.hasMMA()) {
  1116. addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
  1117. setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
  1118. setOperationAction(ISD::STORE, MVT::v512i1, Custom);
  1119. setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
  1120. }
  1121. if (Subtarget.has64BitSupport())
  1122. setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
  1123. if (Subtarget.isISA3_1())
  1124. setOperationAction(ISD::SRA, MVT::v1i128, Legal);
  1125. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
  1126. if (!isPPC64) {
  1127. setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
  1128. setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
  1129. }
  1130. if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
  1131. setMaxAtomicSizeInBitsSupported(128);
  1132. setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
  1133. setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
  1134. setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
  1135. }
  1136. setBooleanContents(ZeroOrOneBooleanContent);
  1137. if (Subtarget.hasAltivec()) {
  1138. // Altivec instructions set fields to all zeros or all ones.
  1139. setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
  1140. }
  1141. setLibcallName(RTLIB::MULO_I128, nullptr);
  1142. if (!isPPC64) {
  1143. // These libcalls are not available in 32-bit.
  1144. setLibcallName(RTLIB::SHL_I128, nullptr);
  1145. setLibcallName(RTLIB::SRL_I128, nullptr);
  1146. setLibcallName(RTLIB::SRA_I128, nullptr);
  1147. setLibcallName(RTLIB::MUL_I128, nullptr);
  1148. setLibcallName(RTLIB::MULO_I64, nullptr);
  1149. }
  1150. if (!isPPC64)
  1151. setMaxAtomicSizeInBitsSupported(32);
  1152. setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
  1153. // We have target-specific dag combine patterns for the following nodes:
  1154. setTargetDAGCombine(ISD::ADD);
  1155. setTargetDAGCombine(ISD::SHL);
  1156. setTargetDAGCombine(ISD::SRA);
  1157. setTargetDAGCombine(ISD::SRL);
  1158. setTargetDAGCombine(ISD::MUL);
  1159. setTargetDAGCombine(ISD::FMA);
  1160. setTargetDAGCombine(ISD::SINT_TO_FP);
  1161. setTargetDAGCombine(ISD::BUILD_VECTOR);
  1162. if (Subtarget.hasFPCVT())
  1163. setTargetDAGCombine(ISD::UINT_TO_FP);
  1164. setTargetDAGCombine(ISD::LOAD);
  1165. setTargetDAGCombine(ISD::STORE);
  1166. setTargetDAGCombine(ISD::BR_CC);
  1167. if (Subtarget.useCRBits())
  1168. setTargetDAGCombine(ISD::BRCOND);
  1169. setTargetDAGCombine(ISD::BSWAP);
  1170. setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
  1171. setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
  1172. setTargetDAGCombine(ISD::INTRINSIC_VOID);
  1173. setTargetDAGCombine(ISD::SIGN_EXTEND);
  1174. setTargetDAGCombine(ISD::ZERO_EXTEND);
  1175. setTargetDAGCombine(ISD::ANY_EXTEND);
  1176. setTargetDAGCombine(ISD::TRUNCATE);
  1177. setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
  1178. if (Subtarget.useCRBits()) {
  1179. setTargetDAGCombine(ISD::TRUNCATE);
  1180. setTargetDAGCombine(ISD::SETCC);
  1181. setTargetDAGCombine(ISD::SELECT_CC);
  1182. }
  1183. if (Subtarget.hasP9Altivec()) {
  1184. setTargetDAGCombine(ISD::ABS);
  1185. setTargetDAGCombine(ISD::VSELECT);
  1186. }
  1187. setLibcallName(RTLIB::LOG_F128, "logf128");
  1188. setLibcallName(RTLIB::LOG2_F128, "log2f128");
  1189. setLibcallName(RTLIB::LOG10_F128, "log10f128");
  1190. setLibcallName(RTLIB::EXP_F128, "expf128");
  1191. setLibcallName(RTLIB::EXP2_F128, "exp2f128");
  1192. setLibcallName(RTLIB::SIN_F128, "sinf128");
  1193. setLibcallName(RTLIB::COS_F128, "cosf128");
  1194. setLibcallName(RTLIB::POW_F128, "powf128");
  1195. setLibcallName(RTLIB::FMIN_F128, "fminf128");
  1196. setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
  1197. setLibcallName(RTLIB::REM_F128, "fmodf128");
  1198. setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
  1199. setLibcallName(RTLIB::CEIL_F128, "ceilf128");
  1200. setLibcallName(RTLIB::FLOOR_F128, "floorf128");
  1201. setLibcallName(RTLIB::TRUNC_F128, "truncf128");
  1202. setLibcallName(RTLIB::ROUND_F128, "roundf128");
  1203. setLibcallName(RTLIB::LROUND_F128, "lroundf128");
  1204. setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
  1205. setLibcallName(RTLIB::RINT_F128, "rintf128");
  1206. setLibcallName(RTLIB::LRINT_F128, "lrintf128");
  1207. setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
  1208. setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
  1209. setLibcallName(RTLIB::FMA_F128, "fmaf128");
  1210. // With 32 condition bits, we don't need to sink (and duplicate) compares
  1211. // aggressively in CodeGenPrep.
  1212. if (Subtarget.useCRBits()) {
  1213. setHasMultipleConditionRegisters();
  1214. setJumpIsExpensive();
  1215. }
  1216. setMinFunctionAlignment(Align(4));
  1217. switch (Subtarget.getCPUDirective()) {
  1218. default: break;
  1219. case PPC::DIR_970:
  1220. case PPC::DIR_A2:
  1221. case PPC::DIR_E500:
  1222. case PPC::DIR_E500mc:
  1223. case PPC::DIR_E5500:
  1224. case PPC::DIR_PWR4:
  1225. case PPC::DIR_PWR5:
  1226. case PPC::DIR_PWR5X:
  1227. case PPC::DIR_PWR6:
  1228. case PPC::DIR_PWR6X:
  1229. case PPC::DIR_PWR7:
  1230. case PPC::DIR_PWR8:
  1231. case PPC::DIR_PWR9:
  1232. case PPC::DIR_PWR10:
  1233. case PPC::DIR_PWR_FUTURE:
  1234. setPrefLoopAlignment(Align(16));
  1235. setPrefFunctionAlignment(Align(16));
  1236. break;
  1237. }
  1238. if (Subtarget.enableMachineScheduler())
  1239. setSchedulingPreference(Sched::Source);
  1240. else
  1241. setSchedulingPreference(Sched::Hybrid);
  1242. computeRegisterProperties(STI.getRegisterInfo());
  1243. // The Freescale cores do better with aggressive inlining of memcpy and
  1244. // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
  1245. if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
  1246. Subtarget.getCPUDirective() == PPC::DIR_E5500) {
  1247. MaxStoresPerMemset = 32;
  1248. MaxStoresPerMemsetOptSize = 16;
  1249. MaxStoresPerMemcpy = 32;
  1250. MaxStoresPerMemcpyOptSize = 8;
  1251. MaxStoresPerMemmove = 32;
  1252. MaxStoresPerMemmoveOptSize = 8;
  1253. } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
  1254. // The A2 also benefits from (very) aggressive inlining of memcpy and
  1255. // friends. The overhead of a the function call, even when warm, can be
  1256. // over one hundred cycles.
  1257. MaxStoresPerMemset = 128;
  1258. MaxStoresPerMemcpy = 128;
  1259. MaxStoresPerMemmove = 128;
  1260. MaxLoadsPerMemcmp = 128;
  1261. } else {
  1262. MaxLoadsPerMemcmp = 8;
  1263. MaxLoadsPerMemcmpOptSize = 4;
  1264. }
  1265. IsStrictFPEnabled = true;
  1266. // Let the subtarget (CPU) decide if a predictable select is more expensive
  1267. // than the corresponding branch. This information is used in CGP to decide
  1268. // when to convert selects into branches.
  1269. PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
  1270. }
  1271. // *********************************** NOTE ************************************
  1272. // For selecting load and store instructions, the addressing modes are defined
  1273. // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
  1274. // patterns to match the load the store instructions.
  1275. //
  1276. // The TD definitions for the addressing modes correspond to their respective
  1277. // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
  1278. // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
  1279. // address mode flags of a particular node. Afterwards, the computed address
  1280. // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
  1281. // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
  1282. // accordingly, based on the preferred addressing mode.
  1283. //
  1284. // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
  1285. // MemOpFlags contains all the possible flags that can be used to compute the
  1286. // optimal addressing mode for load and store instructions.
  1287. // AddrMode contains all the possible load and store addressing modes available
  1288. // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
  1289. //
  1290. // When adding new load and store instructions, it is possible that new address
  1291. // flags may need to be added into MemOpFlags, and a new addressing mode will
  1292. // need to be added to AddrMode. An entry of the new addressing mode (consisting
  1293. // of the minimal and main distinguishing address flags for the new load/store
  1294. // instructions) will need to be added into initializeAddrModeMap() below.
  1295. // Finally, when adding new addressing modes, the getAddrModeForFlags() will
  1296. // need to be updated to account for selecting the optimal addressing mode.
  1297. // *****************************************************************************
  1298. /// Initialize the map that relates the different addressing modes of the load
  1299. /// and store instructions to a set of flags. This ensures the load/store
  1300. /// instruction is correctly matched during instruction selection.
  1301. void PPCTargetLowering::initializeAddrModeMap() {
  1302. AddrModesMap[PPC::AM_DForm] = {
  1303. // LWZ, STW
  1304. PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
  1305. PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
  1306. PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
  1307. PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
  1308. // LBZ, LHZ, STB, STH
  1309. PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
  1310. PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
  1311. PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
  1312. PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
  1313. // LHA
  1314. PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
  1315. PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
  1316. PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
  1317. PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
  1318. // LFS, LFD, STFS, STFD
  1319. PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
  1320. PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
  1321. PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
  1322. PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
  1323. };
  1324. AddrModesMap[PPC::AM_DSForm] = {
  1325. // LWA
  1326. PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
  1327. PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
  1328. PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
  1329. // LD, STD
  1330. PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
  1331. PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
  1332. PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
  1333. // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
  1334. PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
  1335. PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
  1336. PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
  1337. };
  1338. AddrModesMap[PPC::AM_DQForm] = {
  1339. // LXV, STXV
  1340. PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
  1341. PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
  1342. PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
  1343. };
  1344. AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
  1345. PPC::MOF_SubtargetP10};
  1346. // TODO: Add mapping for quadword load/store.
  1347. }
  1348. /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
  1349. /// the desired ByVal argument alignment.
  1350. static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
  1351. if (MaxAlign == MaxMaxAlign)
  1352. return;
  1353. if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
  1354. if (MaxMaxAlign >= 32 &&
  1355. VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
  1356. MaxAlign = Align(32);
  1357. else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
  1358. MaxAlign < 16)
  1359. MaxAlign = Align(16);
  1360. } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  1361. Align EltAlign;
  1362. getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
  1363. if (EltAlign > MaxAlign)
  1364. MaxAlign = EltAlign;
  1365. } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
  1366. for (auto *EltTy : STy->elements()) {
  1367. Align EltAlign;
  1368. getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
  1369. if (EltAlign > MaxAlign)
  1370. MaxAlign = EltAlign;
  1371. if (MaxAlign == MaxMaxAlign)
  1372. break;
  1373. }
  1374. }
  1375. }
  1376. /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
  1377. /// function arguments in the caller parameter area.
  1378. uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
  1379. const DataLayout &DL) const {
  1380. // 16byte and wider vectors are passed on 16byte boundary.
  1381. // The rest is 8 on PPC64 and 4 on PPC32 boundary.
  1382. Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
  1383. if (Subtarget.hasAltivec())
  1384. getMaxByValAlign(Ty, Alignment, Align(16));
  1385. return Alignment.value();
  1386. }
  1387. bool PPCTargetLowering::useSoftFloat() const {
  1388. return Subtarget.useSoftFloat();
  1389. }
  1390. bool PPCTargetLowering::hasSPE() const {
  1391. return Subtarget.hasSPE();
  1392. }
  1393. bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
  1394. return VT.isScalarInteger();
  1395. }
  1396. const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
  1397. switch ((PPCISD::NodeType)Opcode) {
  1398. case PPCISD::FIRST_NUMBER: break;
  1399. case PPCISD::FSEL: return "PPCISD::FSEL";
  1400. case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP";
  1401. case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP";
  1402. case PPCISD::FCFID: return "PPCISD::FCFID";
  1403. case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
  1404. case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
  1405. case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
  1406. case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
  1407. case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
  1408. case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
  1409. case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
  1410. case PPCISD::FP_TO_UINT_IN_VSR:
  1411. return "PPCISD::FP_TO_UINT_IN_VSR,";
  1412. case PPCISD::FP_TO_SINT_IN_VSR:
  1413. return "PPCISD::FP_TO_SINT_IN_VSR";
  1414. case PPCISD::FRE: return "PPCISD::FRE";
  1415. case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
  1416. case PPCISD::FTSQRT:
  1417. return "PPCISD::FTSQRT";
  1418. case PPCISD::FSQRT:
  1419. return "PPCISD::FSQRT";
  1420. case PPCISD::STFIWX: return "PPCISD::STFIWX";
  1421. case PPCISD::VPERM: return "PPCISD::VPERM";
  1422. case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
  1423. case PPCISD::XXSPLTI_SP_TO_DP:
  1424. return "PPCISD::XXSPLTI_SP_TO_DP";
  1425. case PPCISD::XXSPLTI32DX:
  1426. return "PPCISD::XXSPLTI32DX";
  1427. case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
  1428. case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
  1429. case PPCISD::VECSHL: return "PPCISD::VECSHL";
  1430. case PPCISD::CMPB: return "PPCISD::CMPB";
  1431. case PPCISD::Hi: return "PPCISD::Hi";
  1432. case PPCISD::Lo: return "PPCISD::Lo";
  1433. case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
  1434. case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
  1435. case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
  1436. case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
  1437. case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
  1438. case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
  1439. case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
  1440. case PPCISD::SRL: return "PPCISD::SRL";
  1441. case PPCISD::SRA: return "PPCISD::SRA";
  1442. case PPCISD::SHL: return "PPCISD::SHL";
  1443. case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
  1444. case PPCISD::CALL: return "PPCISD::CALL";
  1445. case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
  1446. case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
  1447. case PPCISD::CALL_RM:
  1448. return "PPCISD::CALL_RM";
  1449. case PPCISD::CALL_NOP_RM:
  1450. return "PPCISD::CALL_NOP_RM";
  1451. case PPCISD::CALL_NOTOC_RM:
  1452. return "PPCISD::CALL_NOTOC_RM";
  1453. case PPCISD::MTCTR: return "PPCISD::MTCTR";
  1454. case PPCISD::BCTRL: return "PPCISD::BCTRL";
  1455. case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
  1456. case PPCISD::BCTRL_RM:
  1457. return "PPCISD::BCTRL_RM";
  1458. case PPCISD::BCTRL_LOAD_TOC_RM:
  1459. return "PPCISD::BCTRL_LOAD_TOC_RM";
  1460. case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
  1461. case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
  1462. case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
  1463. case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
  1464. case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
  1465. case PPCISD::MFVSR: return "PPCISD::MFVSR";
  1466. case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
  1467. case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
  1468. case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
  1469. case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
  1470. case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
  1471. return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
  1472. case PPCISD::ANDI_rec_1_EQ_BIT:
  1473. return "PPCISD::ANDI_rec_1_EQ_BIT";
  1474. case PPCISD::ANDI_rec_1_GT_BIT:
  1475. return "PPCISD::ANDI_rec_1_GT_BIT";
  1476. case PPCISD::VCMP: return "PPCISD::VCMP";
  1477. case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
  1478. case PPCISD::LBRX: return "PPCISD::LBRX";
  1479. case PPCISD::STBRX: return "PPCISD::STBRX";
  1480. case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
  1481. case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
  1482. case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
  1483. case PPCISD::STXSIX: return "PPCISD::STXSIX";
  1484. case PPCISD::VEXTS: return "PPCISD::VEXTS";
  1485. case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
  1486. case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
  1487. case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
  1488. case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
  1489. case PPCISD::ST_VSR_SCAL_INT:
  1490. return "PPCISD::ST_VSR_SCAL_INT";
  1491. case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
  1492. case PPCISD::BDNZ: return "PPCISD::BDNZ";
  1493. case PPCISD::BDZ: return "PPCISD::BDZ";
  1494. case PPCISD::MFFS: return "PPCISD::MFFS";
  1495. case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
  1496. case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
  1497. case PPCISD::CR6SET: return "PPCISD::CR6SET";
  1498. case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
  1499. case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
  1500. case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
  1501. case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
  1502. case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
  1503. case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
  1504. case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
  1505. case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
  1506. case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
  1507. case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
  1508. case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
  1509. case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
  1510. case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
  1511. case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
  1512. case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
  1513. case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
  1514. case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
  1515. case PPCISD::PADDI_DTPREL:
  1516. return "PPCISD::PADDI_DTPREL";
  1517. case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
  1518. case PPCISD::SC: return "PPCISD::SC";
  1519. case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
  1520. case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
  1521. case PPCISD::RFEBB: return "PPCISD::RFEBB";
  1522. case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
  1523. case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
  1524. case PPCISD::VABSD: return "PPCISD::VABSD";
  1525. case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
  1526. case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
  1527. case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
  1528. case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
  1529. case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
  1530. case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
  1531. case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
  1532. case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
  1533. return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
  1534. case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
  1535. return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
  1536. case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
  1537. case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
  1538. case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
  1539. case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
  1540. case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
  1541. case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT";
  1542. case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT";
  1543. case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
  1544. case PPCISD::STRICT_FADDRTZ:
  1545. return "PPCISD::STRICT_FADDRTZ";
  1546. case PPCISD::STRICT_FCTIDZ:
  1547. return "PPCISD::STRICT_FCTIDZ";
  1548. case PPCISD::STRICT_FCTIWZ:
  1549. return "PPCISD::STRICT_FCTIWZ";
  1550. case PPCISD::STRICT_FCTIDUZ:
  1551. return "PPCISD::STRICT_FCTIDUZ";
  1552. case PPCISD::STRICT_FCTIWUZ:
  1553. return "PPCISD::STRICT_FCTIWUZ";
  1554. case PPCISD::STRICT_FCFID:
  1555. return "PPCISD::STRICT_FCFID";
  1556. case PPCISD::STRICT_FCFIDU:
  1557. return "PPCISD::STRICT_FCFIDU";
  1558. case PPCISD::STRICT_FCFIDS:
  1559. return "PPCISD::STRICT_FCFIDS";
  1560. case PPCISD::STRICT_FCFIDUS:
  1561. return "PPCISD::STRICT_FCFIDUS";
  1562. case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
  1563. }
  1564. return nullptr;
  1565. }
  1566. EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
  1567. EVT VT) const {
  1568. if (!VT.isVector())
  1569. return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
  1570. return VT.changeVectorElementTypeToInteger();
  1571. }
  1572. bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
  1573. assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
  1574. return true;
  1575. }
  1576. //===----------------------------------------------------------------------===//
  1577. // Node matching predicates, for use by the tblgen matching code.
  1578. //===----------------------------------------------------------------------===//
  1579. /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
  1580. static bool isFloatingPointZero(SDValue Op) {
  1581. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
  1582. return CFP->getValueAPF().isZero();
  1583. else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
  1584. // Maybe this has already been legalized into the constant pool?
  1585. if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
  1586. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
  1587. return CFP->getValueAPF().isZero();
  1588. }
  1589. return false;
  1590. }
  1591. /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
  1592. /// true if Op is undef or if it matches the specified value.
  1593. static bool isConstantOrUndef(int Op, int Val) {
  1594. return Op < 0 || Op == Val;
  1595. }
  1596. /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
  1597. /// VPKUHUM instruction.
  1598. /// The ShuffleKind distinguishes between big-endian operations with
  1599. /// two different inputs (0), either-endian operations with two identical
  1600. /// inputs (1), and little-endian operations with two different inputs (2).
  1601. /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
  1602. bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
  1603. SelectionDAG &DAG) {
  1604. bool IsLE = DAG.getDataLayout().isLittleEndian();
  1605. if (ShuffleKind == 0) {
  1606. if (IsLE)
  1607. return false;
  1608. for (unsigned i = 0; i != 16; ++i)
  1609. if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
  1610. return false;
  1611. } else if (ShuffleKind == 2) {
  1612. if (!IsLE)
  1613. return false;
  1614. for (unsigned i = 0; i != 16; ++i)
  1615. if (!isConstantOrUndef(N->getMaskElt(i), i*2))
  1616. return false;
  1617. } else if (ShuffleKind == 1) {
  1618. unsigned j = IsLE ? 0 : 1;
  1619. for (unsigned i = 0; i != 8; ++i)
  1620. if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
  1621. !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
  1622. return false;
  1623. }
  1624. return true;
  1625. }
  1626. /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
  1627. /// VPKUWUM instruction.
  1628. /// The ShuffleKind distinguishes between big-endian operations with
  1629. /// two different inputs (0), either-endian operations with two identical
  1630. /// inputs (1), and little-endian operations with two different inputs (2).
  1631. /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
  1632. bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
  1633. SelectionDAG &DAG) {
  1634. bool IsLE = DAG.getDataLayout().isLittleEndian();
  1635. if (ShuffleKind == 0) {
  1636. if (IsLE)
  1637. return false;
  1638. for (unsigned i = 0; i != 16; i += 2)
  1639. if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
  1640. !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
  1641. return false;
  1642. } else if (ShuffleKind == 2) {
  1643. if (!IsLE)
  1644. return false;
  1645. for (unsigned i = 0; i != 16; i += 2)
  1646. if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
  1647. !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
  1648. return false;
  1649. } else if (ShuffleKind == 1) {
  1650. unsigned j = IsLE ? 0 : 2;
  1651. for (unsigned i = 0; i != 8; i += 2)
  1652. if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
  1653. !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
  1654. !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
  1655. !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
  1656. return false;
  1657. }
  1658. return true;
  1659. }
  1660. /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
  1661. /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
  1662. /// current subtarget.
  1663. ///
  1664. /// The ShuffleKind distinguishes between big-endian operations with
  1665. /// two different inputs (0), either-endian operations with two identical
  1666. /// inputs (1), and little-endian operations with two different inputs (2).
  1667. /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
  1668. bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
  1669. SelectionDAG &DAG) {
  1670. const PPCSubtarget& Subtarget =
  1671. static_cast<const PPCSubtarget&>(DAG.getSubtarget());
  1672. if (!Subtarget.hasP8Vector())
  1673. return false;
  1674. bool IsLE = DAG.getDataLayout().isLittleEndian();
  1675. if (ShuffleKind == 0) {
  1676. if (IsLE)
  1677. return false;
  1678. for (unsigned i = 0; i != 16; i += 4)
  1679. if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
  1680. !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
  1681. !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
  1682. !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
  1683. return false;
  1684. } else if (ShuffleKind == 2) {
  1685. if (!IsLE)
  1686. return false;
  1687. for (unsigned i = 0; i != 16; i += 4)
  1688. if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
  1689. !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
  1690. !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
  1691. !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
  1692. return false;
  1693. } else if (ShuffleKind == 1) {
  1694. unsigned j = IsLE ? 0 : 4;
  1695. for (unsigned i = 0; i != 8; i += 4)
  1696. if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
  1697. !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
  1698. !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
  1699. !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
  1700. !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
  1701. !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
  1702. !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
  1703. !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
  1704. return false;
  1705. }
  1706. return true;
  1707. }
  1708. /// isVMerge - Common function, used to match vmrg* shuffles.
  1709. ///
  1710. static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
  1711. unsigned LHSStart, unsigned RHSStart) {
  1712. if (N->getValueType(0) != MVT::v16i8)
  1713. return false;
  1714. assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
  1715. "Unsupported merge size!");
  1716. for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
  1717. for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
  1718. if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
  1719. LHSStart+j+i*UnitSize) ||
  1720. !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
  1721. RHSStart+j+i*UnitSize))
  1722. return false;
  1723. }
  1724. return true;
  1725. }
  1726. /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
  1727. /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
  1728. /// The ShuffleKind distinguishes between big-endian merges with two
  1729. /// different inputs (0), either-endian merges with two identical inputs (1),
  1730. /// and little-endian merges with two different inputs (2). For the latter,
  1731. /// the input operands are swapped (see PPCInstrAltivec.td).
  1732. bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
  1733. unsigned ShuffleKind, SelectionDAG &DAG) {
  1734. if (DAG.getDataLayout().isLittleEndian()) {
  1735. if (ShuffleKind == 1) // unary
  1736. return isVMerge(N, UnitSize, 0, 0);
  1737. else if (ShuffleKind == 2) // swapped
  1738. return isVMerge(N, UnitSize, 0, 16);
  1739. else
  1740. return false;
  1741. } else {
  1742. if (ShuffleKind == 1) // unary
  1743. return isVMerge(N, UnitSize, 8, 8);
  1744. else if (ShuffleKind == 0) // normal
  1745. return isVMerge(N, UnitSize, 8, 24);
  1746. else
  1747. return false;
  1748. }
  1749. }
  1750. /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
  1751. /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
  1752. /// The ShuffleKind distinguishes between big-endian merges with two
  1753. /// different inputs (0), either-endian merges with two identical inputs (1),
  1754. /// and little-endian merges with two different inputs (2). For the latter,
  1755. /// the input operands are swapped (see PPCInstrAltivec.td).
  1756. bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
  1757. unsigned ShuffleKind, SelectionDAG &DAG) {
  1758. if (DAG.getDataLayout().isLittleEndian()) {
  1759. if (ShuffleKind == 1) // unary
  1760. return isVMerge(N, UnitSize, 8, 8);
  1761. else if (ShuffleKind == 2) // swapped
  1762. return isVMerge(N, UnitSize, 8, 24);
  1763. else
  1764. return false;
  1765. } else {
  1766. if (ShuffleKind == 1) // unary
  1767. return isVMerge(N, UnitSize, 0, 0);
  1768. else if (ShuffleKind == 0) // normal
  1769. return isVMerge(N, UnitSize, 0, 16);
  1770. else
  1771. return false;
  1772. }
  1773. }
  1774. /**
  1775. * Common function used to match vmrgew and vmrgow shuffles
  1776. *
  1777. * The indexOffset determines whether to look for even or odd words in
  1778. * the shuffle mask. This is based on the of the endianness of the target
  1779. * machine.
  1780. * - Little Endian:
  1781. * - Use offset of 0 to check for odd elements
  1782. * - Use offset of 4 to check for even elements
  1783. * - Big Endian:
  1784. * - Use offset of 0 to check for even elements
  1785. * - Use offset of 4 to check for odd elements
  1786. * A detailed description of the vector element ordering for little endian and
  1787. * big endian can be found at
  1788. * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
  1789. * Targeting your applications - what little endian and big endian IBM XL C/C++
  1790. * compiler differences mean to you
  1791. *
  1792. * The mask to the shuffle vector instruction specifies the indices of the
  1793. * elements from the two input vectors to place in the result. The elements are
  1794. * numbered in array-access order, starting with the first vector. These vectors
  1795. * are always of type v16i8, thus each vector will contain 16 elements of size
  1796. * 8. More info on the shuffle vector can be found in the
  1797. * http://llvm.org/docs/LangRef.html#shufflevector-instruction
  1798. * Language Reference.
  1799. *
  1800. * The RHSStartValue indicates whether the same input vectors are used (unary)
  1801. * or two different input vectors are used, based on the following:
  1802. * - If the instruction uses the same vector for both inputs, the range of the
  1803. * indices will be 0 to 15. In this case, the RHSStart value passed should
  1804. * be 0.
  1805. * - If the instruction has two different vectors then the range of the
  1806. * indices will be 0 to 31. In this case, the RHSStart value passed should
  1807. * be 16 (indices 0-15 specify elements in the first vector while indices 16
  1808. * to 31 specify elements in the second vector).
  1809. *
  1810. * \param[in] N The shuffle vector SD Node to analyze
  1811. * \param[in] IndexOffset Specifies whether to look for even or odd elements
  1812. * \param[in] RHSStartValue Specifies the starting index for the righthand input
  1813. * vector to the shuffle_vector instruction
  1814. * \return true iff this shuffle vector represents an even or odd word merge
  1815. */
  1816. static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
  1817. unsigned RHSStartValue) {
  1818. if (N->getValueType(0) != MVT::v16i8)
  1819. return false;
  1820. for (unsigned i = 0; i < 2; ++i)
  1821. for (unsigned j = 0; j < 4; ++j)
  1822. if (!isConstantOrUndef(N->getMaskElt(i*4+j),
  1823. i*RHSStartValue+j+IndexOffset) ||
  1824. !isConstantOrUndef(N->getMaskElt(i*4+j+8),
  1825. i*RHSStartValue+j+IndexOffset+8))
  1826. return false;
  1827. return true;
  1828. }
  1829. /**
  1830. * Determine if the specified shuffle mask is suitable for the vmrgew or
  1831. * vmrgow instructions.
  1832. *
  1833. * \param[in] N The shuffle vector SD Node to analyze
  1834. * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
  1835. * \param[in] ShuffleKind Identify the type of merge:
  1836. * - 0 = big-endian merge with two different inputs;
  1837. * - 1 = either-endian merge with two identical inputs;
  1838. * - 2 = little-endian merge with two different inputs (inputs are swapped for
  1839. * little-endian merges).
  1840. * \param[in] DAG The current SelectionDAG
  1841. * \return true iff this shuffle mask
  1842. */
  1843. bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
  1844. unsigned ShuffleKind, SelectionDAG &DAG) {
  1845. if (DAG.getDataLayout().isLittleEndian()) {
  1846. unsigned indexOffset = CheckEven ? 4 : 0;
  1847. if (ShuffleKind == 1) // Unary
  1848. return isVMerge(N, indexOffset, 0);
  1849. else if (ShuffleKind == 2) // swapped
  1850. return isVMerge(N, indexOffset, 16);
  1851. else
  1852. return false;
  1853. }
  1854. else {
  1855. unsigned indexOffset = CheckEven ? 0 : 4;
  1856. if (ShuffleKind == 1) // Unary
  1857. return isVMerge(N, indexOffset, 0);
  1858. else if (ShuffleKind == 0) // Normal
  1859. return isVMerge(N, indexOffset, 16);
  1860. else
  1861. return false;
  1862. }
  1863. return false;
  1864. }
  1865. /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
  1866. /// amount, otherwise return -1.
  1867. /// The ShuffleKind distinguishes between big-endian operations with two
  1868. /// different inputs (0), either-endian operations with two identical inputs
  1869. /// (1), and little-endian operations with two different inputs (2). For the
  1870. /// latter, the input operands are swapped (see PPCInstrAltivec.td).
  1871. int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
  1872. SelectionDAG &DAG) {
  1873. if (N->getValueType(0) != MVT::v16i8)
  1874. return -1;
  1875. ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
  1876. // Find the first non-undef value in the shuffle mask.
  1877. unsigned i;
  1878. for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
  1879. /*search*/;
  1880. if (i == 16) return -1; // all undef.
  1881. // Otherwise, check to see if the rest of the elements are consecutively
  1882. // numbered from this value.
  1883. unsigned ShiftAmt = SVOp->getMaskElt(i);
  1884. if (ShiftAmt < i) return -1;
  1885. ShiftAmt -= i;
  1886. bool isLE = DAG.getDataLayout().isLittleEndian();
  1887. if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
  1888. // Check the rest of the elements to see if they are consecutive.
  1889. for (++i; i != 16; ++i)
  1890. if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
  1891. return -1;
  1892. } else if (ShuffleKind == 1) {
  1893. // Check the rest of the elements to see if they are consecutive.
  1894. for (++i; i != 16; ++i)
  1895. if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
  1896. return -1;
  1897. } else
  1898. return -1;
  1899. if (isLE)
  1900. ShiftAmt = 16 - ShiftAmt;
  1901. return ShiftAmt;
  1902. }
  1903. /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
  1904. /// specifies a splat of a single element that is suitable for input to
  1905. /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
  1906. bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
  1907. assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
  1908. EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
  1909. // The consecutive indices need to specify an element, not part of two
  1910. // different elements. So abandon ship early if this isn't the case.
  1911. if (N->getMaskElt(0) % EltSize != 0)
  1912. return false;
  1913. // This is a splat operation if each element of the permute is the same, and
  1914. // if the value doesn't reference the second vector.
  1915. unsigned ElementBase = N->getMaskElt(0);
  1916. // FIXME: Handle UNDEF elements too!
  1917. if (ElementBase >= 16)
  1918. return false;
  1919. // Check that the indices are consecutive, in the case of a multi-byte element
  1920. // splatted with a v16i8 mask.
  1921. for (unsigned i = 1; i != EltSize; ++i)
  1922. if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
  1923. return false;
  1924. for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
  1925. if (N->getMaskElt(i) < 0) continue;
  1926. for (unsigned j = 0; j != EltSize; ++j)
  1927. if (N->getMaskElt(i+j) != N->getMaskElt(j))
  1928. return false;
  1929. }
  1930. return true;
  1931. }
  1932. /// Check that the mask is shuffling N byte elements. Within each N byte
  1933. /// element of the mask, the indices could be either in increasing or
  1934. /// decreasing order as long as they are consecutive.
  1935. /// \param[in] N the shuffle vector SD Node to analyze
  1936. /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
  1937. /// Word/DoubleWord/QuadWord).
  1938. /// \param[in] StepLen the delta indices number among the N byte element, if
  1939. /// the mask is in increasing/decreasing order then it is 1/-1.
  1940. /// \return true iff the mask is shuffling N byte elements.
  1941. static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
  1942. int StepLen) {
  1943. assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
  1944. "Unexpected element width.");
  1945. assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
  1946. unsigned NumOfElem = 16 / Width;
  1947. unsigned MaskVal[16]; // Width is never greater than 16
  1948. for (unsigned i = 0; i < NumOfElem; ++i) {
  1949. MaskVal[0] = N->getMaskElt(i * Width);
  1950. if ((StepLen == 1) && (MaskVal[0] % Width)) {
  1951. return false;
  1952. } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
  1953. return false;
  1954. }
  1955. for (unsigned int j = 1; j < Width; ++j) {
  1956. MaskVal[j] = N->getMaskElt(i * Width + j);
  1957. if (MaskVal[j] != MaskVal[j-1] + StepLen) {
  1958. return false;
  1959. }
  1960. }
  1961. }
  1962. return true;
  1963. }
  1964. bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
  1965. unsigned &InsertAtByte, bool &Swap, bool IsLE) {
  1966. if (!isNByteElemShuffleMask(N, 4, 1))
  1967. return false;
  1968. // Now we look at mask elements 0,4,8,12
  1969. unsigned M0 = N->getMaskElt(0) / 4;
  1970. unsigned M1 = N->getMaskElt(4) / 4;
  1971. unsigned M2 = N->getMaskElt(8) / 4;
  1972. unsigned M3 = N->getMaskElt(12) / 4;
  1973. unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
  1974. unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
  1975. // Below, let H and L be arbitrary elements of the shuffle mask
  1976. // where H is in the range [4,7] and L is in the range [0,3].
  1977. // H, 1, 2, 3 or L, 5, 6, 7
  1978. if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
  1979. (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
  1980. ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
  1981. InsertAtByte = IsLE ? 12 : 0;
  1982. Swap = M0 < 4;
  1983. return true;
  1984. }
  1985. // 0, H, 2, 3 or 4, L, 6, 7
  1986. if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
  1987. (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
  1988. ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
  1989. InsertAtByte = IsLE ? 8 : 4;
  1990. Swap = M1 < 4;
  1991. return true;
  1992. }
  1993. // 0, 1, H, 3 or 4, 5, L, 7
  1994. if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
  1995. (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
  1996. ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
  1997. InsertAtByte = IsLE ? 4 : 8;
  1998. Swap = M2 < 4;
  1999. return true;
  2000. }
  2001. // 0, 1, 2, H or 4, 5, 6, L
  2002. if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
  2003. (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
  2004. ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
  2005. InsertAtByte = IsLE ? 0 : 12;
  2006. Swap = M3 < 4;
  2007. return true;
  2008. }
  2009. // If both vector operands for the shuffle are the same vector, the mask will
  2010. // contain only elements from the first one and the second one will be undef.
  2011. if (N->getOperand(1).isUndef()) {
  2012. ShiftElts = 0;
  2013. Swap = true;
  2014. unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
  2015. if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
  2016. InsertAtByte = IsLE ? 12 : 0;
  2017. return true;
  2018. }
  2019. if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
  2020. InsertAtByte = IsLE ? 8 : 4;
  2021. return true;
  2022. }
  2023. if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
  2024. InsertAtByte = IsLE ? 4 : 8;
  2025. return true;
  2026. }
  2027. if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
  2028. InsertAtByte = IsLE ? 0 : 12;
  2029. return true;
  2030. }
  2031. }
  2032. return false;
  2033. }
  2034. bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
  2035. bool &Swap, bool IsLE) {
  2036. assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
  2037. // Ensure each byte index of the word is consecutive.
  2038. if (!isNByteElemShuffleMask(N, 4, 1))
  2039. return false;
  2040. // Now we look at mask elements 0,4,8,12, which are the beginning of words.
  2041. unsigned M0 = N->getMaskElt(0) / 4;
  2042. unsigned M1 = N->getMaskElt(4) / 4;
  2043. unsigned M2 = N->getMaskElt(8) / 4;
  2044. unsigned M3 = N->getMaskElt(12) / 4;
  2045. // If both vector operands for the shuffle are the same vector, the mask will
  2046. // contain only elements from the first one and the second one will be undef.
  2047. if (N->getOperand(1).isUndef()) {
  2048. assert(M0 < 4 && "Indexing into an undef vector?");
  2049. if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
  2050. return false;
  2051. ShiftElts = IsLE ? (4 - M0) % 4 : M0;
  2052. Swap = false;
  2053. return true;
  2054. }
  2055. // Ensure each word index of the ShuffleVector Mask is consecutive.
  2056. if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
  2057. return false;
  2058. if (IsLE) {
  2059. if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
  2060. // Input vectors don't need to be swapped if the leading element
  2061. // of the result is one of the 3 left elements of the second vector
  2062. // (or if there is no shift to be done at all).
  2063. Swap = false;
  2064. ShiftElts = (8 - M0) % 8;
  2065. } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
  2066. // Input vectors need to be swapped if the leading element
  2067. // of the result is one of the 3 left elements of the first vector
  2068. // (or if we're shifting by 4 - thereby simply swapping the vectors).
  2069. Swap = true;
  2070. ShiftElts = (4 - M0) % 4;
  2071. }
  2072. return true;
  2073. } else { // BE
  2074. if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
  2075. // Input vectors don't need to be swapped if the leading element
  2076. // of the result is one of the 4 elements of the first vector.
  2077. Swap = false;
  2078. ShiftElts = M0;
  2079. } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
  2080. // Input vectors need to be swapped if the leading element
  2081. // of the result is one of the 4 elements of the right vector.
  2082. Swap = true;
  2083. ShiftElts = M0 - 4;
  2084. }
  2085. return true;
  2086. }
  2087. }
  2088. bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
  2089. assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
  2090. if (!isNByteElemShuffleMask(N, Width, -1))
  2091. return false;
  2092. for (int i = 0; i < 16; i += Width)
  2093. if (N->getMaskElt(i) != i + Width - 1)
  2094. return false;
  2095. return true;
  2096. }
  2097. bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
  2098. return isXXBRShuffleMaskHelper(N, 2);
  2099. }
  2100. bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
  2101. return isXXBRShuffleMaskHelper(N, 4);
  2102. }
  2103. bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
  2104. return isXXBRShuffleMaskHelper(N, 8);
  2105. }
  2106. bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
  2107. return isXXBRShuffleMaskHelper(N, 16);
  2108. }
  2109. /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
  2110. /// if the inputs to the instruction should be swapped and set \p DM to the
  2111. /// value for the immediate.
  2112. /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
  2113. /// AND element 0 of the result comes from the first input (LE) or second input
  2114. /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
  2115. /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
  2116. /// mask.
  2117. bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
  2118. bool &Swap, bool IsLE) {
  2119. assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
  2120. // Ensure each byte index of the double word is consecutive.
  2121. if (!isNByteElemShuffleMask(N, 8, 1))
  2122. return false;
  2123. unsigned M0 = N->getMaskElt(0) / 8;
  2124. unsigned M1 = N->getMaskElt(8) / 8;
  2125. assert(((M0 | M1) < 4) && "A mask element out of bounds?");
  2126. // If both vector operands for the shuffle are the same vector, the mask will
  2127. // contain only elements from the first one and the second one will be undef.
  2128. if (N->getOperand(1).isUndef()) {
  2129. if ((M0 | M1) < 2) {
  2130. DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
  2131. Swap = false;
  2132. return true;
  2133. } else
  2134. return false;
  2135. }
  2136. if (IsLE) {
  2137. if (M0 > 1 && M1 < 2) {
  2138. Swap = false;
  2139. } else if (M0 < 2 && M1 > 1) {
  2140. M0 = (M0 + 2) % 4;
  2141. M1 = (M1 + 2) % 4;
  2142. Swap = true;
  2143. } else
  2144. return false;
  2145. // Note: if control flow comes here that means Swap is already set above
  2146. DM = (((~M1) & 1) << 1) + ((~M0) & 1);
  2147. return true;
  2148. } else { // BE
  2149. if (M0 < 2 && M1 > 1) {
  2150. Swap = false;
  2151. } else if (M0 > 1 && M1 < 2) {
  2152. M0 = (M0 + 2) % 4;
  2153. M1 = (M1 + 2) % 4;
  2154. Swap = true;
  2155. } else
  2156. return false;
  2157. // Note: if control flow comes here that means Swap is already set above
  2158. DM = (M0 << 1) + (M1 & 1);
  2159. return true;
  2160. }
  2161. }
  2162. /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
  2163. /// appropriate for PPC mnemonics (which have a big endian bias - namely
  2164. /// elements are counted from the left of the vector register).
  2165. unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
  2166. SelectionDAG &DAG) {
  2167. ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
  2168. assert(isSplatShuffleMask(SVOp, EltSize));
  2169. if (DAG.getDataLayout().isLittleEndian())
  2170. return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
  2171. else
  2172. return SVOp->getMaskElt(0) / EltSize;
  2173. }
  2174. /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
  2175. /// by using a vspltis[bhw] instruction of the specified element size, return
  2176. /// the constant being splatted. The ByteSize field indicates the number of
  2177. /// bytes of each element [124] -> [bhw].
  2178. SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
  2179. SDValue OpVal;
  2180. // If ByteSize of the splat is bigger than the element size of the
  2181. // build_vector, then we have a case where we are checking for a splat where
  2182. // multiple elements of the buildvector are folded together into a single
  2183. // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
  2184. unsigned EltSize = 16/N->getNumOperands();
  2185. if (EltSize < ByteSize) {
  2186. unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
  2187. SDValue UniquedVals[4];
  2188. assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
  2189. // See if all of the elements in the buildvector agree across.
  2190. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  2191. if (N->getOperand(i).isUndef()) continue;
  2192. // If the element isn't a constant, bail fully out.
  2193. if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
  2194. if (!UniquedVals[i&(Multiple-1)].getNode())
  2195. UniquedVals[i&(Multiple-1)] = N->getOperand(i);
  2196. else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
  2197. return SDValue(); // no match.
  2198. }
  2199. // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
  2200. // either constant or undef values that are identical for each chunk. See
  2201. // if these chunks can form into a larger vspltis*.
  2202. // Check to see if all of the leading entries are either 0 or -1. If
  2203. // neither, then this won't fit into the immediate field.
  2204. bool LeadingZero = true;
  2205. bool LeadingOnes = true;
  2206. for (unsigned i = 0; i != Multiple-1; ++i) {
  2207. if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
  2208. LeadingZero &= isNullConstant(UniquedVals[i]);
  2209. LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
  2210. }
  2211. // Finally, check the least significant entry.
  2212. if (LeadingZero) {
  2213. if (!UniquedVals[Multiple-1].getNode())
  2214. return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
  2215. int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
  2216. if (Val < 16) // 0,0,0,4 -> vspltisw(4)
  2217. return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
  2218. }
  2219. if (LeadingOnes) {
  2220. if (!UniquedVals[Multiple-1].getNode())
  2221. return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
  2222. int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
  2223. if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
  2224. return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
  2225. }
  2226. return SDValue();
  2227. }
  2228. // Check to see if this buildvec has a single non-undef value in its elements.
  2229. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  2230. if (N->getOperand(i).isUndef()) continue;
  2231. if (!OpVal.getNode())
  2232. OpVal = N->getOperand(i);
  2233. else if (OpVal != N->getOperand(i))
  2234. return SDValue();
  2235. }
  2236. if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
  2237. unsigned ValSizeInBytes = EltSize;
  2238. uint64_t Value = 0;
  2239. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
  2240. Value = CN->getZExtValue();
  2241. } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
  2242. assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
  2243. Value = FloatToBits(CN->getValueAPF().convertToFloat());
  2244. }
  2245. // If the splat value is larger than the element value, then we can never do
  2246. // this splat. The only case that we could fit the replicated bits into our
  2247. // immediate field for would be zero, and we prefer to use vxor for it.
  2248. if (ValSizeInBytes < ByteSize) return SDValue();
  2249. // If the element value is larger than the splat value, check if it consists
  2250. // of a repeated bit pattern of size ByteSize.
  2251. if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
  2252. return SDValue();
  2253. // Properly sign extend the value.
  2254. int MaskVal = SignExtend32(Value, ByteSize * 8);
  2255. // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
  2256. if (MaskVal == 0) return SDValue();
  2257. // Finally, if this value fits in a 5 bit sext field, return it
  2258. if (SignExtend32<5>(MaskVal) == MaskVal)
  2259. return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
  2260. return SDValue();
  2261. }
  2262. //===----------------------------------------------------------------------===//
  2263. // Addressing Mode Selection
  2264. //===----------------------------------------------------------------------===//
  2265. /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
  2266. /// or 64-bit immediate, and if the value can be accurately represented as a
  2267. /// sign extension from a 16-bit value. If so, this returns true and the
  2268. /// immediate.
  2269. bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
  2270. if (!isa<ConstantSDNode>(N))
  2271. return false;
  2272. Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
  2273. if (N->getValueType(0) == MVT::i32)
  2274. return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
  2275. else
  2276. return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
  2277. }
  2278. bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
  2279. return isIntS16Immediate(Op.getNode(), Imm);
  2280. }
  2281. /// Used when computing address flags for selecting loads and stores.
  2282. /// If we have an OR, check if the LHS and RHS are provably disjoint.
  2283. /// An OR of two provably disjoint values is equivalent to an ADD.
  2284. /// Most PPC load/store instructions compute the effective address as a sum,
  2285. /// so doing this conversion is useful.
  2286. static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
  2287. if (N.getOpcode() != ISD::OR)
  2288. return false;
  2289. KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
  2290. if (!LHSKnown.Zero.getBoolValue())
  2291. return false;
  2292. KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
  2293. return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
  2294. }
  2295. /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
  2296. /// be represented as an indexed [r+r] operation.
  2297. bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
  2298. SDValue &Index,
  2299. SelectionDAG &DAG) const {
  2300. for (SDNode *U : N->uses()) {
  2301. if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
  2302. if (Memop->getMemoryVT() == MVT::f64) {
  2303. Base = N.getOperand(0);
  2304. Index = N.getOperand(1);
  2305. return true;
  2306. }
  2307. }
  2308. }
  2309. return false;
  2310. }
  2311. /// isIntS34Immediate - This method tests if value of node given can be
  2312. /// accurately represented as a sign extension from a 34-bit value. If so,
  2313. /// this returns true and the immediate.
  2314. bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
  2315. if (!isa<ConstantSDNode>(N))
  2316. return false;
  2317. Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
  2318. return isInt<34>(Imm);
  2319. }
  2320. bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
  2321. return isIntS34Immediate(Op.getNode(), Imm);
  2322. }
  2323. /// SelectAddressRegReg - Given the specified addressed, check to see if it
  2324. /// can be represented as an indexed [r+r] operation. Returns false if it
  2325. /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
  2326. /// non-zero and N can be represented by a base register plus a signed 16-bit
  2327. /// displacement, make a more precise judgement by checking (displacement % \p
  2328. /// EncodingAlignment).
  2329. bool PPCTargetLowering::SelectAddressRegReg(
  2330. SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
  2331. MaybeAlign EncodingAlignment) const {
  2332. // If we have a PC Relative target flag don't select as [reg+reg]. It will be
  2333. // a [pc+imm].
  2334. if (SelectAddressPCRel(N, Base))
  2335. return false;
  2336. int16_t Imm = 0;
  2337. if (N.getOpcode() == ISD::ADD) {
  2338. // Is there any SPE load/store (f64), which can't handle 16bit offset?
  2339. // SPE load/store can only handle 8-bit offsets.
  2340. if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
  2341. return true;
  2342. if (isIntS16Immediate(N.getOperand(1), Imm) &&
  2343. (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
  2344. return false; // r+i
  2345. if (N.getOperand(1).getOpcode() == PPCISD::Lo)
  2346. return false; // r+i
  2347. Base = N.getOperand(0);
  2348. Index = N.getOperand(1);
  2349. return true;
  2350. } else if (N.getOpcode() == ISD::OR) {
  2351. if (isIntS16Immediate(N.getOperand(1), Imm) &&
  2352. (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
  2353. return false; // r+i can fold it if we can.
  2354. // If this is an or of disjoint bitfields, we can codegen this as an add
  2355. // (for better address arithmetic) if the LHS and RHS of the OR are provably
  2356. // disjoint.
  2357. KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
  2358. if (LHSKnown.Zero.getBoolValue()) {
  2359. KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
  2360. // If all of the bits are known zero on the LHS or RHS, the add won't
  2361. // carry.
  2362. if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
  2363. Base = N.getOperand(0);
  2364. Index = N.getOperand(1);
  2365. return true;
  2366. }
  2367. }
  2368. }
  2369. return false;
  2370. }
  2371. // If we happen to be doing an i64 load or store into a stack slot that has
  2372. // less than a 4-byte alignment, then the frame-index elimination may need to
  2373. // use an indexed load or store instruction (because the offset may not be a
  2374. // multiple of 4). The extra register needed to hold the offset comes from the
  2375. // register scavenger, and it is possible that the scavenger will need to use
  2376. // an emergency spill slot. As a result, we need to make sure that a spill slot
  2377. // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
  2378. // stack slot.
  2379. static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
  2380. // FIXME: This does not handle the LWA case.
  2381. if (VT != MVT::i64)
  2382. return;
  2383. // NOTE: We'll exclude negative FIs here, which come from argument
  2384. // lowering, because there are no known test cases triggering this problem
  2385. // using packed structures (or similar). We can remove this exclusion if
  2386. // we find such a test case. The reason why this is so test-case driven is
  2387. // because this entire 'fixup' is only to prevent crashes (from the
  2388. // register scavenger) on not-really-valid inputs. For example, if we have:
  2389. // %a = alloca i1
  2390. // %b = bitcast i1* %a to i64*
  2391. // store i64* a, i64 b
  2392. // then the store should really be marked as 'align 1', but is not. If it
  2393. // were marked as 'align 1' then the indexed form would have been
  2394. // instruction-selected initially, and the problem this 'fixup' is preventing
  2395. // won't happen regardless.
  2396. if (FrameIdx < 0)
  2397. return;
  2398. MachineFunction &MF = DAG.getMachineFunction();
  2399. MachineFrameInfo &MFI = MF.getFrameInfo();
  2400. if (MFI.getObjectAlign(FrameIdx) >= Align(4))
  2401. return;
  2402. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  2403. FuncInfo->setHasNonRISpills();
  2404. }
  2405. /// Returns true if the address N can be represented by a base register plus
  2406. /// a signed 16-bit displacement [r+imm], and if it is not better
  2407. /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
  2408. /// displacements that are multiples of that value.
  2409. bool PPCTargetLowering::SelectAddressRegImm(
  2410. SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
  2411. MaybeAlign EncodingAlignment) const {
  2412. // FIXME dl should come from parent load or store, not from address
  2413. SDLoc dl(N);
  2414. // If we have a PC Relative target flag don't select as [reg+imm]. It will be
  2415. // a [pc+imm].
  2416. if (SelectAddressPCRel(N, Base))
  2417. return false;
  2418. // If this can be more profitably realized as r+r, fail.
  2419. if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
  2420. return false;
  2421. if (N.getOpcode() == ISD::ADD) {
  2422. int16_t imm = 0;
  2423. if (isIntS16Immediate(N.getOperand(1), imm) &&
  2424. (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
  2425. Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
  2426. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
  2427. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2428. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  2429. } else {
  2430. Base = N.getOperand(0);
  2431. }
  2432. return true; // [r+i]
  2433. } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
  2434. // Match LOAD (ADD (X, Lo(G))).
  2435. assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
  2436. && "Cannot handle constant offsets yet!");
  2437. Disp = N.getOperand(1).getOperand(0); // The global address.
  2438. assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
  2439. Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
  2440. Disp.getOpcode() == ISD::TargetConstantPool ||
  2441. Disp.getOpcode() == ISD::TargetJumpTable);
  2442. Base = N.getOperand(0);
  2443. return true; // [&g+r]
  2444. }
  2445. } else if (N.getOpcode() == ISD::OR) {
  2446. int16_t imm = 0;
  2447. if (isIntS16Immediate(N.getOperand(1), imm) &&
  2448. (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
  2449. // If this is an or of disjoint bitfields, we can codegen this as an add
  2450. // (for better address arithmetic) if the LHS and RHS of the OR are
  2451. // provably disjoint.
  2452. KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
  2453. if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
  2454. // If all of the bits are known zero on the LHS or RHS, the add won't
  2455. // carry.
  2456. if (FrameIndexSDNode *FI =
  2457. dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
  2458. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2459. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  2460. } else {
  2461. Base = N.getOperand(0);
  2462. }
  2463. Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
  2464. return true;
  2465. }
  2466. }
  2467. } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
  2468. // Loading from a constant address.
  2469. // If this address fits entirely in a 16-bit sext immediate field, codegen
  2470. // this as "d, 0"
  2471. int16_t Imm;
  2472. if (isIntS16Immediate(CN, Imm) &&
  2473. (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
  2474. Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
  2475. Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  2476. CN->getValueType(0));
  2477. return true;
  2478. }
  2479. // Handle 32-bit sext immediates with LIS + addr mode.
  2480. if ((CN->getValueType(0) == MVT::i32 ||
  2481. (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
  2482. (!EncodingAlignment ||
  2483. isAligned(*EncodingAlignment, CN->getZExtValue()))) {
  2484. int Addr = (int)CN->getZExtValue();
  2485. // Otherwise, break this down into an LIS + disp.
  2486. Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
  2487. Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
  2488. MVT::i32);
  2489. unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
  2490. Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
  2491. return true;
  2492. }
  2493. }
  2494. Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
  2495. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
  2496. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2497. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  2498. } else
  2499. Base = N;
  2500. return true; // [r+0]
  2501. }
  2502. /// Similar to the 16-bit case but for instructions that take a 34-bit
  2503. /// displacement field (prefixed loads/stores).
  2504. bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
  2505. SDValue &Base,
  2506. SelectionDAG &DAG) const {
  2507. // Only on 64-bit targets.
  2508. if (N.getValueType() != MVT::i64)
  2509. return false;
  2510. SDLoc dl(N);
  2511. int64_t Imm = 0;
  2512. if (N.getOpcode() == ISD::ADD) {
  2513. if (!isIntS34Immediate(N.getOperand(1), Imm))
  2514. return false;
  2515. Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
  2516. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
  2517. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2518. else
  2519. Base = N.getOperand(0);
  2520. return true;
  2521. }
  2522. if (N.getOpcode() == ISD::OR) {
  2523. if (!isIntS34Immediate(N.getOperand(1), Imm))
  2524. return false;
  2525. // If this is an or of disjoint bitfields, we can codegen this as an add
  2526. // (for better address arithmetic) if the LHS and RHS of the OR are
  2527. // provably disjoint.
  2528. KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
  2529. if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
  2530. return false;
  2531. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
  2532. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  2533. else
  2534. Base = N.getOperand(0);
  2535. Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
  2536. return true;
  2537. }
  2538. if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
  2539. Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
  2540. Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
  2541. return true;
  2542. }
  2543. return false;
  2544. }
  2545. /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
  2546. /// represented as an indexed [r+r] operation.
  2547. bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
  2548. SDValue &Index,
  2549. SelectionDAG &DAG) const {
  2550. // Check to see if we can easily represent this as an [r+r] address. This
  2551. // will fail if it thinks that the address is more profitably represented as
  2552. // reg+imm, e.g. where imm = 0.
  2553. if (SelectAddressRegReg(N, Base, Index, DAG))
  2554. return true;
  2555. // If the address is the result of an add, we will utilize the fact that the
  2556. // address calculation includes an implicit add. However, we can reduce
  2557. // register pressure if we do not materialize a constant just for use as the
  2558. // index register. We only get rid of the add if it is not an add of a
  2559. // value and a 16-bit signed constant and both have a single use.
  2560. int16_t imm = 0;
  2561. if (N.getOpcode() == ISD::ADD &&
  2562. (!isIntS16Immediate(N.getOperand(1), imm) ||
  2563. !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
  2564. Base = N.getOperand(0);
  2565. Index = N.getOperand(1);
  2566. return true;
  2567. }
  2568. // Otherwise, do it the hard way, using R0 as the base register.
  2569. Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  2570. N.getValueType());
  2571. Index = N;
  2572. return true;
  2573. }
  2574. template <typename Ty> static bool isValidPCRelNode(SDValue N) {
  2575. Ty *PCRelCand = dyn_cast<Ty>(N);
  2576. return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
  2577. }
  2578. /// Returns true if this address is a PC Relative address.
  2579. /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
  2580. /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
  2581. bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
  2582. // This is a materialize PC Relative node. Always select this as PC Relative.
  2583. Base = N;
  2584. if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
  2585. return true;
  2586. if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
  2587. isValidPCRelNode<GlobalAddressSDNode>(N) ||
  2588. isValidPCRelNode<JumpTableSDNode>(N) ||
  2589. isValidPCRelNode<BlockAddressSDNode>(N))
  2590. return true;
  2591. return false;
  2592. }
  2593. /// Returns true if we should use a direct load into vector instruction
  2594. /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
  2595. static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
  2596. // If there are any other uses other than scalar to vector, then we should
  2597. // keep it as a scalar load -> direct move pattern to prevent multiple
  2598. // loads.
  2599. LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
  2600. if (!LD)
  2601. return false;
  2602. EVT MemVT = LD->getMemoryVT();
  2603. if (!MemVT.isSimple())
  2604. return false;
  2605. switch(MemVT.getSimpleVT().SimpleTy) {
  2606. case MVT::i64:
  2607. break;
  2608. case MVT::i32:
  2609. if (!ST.hasP8Vector())
  2610. return false;
  2611. break;
  2612. case MVT::i16:
  2613. case MVT::i8:
  2614. if (!ST.hasP9Vector())
  2615. return false;
  2616. break;
  2617. default:
  2618. return false;
  2619. }
  2620. SDValue LoadedVal(N, 0);
  2621. if (!LoadedVal.hasOneUse())
  2622. return false;
  2623. for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
  2624. UI != UE; ++UI)
  2625. if (UI.getUse().get().getResNo() == 0 &&
  2626. UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
  2627. UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
  2628. return false;
  2629. return true;
  2630. }
  2631. /// getPreIndexedAddressParts - returns true by value, base pointer and
  2632. /// offset pointer and addressing mode by reference if the node's address
  2633. /// can be legally represented as pre-indexed load / store address.
  2634. bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
  2635. SDValue &Offset,
  2636. ISD::MemIndexedMode &AM,
  2637. SelectionDAG &DAG) const {
  2638. if (DisablePPCPreinc) return false;
  2639. bool isLoad = true;
  2640. SDValue Ptr;
  2641. EVT VT;
  2642. unsigned Alignment;
  2643. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  2644. Ptr = LD->getBasePtr();
  2645. VT = LD->getMemoryVT();
  2646. Alignment = LD->getAlignment();
  2647. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  2648. Ptr = ST->getBasePtr();
  2649. VT = ST->getMemoryVT();
  2650. Alignment = ST->getAlignment();
  2651. isLoad = false;
  2652. } else
  2653. return false;
  2654. // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
  2655. // instructions because we can fold these into a more efficient instruction
  2656. // instead, (such as LXSD).
  2657. if (isLoad && usePartialVectorLoads(N, Subtarget)) {
  2658. return false;
  2659. }
  2660. // PowerPC doesn't have preinc load/store instructions for vectors
  2661. if (VT.isVector())
  2662. return false;
  2663. if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
  2664. // Common code will reject creating a pre-inc form if the base pointer
  2665. // is a frame index, or if N is a store and the base pointer is either
  2666. // the same as or a predecessor of the value being stored. Check for
  2667. // those situations here, and try with swapped Base/Offset instead.
  2668. bool Swap = false;
  2669. if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
  2670. Swap = true;
  2671. else if (!isLoad) {
  2672. SDValue Val = cast<StoreSDNode>(N)->getValue();
  2673. if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
  2674. Swap = true;
  2675. }
  2676. if (Swap)
  2677. std::swap(Base, Offset);
  2678. AM = ISD::PRE_INC;
  2679. return true;
  2680. }
  2681. // LDU/STU can only handle immediates that are a multiple of 4.
  2682. if (VT != MVT::i64) {
  2683. if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
  2684. return false;
  2685. } else {
  2686. // LDU/STU need an address with at least 4-byte alignment.
  2687. if (Alignment < 4)
  2688. return false;
  2689. if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
  2690. return false;
  2691. }
  2692. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  2693. // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
  2694. // sext i32 to i64 when addr mode is r+i.
  2695. if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
  2696. LD->getExtensionType() == ISD::SEXTLOAD &&
  2697. isa<ConstantSDNode>(Offset))
  2698. return false;
  2699. }
  2700. AM = ISD::PRE_INC;
  2701. return true;
  2702. }
  2703. //===----------------------------------------------------------------------===//
  2704. // LowerOperation implementation
  2705. //===----------------------------------------------------------------------===//
  2706. /// Return true if we should reference labels using a PICBase, set the HiOpFlags
  2707. /// and LoOpFlags to the target MO flags.
  2708. static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
  2709. unsigned &HiOpFlags, unsigned &LoOpFlags,
  2710. const GlobalValue *GV = nullptr) {
  2711. HiOpFlags = PPCII::MO_HA;
  2712. LoOpFlags = PPCII::MO_LO;
  2713. // Don't use the pic base if not in PIC relocation model.
  2714. if (IsPIC) {
  2715. HiOpFlags |= PPCII::MO_PIC_FLAG;
  2716. LoOpFlags |= PPCII::MO_PIC_FLAG;
  2717. }
  2718. }
  2719. static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
  2720. SelectionDAG &DAG) {
  2721. SDLoc DL(HiPart);
  2722. EVT PtrVT = HiPart.getValueType();
  2723. SDValue Zero = DAG.getConstant(0, DL, PtrVT);
  2724. SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
  2725. SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
  2726. // With PIC, the first instruction is actually "GR+hi(&G)".
  2727. if (isPIC)
  2728. Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
  2729. DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
  2730. // Generate non-pic code that has direct accesses to the constant pool.
  2731. // The address of the global is just (hi(&g)+lo(&g)).
  2732. return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
  2733. }
  2734. static void setUsesTOCBasePtr(MachineFunction &MF) {
  2735. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  2736. FuncInfo->setUsesTOCBasePtr();
  2737. }
  2738. static void setUsesTOCBasePtr(SelectionDAG &DAG) {
  2739. setUsesTOCBasePtr(DAG.getMachineFunction());
  2740. }
  2741. SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
  2742. SDValue GA) const {
  2743. const bool Is64Bit = Subtarget.isPPC64();
  2744. EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
  2745. SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
  2746. : Subtarget.isAIXABI()
  2747. ? DAG.getRegister(PPC::R2, VT)
  2748. : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
  2749. SDValue Ops[] = { GA, Reg };
  2750. return DAG.getMemIntrinsicNode(
  2751. PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
  2752. MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
  2753. MachineMemOperand::MOLoad);
  2754. }
  2755. SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
  2756. SelectionDAG &DAG) const {
  2757. EVT PtrVT = Op.getValueType();
  2758. ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
  2759. const Constant *C = CP->getConstVal();
  2760. // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
  2761. // The actual address of the GlobalValue is stored in the TOC.
  2762. if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
  2763. if (Subtarget.isUsingPCRelativeCalls()) {
  2764. SDLoc DL(CP);
  2765. EVT Ty = getPointerTy(DAG.getDataLayout());
  2766. SDValue ConstPool = DAG.getTargetConstantPool(
  2767. C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
  2768. return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
  2769. }
  2770. setUsesTOCBasePtr(DAG);
  2771. SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
  2772. return getTOCEntry(DAG, SDLoc(CP), GA);
  2773. }
  2774. unsigned MOHiFlag, MOLoFlag;
  2775. bool IsPIC = isPositionIndependent();
  2776. getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
  2777. if (IsPIC && Subtarget.isSVR4ABI()) {
  2778. SDValue GA =
  2779. DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
  2780. return getTOCEntry(DAG, SDLoc(CP), GA);
  2781. }
  2782. SDValue CPIHi =
  2783. DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
  2784. SDValue CPILo =
  2785. DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
  2786. return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
  2787. }
  2788. // For 64-bit PowerPC, prefer the more compact relative encodings.
  2789. // This trades 32 bits per jump table entry for one or two instructions
  2790. // on the jump site.
  2791. unsigned PPCTargetLowering::getJumpTableEncoding() const {
  2792. if (isJumpTableRelative())
  2793. return MachineJumpTableInfo::EK_LabelDifference32;
  2794. return TargetLowering::getJumpTableEncoding();
  2795. }
  2796. bool PPCTargetLowering::isJumpTableRelative() const {
  2797. if (UseAbsoluteJumpTables)
  2798. return false;
  2799. if (Subtarget.isPPC64() || Subtarget.isAIXABI())
  2800. return true;
  2801. return TargetLowering::isJumpTableRelative();
  2802. }
  2803. SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
  2804. SelectionDAG &DAG) const {
  2805. if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
  2806. return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
  2807. switch (getTargetMachine().getCodeModel()) {
  2808. case CodeModel::Small:
  2809. case CodeModel::Medium:
  2810. return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
  2811. default:
  2812. return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
  2813. getPointerTy(DAG.getDataLayout()));
  2814. }
  2815. }
  2816. const MCExpr *
  2817. PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
  2818. unsigned JTI,
  2819. MCContext &Ctx) const {
  2820. if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
  2821. return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
  2822. switch (getTargetMachine().getCodeModel()) {
  2823. case CodeModel::Small:
  2824. case CodeModel::Medium:
  2825. return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
  2826. default:
  2827. return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
  2828. }
  2829. }
  2830. SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
  2831. EVT PtrVT = Op.getValueType();
  2832. JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
  2833. // isUsingPCRelativeCalls() returns true when PCRelative is enabled
  2834. if (Subtarget.isUsingPCRelativeCalls()) {
  2835. SDLoc DL(JT);
  2836. EVT Ty = getPointerTy(DAG.getDataLayout());
  2837. SDValue GA =
  2838. DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
  2839. SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
  2840. return MatAddr;
  2841. }
  2842. // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
  2843. // The actual address of the GlobalValue is stored in the TOC.
  2844. if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
  2845. setUsesTOCBasePtr(DAG);
  2846. SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
  2847. return getTOCEntry(DAG, SDLoc(JT), GA);
  2848. }
  2849. unsigned MOHiFlag, MOLoFlag;
  2850. bool IsPIC = isPositionIndependent();
  2851. getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
  2852. if (IsPIC && Subtarget.isSVR4ABI()) {
  2853. SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
  2854. PPCII::MO_PIC_FLAG);
  2855. return getTOCEntry(DAG, SDLoc(GA), GA);
  2856. }
  2857. SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
  2858. SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
  2859. return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
  2860. }
  2861. SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
  2862. SelectionDAG &DAG) const {
  2863. EVT PtrVT = Op.getValueType();
  2864. BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
  2865. const BlockAddress *BA = BASDN->getBlockAddress();
  2866. // isUsingPCRelativeCalls() returns true when PCRelative is enabled
  2867. if (Subtarget.isUsingPCRelativeCalls()) {
  2868. SDLoc DL(BASDN);
  2869. EVT Ty = getPointerTy(DAG.getDataLayout());
  2870. SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
  2871. PPCII::MO_PCREL_FLAG);
  2872. SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
  2873. return MatAddr;
  2874. }
  2875. // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
  2876. // The actual BlockAddress is stored in the TOC.
  2877. if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
  2878. setUsesTOCBasePtr(DAG);
  2879. SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
  2880. return getTOCEntry(DAG, SDLoc(BASDN), GA);
  2881. }
  2882. // 32-bit position-independent ELF stores the BlockAddress in the .got.
  2883. if (Subtarget.is32BitELFABI() && isPositionIndependent())
  2884. return getTOCEntry(
  2885. DAG, SDLoc(BASDN),
  2886. DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
  2887. unsigned MOHiFlag, MOLoFlag;
  2888. bool IsPIC = isPositionIndependent();
  2889. getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
  2890. SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
  2891. SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
  2892. return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
  2893. }
  2894. SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
  2895. SelectionDAG &DAG) const {
  2896. if (Subtarget.isAIXABI())
  2897. return LowerGlobalTLSAddressAIX(Op, DAG);
  2898. return LowerGlobalTLSAddressLinux(Op, DAG);
  2899. }
  2900. SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
  2901. SelectionDAG &DAG) const {
  2902. GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  2903. if (DAG.getTarget().useEmulatedTLS())
  2904. report_fatal_error("Emulated TLS is not yet supported on AIX");
  2905. SDLoc dl(GA);
  2906. const GlobalValue *GV = GA->getGlobal();
  2907. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  2908. // The general-dynamic model is the only access model supported for now, so
  2909. // all the GlobalTLSAddress nodes are lowered with this model.
  2910. // We need to generate two TOC entries, one for the variable offset, one for
  2911. // the region handle. The global address for the TOC entry of the region
  2912. // handle is created with the MO_TLSGDM_FLAG flag and the global address
  2913. // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
  2914. SDValue VariableOffsetTGA =
  2915. DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
  2916. SDValue RegionHandleTGA =
  2917. DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
  2918. SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
  2919. SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
  2920. return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
  2921. RegionHandle);
  2922. }
  2923. SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
  2924. SelectionDAG &DAG) const {
  2925. // FIXME: TLS addresses currently use medium model code sequences,
  2926. // which is the most useful form. Eventually support for small and
  2927. // large models could be added if users need it, at the cost of
  2928. // additional complexity.
  2929. GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  2930. if (DAG.getTarget().useEmulatedTLS())
  2931. return LowerToTLSEmulatedModel(GA, DAG);
  2932. SDLoc dl(GA);
  2933. const GlobalValue *GV = GA->getGlobal();
  2934. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  2935. bool is64bit = Subtarget.isPPC64();
  2936. const Module *M = DAG.getMachineFunction().getFunction().getParent();
  2937. PICLevel::Level picLevel = M->getPICLevel();
  2938. const TargetMachine &TM = getTargetMachine();
  2939. TLSModel::Model Model = TM.getTLSModel(GV);
  2940. if (Model == TLSModel::LocalExec) {
  2941. if (Subtarget.isUsingPCRelativeCalls()) {
  2942. SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
  2943. SDValue TGA = DAG.getTargetGlobalAddress(
  2944. GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
  2945. SDValue MatAddr =
  2946. DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
  2947. return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
  2948. }
  2949. SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
  2950. PPCII::MO_TPREL_HA);
  2951. SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
  2952. PPCII::MO_TPREL_LO);
  2953. SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
  2954. : DAG.getRegister(PPC::R2, MVT::i32);
  2955. SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
  2956. return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
  2957. }
  2958. if (Model == TLSModel::InitialExec) {
  2959. bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
  2960. SDValue TGA = DAG.getTargetGlobalAddress(
  2961. GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
  2962. SDValue TGATLS = DAG.getTargetGlobalAddress(
  2963. GV, dl, PtrVT, 0,
  2964. IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
  2965. SDValue TPOffset;
  2966. if (IsPCRel) {
  2967. SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
  2968. TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
  2969. MachinePointerInfo());
  2970. } else {
  2971. SDValue GOTPtr;
  2972. if (is64bit) {
  2973. setUsesTOCBasePtr(DAG);
  2974. SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
  2975. GOTPtr =
  2976. DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
  2977. } else {
  2978. if (!TM.isPositionIndependent())
  2979. GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
  2980. else if (picLevel == PICLevel::SmallPIC)
  2981. GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
  2982. else
  2983. GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
  2984. }
  2985. TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
  2986. }
  2987. return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
  2988. }
  2989. if (Model == TLSModel::GeneralDynamic) {
  2990. if (Subtarget.isUsingPCRelativeCalls()) {
  2991. SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
  2992. PPCII::MO_GOT_TLSGD_PCREL_FLAG);
  2993. return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
  2994. }
  2995. SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
  2996. SDValue GOTPtr;
  2997. if (is64bit) {
  2998. setUsesTOCBasePtr(DAG);
  2999. SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
  3000. GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
  3001. GOTReg, TGA);
  3002. } else {
  3003. if (picLevel == PICLevel::SmallPIC)
  3004. GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
  3005. else
  3006. GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
  3007. }
  3008. return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
  3009. GOTPtr, TGA, TGA);
  3010. }
  3011. if (Model == TLSModel::LocalDynamic) {
  3012. if (Subtarget.isUsingPCRelativeCalls()) {
  3013. SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
  3014. PPCII::MO_GOT_TLSLD_PCREL_FLAG);
  3015. SDValue MatPCRel =
  3016. DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
  3017. return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
  3018. }
  3019. SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
  3020. SDValue GOTPtr;
  3021. if (is64bit) {
  3022. setUsesTOCBasePtr(DAG);
  3023. SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
  3024. GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
  3025. GOTReg, TGA);
  3026. } else {
  3027. if (picLevel == PICLevel::SmallPIC)
  3028. GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
  3029. else
  3030. GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
  3031. }
  3032. SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
  3033. PtrVT, GOTPtr, TGA, TGA);
  3034. SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
  3035. PtrVT, TLSAddr, TGA);
  3036. return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
  3037. }
  3038. llvm_unreachable("Unknown TLS model!");
  3039. }
  3040. SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
  3041. SelectionDAG &DAG) const {
  3042. EVT PtrVT = Op.getValueType();
  3043. GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
  3044. SDLoc DL(GSDN);
  3045. const GlobalValue *GV = GSDN->getGlobal();
  3046. // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
  3047. // The actual address of the GlobalValue is stored in the TOC.
  3048. if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
  3049. if (Subtarget.isUsingPCRelativeCalls()) {
  3050. EVT Ty = getPointerTy(DAG.getDataLayout());
  3051. if (isAccessedAsGotIndirect(Op)) {
  3052. SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
  3053. PPCII::MO_PCREL_FLAG |
  3054. PPCII::MO_GOT_FLAG);
  3055. SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
  3056. SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
  3057. MachinePointerInfo());
  3058. return Load;
  3059. } else {
  3060. SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
  3061. PPCII::MO_PCREL_FLAG);
  3062. return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
  3063. }
  3064. }
  3065. setUsesTOCBasePtr(DAG);
  3066. SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
  3067. return getTOCEntry(DAG, DL, GA);
  3068. }
  3069. unsigned MOHiFlag, MOLoFlag;
  3070. bool IsPIC = isPositionIndependent();
  3071. getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
  3072. if (IsPIC && Subtarget.isSVR4ABI()) {
  3073. SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
  3074. GSDN->getOffset(),
  3075. PPCII::MO_PIC_FLAG);
  3076. return getTOCEntry(DAG, DL, GA);
  3077. }
  3078. SDValue GAHi =
  3079. DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
  3080. SDValue GALo =
  3081. DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
  3082. return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
  3083. }
  3084. SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
  3085. bool IsStrict = Op->isStrictFPOpcode();
  3086. ISD::CondCode CC =
  3087. cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
  3088. SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
  3089. SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
  3090. SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
  3091. EVT LHSVT = LHS.getValueType();
  3092. SDLoc dl(Op);
  3093. // Soften the setcc with libcall if it is fp128.
  3094. if (LHSVT == MVT::f128) {
  3095. assert(!Subtarget.hasP9Vector() &&
  3096. "SETCC for f128 is already legal under Power9!");
  3097. softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
  3098. Op->getOpcode() == ISD::STRICT_FSETCCS);
  3099. if (RHS.getNode())
  3100. LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
  3101. DAG.getCondCode(CC));
  3102. if (IsStrict)
  3103. return DAG.getMergeValues({LHS, Chain}, dl);
  3104. return LHS;
  3105. }
  3106. assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
  3107. if (Op.getValueType() == MVT::v2i64) {
  3108. // When the operands themselves are v2i64 values, we need to do something
  3109. // special because VSX has no underlying comparison operations for these.
  3110. if (LHS.getValueType() == MVT::v2i64) {
  3111. // Equality can be handled by casting to the legal type for Altivec
  3112. // comparisons, everything else needs to be expanded.
  3113. if (CC != ISD::SETEQ && CC != ISD::SETNE)
  3114. return SDValue();
  3115. SDValue SetCC32 = DAG.getSetCC(
  3116. dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
  3117. DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
  3118. int ShuffV[] = {1, 0, 3, 2};
  3119. SDValue Shuff =
  3120. DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
  3121. return DAG.getBitcast(MVT::v2i64,
  3122. DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
  3123. dl, MVT::v4i32, Shuff, SetCC32));
  3124. }
  3125. // We handle most of these in the usual way.
  3126. return Op;
  3127. }
  3128. // If we're comparing for equality to zero, expose the fact that this is
  3129. // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
  3130. // fold the new nodes.
  3131. if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
  3132. return V;
  3133. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
  3134. // Leave comparisons against 0 and -1 alone for now, since they're usually
  3135. // optimized. FIXME: revisit this when we can custom lower all setcc
  3136. // optimizations.
  3137. if (C->isAllOnes() || C->isZero())
  3138. return SDValue();
  3139. }
  3140. // If we have an integer seteq/setne, turn it into a compare against zero
  3141. // by xor'ing the rhs with the lhs, which is faster than setting a
  3142. // condition register, reading it back out, and masking the correct bit. The
  3143. // normal approach here uses sub to do this instead of xor. Using xor exposes
  3144. // the result to other bit-twiddling opportunities.
  3145. if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
  3146. EVT VT = Op.getValueType();
  3147. SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
  3148. return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
  3149. }
  3150. return SDValue();
  3151. }
  3152. SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
  3153. SDNode *Node = Op.getNode();
  3154. EVT VT = Node->getValueType(0);
  3155. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  3156. SDValue InChain = Node->getOperand(0);
  3157. SDValue VAListPtr = Node->getOperand(1);
  3158. const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
  3159. SDLoc dl(Node);
  3160. assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
  3161. // gpr_index
  3162. SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
  3163. VAListPtr, MachinePointerInfo(SV), MVT::i8);
  3164. InChain = GprIndex.getValue(1);
  3165. if (VT == MVT::i64) {
  3166. // Check if GprIndex is even
  3167. SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
  3168. DAG.getConstant(1, dl, MVT::i32));
  3169. SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
  3170. DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
  3171. SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
  3172. DAG.getConstant(1, dl, MVT::i32));
  3173. // Align GprIndex to be even if it isn't
  3174. GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
  3175. GprIndex);
  3176. }
  3177. // fpr index is 1 byte after gpr
  3178. SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
  3179. DAG.getConstant(1, dl, MVT::i32));
  3180. // fpr
  3181. SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
  3182. FprPtr, MachinePointerInfo(SV), MVT::i8);
  3183. InChain = FprIndex.getValue(1);
  3184. SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
  3185. DAG.getConstant(8, dl, MVT::i32));
  3186. SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
  3187. DAG.getConstant(4, dl, MVT::i32));
  3188. // areas
  3189. SDValue OverflowArea =
  3190. DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
  3191. InChain = OverflowArea.getValue(1);
  3192. SDValue RegSaveArea =
  3193. DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
  3194. InChain = RegSaveArea.getValue(1);
  3195. // select overflow_area if index > 8
  3196. SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
  3197. DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
  3198. // adjustment constant gpr_index * 4/8
  3199. SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
  3200. VT.isInteger() ? GprIndex : FprIndex,
  3201. DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
  3202. MVT::i32));
  3203. // OurReg = RegSaveArea + RegConstant
  3204. SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
  3205. RegConstant);
  3206. // Floating types are 32 bytes into RegSaveArea
  3207. if (VT.isFloatingPoint())
  3208. OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
  3209. DAG.getConstant(32, dl, MVT::i32));
  3210. // increase {f,g}pr_index by 1 (or 2 if VT is i64)
  3211. SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  3212. VT.isInteger() ? GprIndex : FprIndex,
  3213. DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
  3214. MVT::i32));
  3215. InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
  3216. VT.isInteger() ? VAListPtr : FprPtr,
  3217. MachinePointerInfo(SV), MVT::i8);
  3218. // determine if we should load from reg_save_area or overflow_area
  3219. SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
  3220. // increase overflow_area by 4/8 if gpr/fpr > 8
  3221. SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
  3222. DAG.getConstant(VT.isInteger() ? 4 : 8,
  3223. dl, MVT::i32));
  3224. OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
  3225. OverflowAreaPlusN);
  3226. InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
  3227. MachinePointerInfo(), MVT::i32);
  3228. return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
  3229. }
  3230. SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
  3231. assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
  3232. // We have to copy the entire va_list struct:
  3233. // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
  3234. return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
  3235. DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
  3236. false, true, false, MachinePointerInfo(),
  3237. MachinePointerInfo());
  3238. }
  3239. SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
  3240. SelectionDAG &DAG) const {
  3241. if (Subtarget.isAIXABI())
  3242. report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
  3243. return Op.getOperand(0);
  3244. }
  3245. SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
  3246. MachineFunction &MF = DAG.getMachineFunction();
  3247. PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
  3248. assert((Op.getOpcode() == ISD::INLINEASM ||
  3249. Op.getOpcode() == ISD::INLINEASM_BR) &&
  3250. "Expecting Inline ASM node.");
  3251. // If an LR store is already known to be required then there is not point in
  3252. // checking this ASM as well.
  3253. if (MFI.isLRStoreRequired())
  3254. return Op;
  3255. // Inline ASM nodes have an optional last operand that is an incoming Flag of
  3256. // type MVT::Glue. We want to ignore this last operand if that is the case.
  3257. unsigned NumOps = Op.getNumOperands();
  3258. if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
  3259. --NumOps;
  3260. // Check all operands that may contain the LR.
  3261. for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
  3262. unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
  3263. unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
  3264. ++i; // Skip the ID value.
  3265. switch (InlineAsm::getKind(Flags)) {
  3266. default:
  3267. llvm_unreachable("Bad flags!");
  3268. case InlineAsm::Kind_RegUse:
  3269. case InlineAsm::Kind_Imm:
  3270. case InlineAsm::Kind_Mem:
  3271. i += NumVals;
  3272. break;
  3273. case InlineAsm::Kind_Clobber:
  3274. case InlineAsm::Kind_RegDef:
  3275. case InlineAsm::Kind_RegDefEarlyClobber: {
  3276. for (; NumVals; --NumVals, ++i) {
  3277. Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
  3278. if (Reg != PPC::LR && Reg != PPC::LR8)
  3279. continue;
  3280. MFI.setLRStoreRequired();
  3281. return Op;
  3282. }
  3283. break;
  3284. }
  3285. }
  3286. }
  3287. return Op;
  3288. }
  3289. SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
  3290. SelectionDAG &DAG) const {
  3291. if (Subtarget.isAIXABI())
  3292. report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
  3293. SDValue Chain = Op.getOperand(0);
  3294. SDValue Trmp = Op.getOperand(1); // trampoline
  3295. SDValue FPtr = Op.getOperand(2); // nested function
  3296. SDValue Nest = Op.getOperand(3); // 'nest' parameter value
  3297. SDLoc dl(Op);
  3298. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  3299. bool isPPC64 = (PtrVT == MVT::i64);
  3300. Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
  3301. TargetLowering::ArgListTy Args;
  3302. TargetLowering::ArgListEntry Entry;
  3303. Entry.Ty = IntPtrTy;
  3304. Entry.Node = Trmp; Args.push_back(Entry);
  3305. // TrampSize == (isPPC64 ? 48 : 40);
  3306. Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
  3307. isPPC64 ? MVT::i64 : MVT::i32);
  3308. Args.push_back(Entry);
  3309. Entry.Node = FPtr; Args.push_back(Entry);
  3310. Entry.Node = Nest; Args.push_back(Entry);
  3311. // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
  3312. TargetLowering::CallLoweringInfo CLI(DAG);
  3313. CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
  3314. CallingConv::C, Type::getVoidTy(*DAG.getContext()),
  3315. DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
  3316. std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
  3317. return CallResult.second;
  3318. }
  3319. SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
  3320. MachineFunction &MF = DAG.getMachineFunction();
  3321. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  3322. EVT PtrVT = getPointerTy(MF.getDataLayout());
  3323. SDLoc dl(Op);
  3324. if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
  3325. // vastart just stores the address of the VarArgsFrameIndex slot into the
  3326. // memory location argument.
  3327. SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
  3328. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  3329. return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
  3330. MachinePointerInfo(SV));
  3331. }
  3332. // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
  3333. // We suppose the given va_list is already allocated.
  3334. //
  3335. // typedef struct {
  3336. // char gpr; /* index into the array of 8 GPRs
  3337. // * stored in the register save area
  3338. // * gpr=0 corresponds to r3,
  3339. // * gpr=1 to r4, etc.
  3340. // */
  3341. // char fpr; /* index into the array of 8 FPRs
  3342. // * stored in the register save area
  3343. // * fpr=0 corresponds to f1,
  3344. // * fpr=1 to f2, etc.
  3345. // */
  3346. // char *overflow_arg_area;
  3347. // /* location on stack that holds
  3348. // * the next overflow argument
  3349. // */
  3350. // char *reg_save_area;
  3351. // /* where r3:r10 and f1:f8 (if saved)
  3352. // * are stored
  3353. // */
  3354. // } va_list[1];
  3355. SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
  3356. SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
  3357. SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
  3358. PtrVT);
  3359. SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
  3360. PtrVT);
  3361. uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
  3362. SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
  3363. uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
  3364. SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
  3365. uint64_t FPROffset = 1;
  3366. SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
  3367. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  3368. // Store first byte : number of int regs
  3369. SDValue firstStore =
  3370. DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
  3371. MachinePointerInfo(SV), MVT::i8);
  3372. uint64_t nextOffset = FPROffset;
  3373. SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
  3374. ConstFPROffset);
  3375. // Store second byte : number of float regs
  3376. SDValue secondStore =
  3377. DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
  3378. MachinePointerInfo(SV, nextOffset), MVT::i8);
  3379. nextOffset += StackOffset;
  3380. nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
  3381. // Store second word : arguments given on stack
  3382. SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
  3383. MachinePointerInfo(SV, nextOffset));
  3384. nextOffset += FrameOffset;
  3385. nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
  3386. // Store third word : arguments given in registers
  3387. return DAG.getStore(thirdStore, dl, FR, nextPtr,
  3388. MachinePointerInfo(SV, nextOffset));
  3389. }
  3390. /// FPR - The set of FP registers that should be allocated for arguments
  3391. /// on Darwin and AIX.
  3392. static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
  3393. PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
  3394. PPC::F11, PPC::F12, PPC::F13};
  3395. /// CalculateStackSlotSize - Calculates the size reserved for this argument on
  3396. /// the stack.
  3397. static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
  3398. unsigned PtrByteSize) {
  3399. unsigned ArgSize = ArgVT.getStoreSize();
  3400. if (Flags.isByVal())
  3401. ArgSize = Flags.getByValSize();
  3402. // Round up to multiples of the pointer size, except for array members,
  3403. // which are always packed.
  3404. if (!Flags.isInConsecutiveRegs())
  3405. ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  3406. return ArgSize;
  3407. }
  3408. /// CalculateStackSlotAlignment - Calculates the alignment of this argument
  3409. /// on the stack.
  3410. static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
  3411. ISD::ArgFlagsTy Flags,
  3412. unsigned PtrByteSize) {
  3413. Align Alignment(PtrByteSize);
  3414. // Altivec parameters are padded to a 16 byte boundary.
  3415. if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
  3416. ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
  3417. ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
  3418. ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
  3419. Alignment = Align(16);
  3420. // ByVal parameters are aligned as requested.
  3421. if (Flags.isByVal()) {
  3422. auto BVAlign = Flags.getNonZeroByValAlign();
  3423. if (BVAlign > PtrByteSize) {
  3424. if (BVAlign.value() % PtrByteSize != 0)
  3425. llvm_unreachable(
  3426. "ByVal alignment is not a multiple of the pointer size");
  3427. Alignment = BVAlign;
  3428. }
  3429. }
  3430. // Array members are always packed to their original alignment.
  3431. if (Flags.isInConsecutiveRegs()) {
  3432. // If the array member was split into multiple registers, the first
  3433. // needs to be aligned to the size of the full type. (Except for
  3434. // ppcf128, which is only aligned as its f64 components.)
  3435. if (Flags.isSplit() && OrigVT != MVT::ppcf128)
  3436. Alignment = Align(OrigVT.getStoreSize());
  3437. else
  3438. Alignment = Align(ArgVT.getStoreSize());
  3439. }
  3440. return Alignment;
  3441. }
  3442. /// CalculateStackSlotUsed - Return whether this argument will use its
  3443. /// stack slot (instead of being passed in registers). ArgOffset,
  3444. /// AvailableFPRs, and AvailableVRs must hold the current argument
  3445. /// position, and will be updated to account for this argument.
  3446. static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
  3447. unsigned PtrByteSize, unsigned LinkageSize,
  3448. unsigned ParamAreaSize, unsigned &ArgOffset,
  3449. unsigned &AvailableFPRs,
  3450. unsigned &AvailableVRs) {
  3451. bool UseMemory = false;
  3452. // Respect alignment of argument on the stack.
  3453. Align Alignment =
  3454. CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
  3455. ArgOffset = alignTo(ArgOffset, Alignment);
  3456. // If there's no space left in the argument save area, we must
  3457. // use memory (this check also catches zero-sized arguments).
  3458. if (ArgOffset >= LinkageSize + ParamAreaSize)
  3459. UseMemory = true;
  3460. // Allocate argument on the stack.
  3461. ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
  3462. if (Flags.isInConsecutiveRegsLast())
  3463. ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  3464. // If we overran the argument save area, we must use memory
  3465. // (this check catches arguments passed partially in memory)
  3466. if (ArgOffset > LinkageSize + ParamAreaSize)
  3467. UseMemory = true;
  3468. // However, if the argument is actually passed in an FPR or a VR,
  3469. // we don't use memory after all.
  3470. if (!Flags.isByVal()) {
  3471. if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
  3472. if (AvailableFPRs > 0) {
  3473. --AvailableFPRs;
  3474. return false;
  3475. }
  3476. if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
  3477. ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
  3478. ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
  3479. ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
  3480. if (AvailableVRs > 0) {
  3481. --AvailableVRs;
  3482. return false;
  3483. }
  3484. }
  3485. return UseMemory;
  3486. }
  3487. /// EnsureStackAlignment - Round stack frame size up from NumBytes to
  3488. /// ensure minimum alignment required for target.
  3489. static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
  3490. unsigned NumBytes) {
  3491. return alignTo(NumBytes, Lowering->getStackAlign());
  3492. }
  3493. SDValue PPCTargetLowering::LowerFormalArguments(
  3494. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  3495. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  3496. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  3497. if (Subtarget.isAIXABI())
  3498. return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
  3499. InVals);
  3500. if (Subtarget.is64BitELFABI())
  3501. return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
  3502. InVals);
  3503. assert(Subtarget.is32BitELFABI());
  3504. return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
  3505. InVals);
  3506. }
  3507. SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
  3508. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  3509. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  3510. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  3511. // 32-bit SVR4 ABI Stack Frame Layout:
  3512. // +-----------------------------------+
  3513. // +--> | Back chain |
  3514. // | +-----------------------------------+
  3515. // | | Floating-point register save area |
  3516. // | +-----------------------------------+
  3517. // | | General register save area |
  3518. // | +-----------------------------------+
  3519. // | | CR save word |
  3520. // | +-----------------------------------+
  3521. // | | VRSAVE save word |
  3522. // | +-----------------------------------+
  3523. // | | Alignment padding |
  3524. // | +-----------------------------------+
  3525. // | | Vector register save area |
  3526. // | +-----------------------------------+
  3527. // | | Local variable space |
  3528. // | +-----------------------------------+
  3529. // | | Parameter list area |
  3530. // | +-----------------------------------+
  3531. // | | LR save word |
  3532. // | +-----------------------------------+
  3533. // SP--> +--- | Back chain |
  3534. // +-----------------------------------+
  3535. //
  3536. // Specifications:
  3537. // System V Application Binary Interface PowerPC Processor Supplement
  3538. // AltiVec Technology Programming Interface Manual
  3539. MachineFunction &MF = DAG.getMachineFunction();
  3540. MachineFrameInfo &MFI = MF.getFrameInfo();
  3541. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  3542. EVT PtrVT = getPointerTy(MF.getDataLayout());
  3543. // Potential tail calls could cause overwriting of argument stack slots.
  3544. bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
  3545. (CallConv == CallingConv::Fast));
  3546. const Align PtrAlign(4);
  3547. // Assign locations to all of the incoming arguments.
  3548. SmallVector<CCValAssign, 16> ArgLocs;
  3549. PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
  3550. *DAG.getContext());
  3551. // Reserve space for the linkage area on the stack.
  3552. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  3553. CCInfo.AllocateStack(LinkageSize, PtrAlign);
  3554. if (useSoftFloat())
  3555. CCInfo.PreAnalyzeFormalArguments(Ins);
  3556. CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
  3557. CCInfo.clearWasPPCF128();
  3558. for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
  3559. CCValAssign &VA = ArgLocs[i];
  3560. // Arguments stored in registers.
  3561. if (VA.isRegLoc()) {
  3562. const TargetRegisterClass *RC;
  3563. EVT ValVT = VA.getValVT();
  3564. switch (ValVT.getSimpleVT().SimpleTy) {
  3565. default:
  3566. llvm_unreachable("ValVT not supported by formal arguments Lowering");
  3567. case MVT::i1:
  3568. case MVT::i32:
  3569. RC = &PPC::GPRCRegClass;
  3570. break;
  3571. case MVT::f32:
  3572. if (Subtarget.hasP8Vector())
  3573. RC = &PPC::VSSRCRegClass;
  3574. else if (Subtarget.hasSPE())
  3575. RC = &PPC::GPRCRegClass;
  3576. else
  3577. RC = &PPC::F4RCRegClass;
  3578. break;
  3579. case MVT::f64:
  3580. if (Subtarget.hasVSX())
  3581. RC = &PPC::VSFRCRegClass;
  3582. else if (Subtarget.hasSPE())
  3583. // SPE passes doubles in GPR pairs.
  3584. RC = &PPC::GPRCRegClass;
  3585. else
  3586. RC = &PPC::F8RCRegClass;
  3587. break;
  3588. case MVT::v16i8:
  3589. case MVT::v8i16:
  3590. case MVT::v4i32:
  3591. RC = &PPC::VRRCRegClass;
  3592. break;
  3593. case MVT::v4f32:
  3594. RC = &PPC::VRRCRegClass;
  3595. break;
  3596. case MVT::v2f64:
  3597. case MVT::v2i64:
  3598. RC = &PPC::VRRCRegClass;
  3599. break;
  3600. }
  3601. SDValue ArgValue;
  3602. // Transform the arguments stored in physical registers into
  3603. // virtual ones.
  3604. if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
  3605. assert(i + 1 < e && "No second half of double precision argument");
  3606. Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
  3607. Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
  3608. SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
  3609. SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
  3610. if (!Subtarget.isLittleEndian())
  3611. std::swap (ArgValueLo, ArgValueHi);
  3612. ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
  3613. ArgValueHi);
  3614. } else {
  3615. Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
  3616. ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
  3617. ValVT == MVT::i1 ? MVT::i32 : ValVT);
  3618. if (ValVT == MVT::i1)
  3619. ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
  3620. }
  3621. InVals.push_back(ArgValue);
  3622. } else {
  3623. // Argument stored in memory.
  3624. assert(VA.isMemLoc());
  3625. // Get the extended size of the argument type in stack
  3626. unsigned ArgSize = VA.getLocVT().getStoreSize();
  3627. // Get the actual size of the argument type
  3628. unsigned ObjSize = VA.getValVT().getStoreSize();
  3629. unsigned ArgOffset = VA.getLocMemOffset();
  3630. // Stack objects in PPC32 are right justified.
  3631. ArgOffset += ArgSize - ObjSize;
  3632. int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
  3633. // Create load nodes to retrieve arguments from the stack.
  3634. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  3635. InVals.push_back(
  3636. DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
  3637. }
  3638. }
  3639. // Assign locations to all of the incoming aggregate by value arguments.
  3640. // Aggregates passed by value are stored in the local variable space of the
  3641. // caller's stack frame, right above the parameter list area.
  3642. SmallVector<CCValAssign, 16> ByValArgLocs;
  3643. CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
  3644. ByValArgLocs, *DAG.getContext());
  3645. // Reserve stack space for the allocations in CCInfo.
  3646. CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
  3647. CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
  3648. // Area that is at least reserved in the caller of this function.
  3649. unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
  3650. MinReservedArea = std::max(MinReservedArea, LinkageSize);
  3651. // Set the size that is at least reserved in caller of this function. Tail
  3652. // call optimized function's reserved stack space needs to be aligned so that
  3653. // taking the difference between two stack areas will result in an aligned
  3654. // stack.
  3655. MinReservedArea =
  3656. EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
  3657. FuncInfo->setMinReservedArea(MinReservedArea);
  3658. SmallVector<SDValue, 8> MemOps;
  3659. // If the function takes variable number of arguments, make a frame index for
  3660. // the start of the first vararg value... for expansion of llvm.va_start.
  3661. if (isVarArg) {
  3662. static const MCPhysReg GPArgRegs[] = {
  3663. PPC::R3, PPC::R4, PPC::R5, PPC::R6,
  3664. PPC::R7, PPC::R8, PPC::R9, PPC::R10,
  3665. };
  3666. const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
  3667. static const MCPhysReg FPArgRegs[] = {
  3668. PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
  3669. PPC::F8
  3670. };
  3671. unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
  3672. if (useSoftFloat() || hasSPE())
  3673. NumFPArgRegs = 0;
  3674. FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
  3675. FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
  3676. // Make room for NumGPArgRegs and NumFPArgRegs.
  3677. int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
  3678. NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
  3679. FuncInfo->setVarArgsStackOffset(
  3680. MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
  3681. CCInfo.getNextStackOffset(), true));
  3682. FuncInfo->setVarArgsFrameIndex(
  3683. MFI.CreateStackObject(Depth, Align(8), false));
  3684. SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
  3685. // The fixed integer arguments of a variadic function are stored to the
  3686. // VarArgsFrameIndex on the stack so that they may be loaded by
  3687. // dereferencing the result of va_next.
  3688. for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
  3689. // Get an existing live-in vreg, or add a new one.
  3690. Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
  3691. if (!VReg)
  3692. VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
  3693. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  3694. SDValue Store =
  3695. DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
  3696. MemOps.push_back(Store);
  3697. // Increment the address by four for the next argument to store
  3698. SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
  3699. FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
  3700. }
  3701. // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
  3702. // is set.
  3703. // The double arguments are stored to the VarArgsFrameIndex
  3704. // on the stack.
  3705. for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
  3706. // Get an existing live-in vreg, or add a new one.
  3707. Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
  3708. if (!VReg)
  3709. VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
  3710. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
  3711. SDValue Store =
  3712. DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
  3713. MemOps.push_back(Store);
  3714. // Increment the address by eight for the next argument to store
  3715. SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
  3716. PtrVT);
  3717. FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
  3718. }
  3719. }
  3720. if (!MemOps.empty())
  3721. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
  3722. return Chain;
  3723. }
  3724. // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
  3725. // value to MVT::i64 and then truncate to the correct register size.
  3726. SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
  3727. EVT ObjectVT, SelectionDAG &DAG,
  3728. SDValue ArgVal,
  3729. const SDLoc &dl) const {
  3730. if (Flags.isSExt())
  3731. ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
  3732. DAG.getValueType(ObjectVT));
  3733. else if (Flags.isZExt())
  3734. ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
  3735. DAG.getValueType(ObjectVT));
  3736. return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
  3737. }
  3738. SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
  3739. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  3740. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  3741. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  3742. // TODO: add description of PPC stack frame format, or at least some docs.
  3743. //
  3744. bool isELFv2ABI = Subtarget.isELFv2ABI();
  3745. bool isLittleEndian = Subtarget.isLittleEndian();
  3746. MachineFunction &MF = DAG.getMachineFunction();
  3747. MachineFrameInfo &MFI = MF.getFrameInfo();
  3748. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  3749. assert(!(CallConv == CallingConv::Fast && isVarArg) &&
  3750. "fastcc not supported on varargs functions");
  3751. EVT PtrVT = getPointerTy(MF.getDataLayout());
  3752. // Potential tail calls could cause overwriting of argument stack slots.
  3753. bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
  3754. (CallConv == CallingConv::Fast));
  3755. unsigned PtrByteSize = 8;
  3756. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  3757. static const MCPhysReg GPR[] = {
  3758. PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  3759. PPC::X7, PPC::X8, PPC::X9, PPC::X10,
  3760. };
  3761. static const MCPhysReg VR[] = {
  3762. PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
  3763. PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
  3764. };
  3765. const unsigned Num_GPR_Regs = array_lengthof(GPR);
  3766. const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
  3767. const unsigned Num_VR_Regs = array_lengthof(VR);
  3768. // Do a first pass over the arguments to determine whether the ABI
  3769. // guarantees that our caller has allocated the parameter save area
  3770. // on its stack frame. In the ELFv1 ABI, this is always the case;
  3771. // in the ELFv2 ABI, it is true if this is a vararg function or if
  3772. // any parameter is located in a stack slot.
  3773. bool HasParameterArea = !isELFv2ABI || isVarArg;
  3774. unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
  3775. unsigned NumBytes = LinkageSize;
  3776. unsigned AvailableFPRs = Num_FPR_Regs;
  3777. unsigned AvailableVRs = Num_VR_Regs;
  3778. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  3779. if (Ins[i].Flags.isNest())
  3780. continue;
  3781. if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
  3782. PtrByteSize, LinkageSize, ParamAreaSize,
  3783. NumBytes, AvailableFPRs, AvailableVRs))
  3784. HasParameterArea = true;
  3785. }
  3786. // Add DAG nodes to load the arguments or copy them out of registers. On
  3787. // entry to a function on PPC, the arguments start after the linkage area,
  3788. // although the first ones are often in registers.
  3789. unsigned ArgOffset = LinkageSize;
  3790. unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
  3791. SmallVector<SDValue, 8> MemOps;
  3792. Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
  3793. unsigned CurArgIdx = 0;
  3794. for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
  3795. SDValue ArgVal;
  3796. bool needsLoad = false;
  3797. EVT ObjectVT = Ins[ArgNo].VT;
  3798. EVT OrigVT = Ins[ArgNo].ArgVT;
  3799. unsigned ObjSize = ObjectVT.getStoreSize();
  3800. unsigned ArgSize = ObjSize;
  3801. ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
  3802. if (Ins[ArgNo].isOrigArg()) {
  3803. std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
  3804. CurArgIdx = Ins[ArgNo].getOrigArgIndex();
  3805. }
  3806. // We re-align the argument offset for each argument, except when using the
  3807. // fast calling convention, when we need to make sure we do that only when
  3808. // we'll actually use a stack slot.
  3809. unsigned CurArgOffset;
  3810. Align Alignment;
  3811. auto ComputeArgOffset = [&]() {
  3812. /* Respect alignment of argument on the stack. */
  3813. Alignment =
  3814. CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
  3815. ArgOffset = alignTo(ArgOffset, Alignment);
  3816. CurArgOffset = ArgOffset;
  3817. };
  3818. if (CallConv != CallingConv::Fast) {
  3819. ComputeArgOffset();
  3820. /* Compute GPR index associated with argument offset. */
  3821. GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
  3822. GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
  3823. }
  3824. // FIXME the codegen can be much improved in some cases.
  3825. // We do not have to keep everything in memory.
  3826. if (Flags.isByVal()) {
  3827. assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
  3828. if (CallConv == CallingConv::Fast)
  3829. ComputeArgOffset();
  3830. // ObjSize is the true size, ArgSize rounded up to multiple of registers.
  3831. ObjSize = Flags.getByValSize();
  3832. ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  3833. // Empty aggregate parameters do not take up registers. Examples:
  3834. // struct { } a;
  3835. // union { } b;
  3836. // int c[0];
  3837. // etc. However, we have to provide a place-holder in InVals, so
  3838. // pretend we have an 8-byte item at the current address for that
  3839. // purpose.
  3840. if (!ObjSize) {
  3841. int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
  3842. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  3843. InVals.push_back(FIN);
  3844. continue;
  3845. }
  3846. // Create a stack object covering all stack doublewords occupied
  3847. // by the argument. If the argument is (fully or partially) on
  3848. // the stack, or if the argument is fully in registers but the
  3849. // caller has allocated the parameter save anyway, we can refer
  3850. // directly to the caller's stack frame. Otherwise, create a
  3851. // local copy in our own frame.
  3852. int FI;
  3853. if (HasParameterArea ||
  3854. ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
  3855. FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
  3856. else
  3857. FI = MFI.CreateStackObject(ArgSize, Alignment, false);
  3858. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  3859. // Handle aggregates smaller than 8 bytes.
  3860. if (ObjSize < PtrByteSize) {
  3861. // The value of the object is its address, which differs from the
  3862. // address of the enclosing doubleword on big-endian systems.
  3863. SDValue Arg = FIN;
  3864. if (!isLittleEndian) {
  3865. SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
  3866. Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
  3867. }
  3868. InVals.push_back(Arg);
  3869. if (GPR_idx != Num_GPR_Regs) {
  3870. Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
  3871. FuncInfo->addLiveInAttr(VReg, Flags);
  3872. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  3873. EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
  3874. SDValue Store =
  3875. DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
  3876. MachinePointerInfo(&*FuncArg), ObjType);
  3877. MemOps.push_back(Store);
  3878. }
  3879. // Whether we copied from a register or not, advance the offset
  3880. // into the parameter save area by a full doubleword.
  3881. ArgOffset += PtrByteSize;
  3882. continue;
  3883. }
  3884. // The value of the object is its address, which is the address of
  3885. // its first stack doubleword.
  3886. InVals.push_back(FIN);
  3887. // Store whatever pieces of the object are in registers to memory.
  3888. for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
  3889. if (GPR_idx == Num_GPR_Regs)
  3890. break;
  3891. Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
  3892. FuncInfo->addLiveInAttr(VReg, Flags);
  3893. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  3894. SDValue Addr = FIN;
  3895. if (j) {
  3896. SDValue Off = DAG.getConstant(j, dl, PtrVT);
  3897. Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
  3898. }
  3899. SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
  3900. MachinePointerInfo(&*FuncArg, j));
  3901. MemOps.push_back(Store);
  3902. ++GPR_idx;
  3903. }
  3904. ArgOffset += ArgSize;
  3905. continue;
  3906. }
  3907. switch (ObjectVT.getSimpleVT().SimpleTy) {
  3908. default: llvm_unreachable("Unhandled argument type!");
  3909. case MVT::i1:
  3910. case MVT::i32:
  3911. case MVT::i64:
  3912. if (Flags.isNest()) {
  3913. // The 'nest' parameter, if any, is passed in R11.
  3914. Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
  3915. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
  3916. if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
  3917. ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
  3918. break;
  3919. }
  3920. // These can be scalar arguments or elements of an integer array type
  3921. // passed directly. Clang may use those instead of "byval" aggregate
  3922. // types to avoid forcing arguments to memory unnecessarily.
  3923. if (GPR_idx != Num_GPR_Regs) {
  3924. Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
  3925. FuncInfo->addLiveInAttr(VReg, Flags);
  3926. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
  3927. if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
  3928. // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
  3929. // value to MVT::i64 and then truncate to the correct register size.
  3930. ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
  3931. } else {
  3932. if (CallConv == CallingConv::Fast)
  3933. ComputeArgOffset();
  3934. needsLoad = true;
  3935. ArgSize = PtrByteSize;
  3936. }
  3937. if (CallConv != CallingConv::Fast || needsLoad)
  3938. ArgOffset += 8;
  3939. break;
  3940. case MVT::f32:
  3941. case MVT::f64:
  3942. // These can be scalar arguments or elements of a float array type
  3943. // passed directly. The latter are used to implement ELFv2 homogenous
  3944. // float aggregates.
  3945. if (FPR_idx != Num_FPR_Regs) {
  3946. unsigned VReg;
  3947. if (ObjectVT == MVT::f32)
  3948. VReg = MF.addLiveIn(FPR[FPR_idx],
  3949. Subtarget.hasP8Vector()
  3950. ? &PPC::VSSRCRegClass
  3951. : &PPC::F4RCRegClass);
  3952. else
  3953. VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
  3954. ? &PPC::VSFRCRegClass
  3955. : &PPC::F8RCRegClass);
  3956. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
  3957. ++FPR_idx;
  3958. } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
  3959. // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
  3960. // once we support fp <-> gpr moves.
  3961. // This can only ever happen in the presence of f32 array types,
  3962. // since otherwise we never run out of FPRs before running out
  3963. // of GPRs.
  3964. Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
  3965. FuncInfo->addLiveInAttr(VReg, Flags);
  3966. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
  3967. if (ObjectVT == MVT::f32) {
  3968. if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
  3969. ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
  3970. DAG.getConstant(32, dl, MVT::i32));
  3971. ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
  3972. }
  3973. ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
  3974. } else {
  3975. if (CallConv == CallingConv::Fast)
  3976. ComputeArgOffset();
  3977. needsLoad = true;
  3978. }
  3979. // When passing an array of floats, the array occupies consecutive
  3980. // space in the argument area; only round up to the next doubleword
  3981. // at the end of the array. Otherwise, each float takes 8 bytes.
  3982. if (CallConv != CallingConv::Fast || needsLoad) {
  3983. ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
  3984. ArgOffset += ArgSize;
  3985. if (Flags.isInConsecutiveRegsLast())
  3986. ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  3987. }
  3988. break;
  3989. case MVT::v4f32:
  3990. case MVT::v4i32:
  3991. case MVT::v8i16:
  3992. case MVT::v16i8:
  3993. case MVT::v2f64:
  3994. case MVT::v2i64:
  3995. case MVT::v1i128:
  3996. case MVT::f128:
  3997. // These can be scalar arguments or elements of a vector array type
  3998. // passed directly. The latter are used to implement ELFv2 homogenous
  3999. // vector aggregates.
  4000. if (VR_idx != Num_VR_Regs) {
  4001. Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
  4002. ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
  4003. ++VR_idx;
  4004. } else {
  4005. if (CallConv == CallingConv::Fast)
  4006. ComputeArgOffset();
  4007. needsLoad = true;
  4008. }
  4009. if (CallConv != CallingConv::Fast || needsLoad)
  4010. ArgOffset += 16;
  4011. break;
  4012. }
  4013. // We need to load the argument to a virtual register if we determined
  4014. // above that we ran out of physical registers of the appropriate type.
  4015. if (needsLoad) {
  4016. if (ObjSize < ArgSize && !isLittleEndian)
  4017. CurArgOffset += ArgSize - ObjSize;
  4018. int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
  4019. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  4020. ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
  4021. }
  4022. InVals.push_back(ArgVal);
  4023. }
  4024. // Area that is at least reserved in the caller of this function.
  4025. unsigned MinReservedArea;
  4026. if (HasParameterArea)
  4027. MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
  4028. else
  4029. MinReservedArea = LinkageSize;
  4030. // Set the size that is at least reserved in caller of this function. Tail
  4031. // call optimized functions' reserved stack space needs to be aligned so that
  4032. // taking the difference between two stack areas will result in an aligned
  4033. // stack.
  4034. MinReservedArea =
  4035. EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
  4036. FuncInfo->setMinReservedArea(MinReservedArea);
  4037. // If the function takes variable number of arguments, make a frame index for
  4038. // the start of the first vararg value... for expansion of llvm.va_start.
  4039. // On ELFv2ABI spec, it writes:
  4040. // C programs that are intended to be *portable* across different compilers
  4041. // and architectures must use the header file <stdarg.h> to deal with variable
  4042. // argument lists.
  4043. if (isVarArg && MFI.hasVAStart()) {
  4044. int Depth = ArgOffset;
  4045. FuncInfo->setVarArgsFrameIndex(
  4046. MFI.CreateFixedObject(PtrByteSize, Depth, true));
  4047. SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
  4048. // If this function is vararg, store any remaining integer argument regs
  4049. // to their spots on the stack so that they may be loaded by dereferencing
  4050. // the result of va_next.
  4051. for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
  4052. GPR_idx < Num_GPR_Regs; ++GPR_idx) {
  4053. Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
  4054. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  4055. SDValue Store =
  4056. DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
  4057. MemOps.push_back(Store);
  4058. // Increment the address by four for the next argument to store
  4059. SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
  4060. FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
  4061. }
  4062. }
  4063. if (!MemOps.empty())
  4064. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
  4065. return Chain;
  4066. }
  4067. /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
  4068. /// adjusted to accommodate the arguments for the tailcall.
  4069. static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
  4070. unsigned ParamSize) {
  4071. if (!isTailCall) return 0;
  4072. PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
  4073. unsigned CallerMinReservedArea = FI->getMinReservedArea();
  4074. int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
  4075. // Remember only if the new adjustment is bigger.
  4076. if (SPDiff < FI->getTailCallSPDelta())
  4077. FI->setTailCallSPDelta(SPDiff);
  4078. return SPDiff;
  4079. }
  4080. static bool isFunctionGlobalAddress(SDValue Callee);
  4081. static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
  4082. const TargetMachine &TM) {
  4083. // It does not make sense to call callsShareTOCBase() with a caller that
  4084. // is PC Relative since PC Relative callers do not have a TOC.
  4085. #ifndef NDEBUG
  4086. const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
  4087. assert(!STICaller->isUsingPCRelativeCalls() &&
  4088. "PC Relative callers do not have a TOC and cannot share a TOC Base");
  4089. #endif
  4090. // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
  4091. // don't have enough information to determine if the caller and callee share
  4092. // the same TOC base, so we have to pessimistically assume they don't for
  4093. // correctness.
  4094. GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
  4095. if (!G)
  4096. return false;
  4097. const GlobalValue *GV = G->getGlobal();
  4098. // If the callee is preemptable, then the static linker will use a plt-stub
  4099. // which saves the toc to the stack, and needs a nop after the call
  4100. // instruction to convert to a toc-restore.
  4101. if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
  4102. return false;
  4103. // Functions with PC Relative enabled may clobber the TOC in the same DSO.
  4104. // We may need a TOC restore in the situation where the caller requires a
  4105. // valid TOC but the callee is PC Relative and does not.
  4106. const Function *F = dyn_cast<Function>(GV);
  4107. const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
  4108. // If we have an Alias we can try to get the function from there.
  4109. if (Alias) {
  4110. const GlobalObject *GlobalObj = Alias->getAliaseeObject();
  4111. F = dyn_cast<Function>(GlobalObj);
  4112. }
  4113. // If we still have no valid function pointer we do not have enough
  4114. // information to determine if the callee uses PC Relative calls so we must
  4115. // assume that it does.
  4116. if (!F)
  4117. return false;
  4118. // If the callee uses PC Relative we cannot guarantee that the callee won't
  4119. // clobber the TOC of the caller and so we must assume that the two
  4120. // functions do not share a TOC base.
  4121. const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
  4122. if (STICallee->isUsingPCRelativeCalls())
  4123. return false;
  4124. // If the GV is not a strong definition then we need to assume it can be
  4125. // replaced by another function at link time. The function that replaces
  4126. // it may not share the same TOC as the caller since the callee may be
  4127. // replaced by a PC Relative version of the same function.
  4128. if (!GV->isStrongDefinitionForLinker())
  4129. return false;
  4130. // The medium and large code models are expected to provide a sufficiently
  4131. // large TOC to provide all data addressing needs of a module with a
  4132. // single TOC.
  4133. if (CodeModel::Medium == TM.getCodeModel() ||
  4134. CodeModel::Large == TM.getCodeModel())
  4135. return true;
  4136. // Any explicitly-specified sections and section prefixes must also match.
  4137. // Also, if we're using -ffunction-sections, then each function is always in
  4138. // a different section (the same is true for COMDAT functions).
  4139. if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
  4140. GV->getSection() != Caller->getSection())
  4141. return false;
  4142. if (const auto *F = dyn_cast<Function>(GV)) {
  4143. if (F->getSectionPrefix() != Caller->getSectionPrefix())
  4144. return false;
  4145. }
  4146. return true;
  4147. }
  4148. static bool
  4149. needStackSlotPassParameters(const PPCSubtarget &Subtarget,
  4150. const SmallVectorImpl<ISD::OutputArg> &Outs) {
  4151. assert(Subtarget.is64BitELFABI());
  4152. const unsigned PtrByteSize = 8;
  4153. const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  4154. static const MCPhysReg GPR[] = {
  4155. PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  4156. PPC::X7, PPC::X8, PPC::X9, PPC::X10,
  4157. };
  4158. static const MCPhysReg VR[] = {
  4159. PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
  4160. PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
  4161. };
  4162. const unsigned NumGPRs = array_lengthof(GPR);
  4163. const unsigned NumFPRs = 13;
  4164. const unsigned NumVRs = array_lengthof(VR);
  4165. const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
  4166. unsigned NumBytes = LinkageSize;
  4167. unsigned AvailableFPRs = NumFPRs;
  4168. unsigned AvailableVRs = NumVRs;
  4169. for (const ISD::OutputArg& Param : Outs) {
  4170. if (Param.Flags.isNest()) continue;
  4171. if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
  4172. LinkageSize, ParamAreaSize, NumBytes,
  4173. AvailableFPRs, AvailableVRs))
  4174. return true;
  4175. }
  4176. return false;
  4177. }
  4178. static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
  4179. if (CB.arg_size() != CallerFn->arg_size())
  4180. return false;
  4181. auto CalleeArgIter = CB.arg_begin();
  4182. auto CalleeArgEnd = CB.arg_end();
  4183. Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
  4184. for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
  4185. const Value* CalleeArg = *CalleeArgIter;
  4186. const Value* CallerArg = &(*CallerArgIter);
  4187. if (CalleeArg == CallerArg)
  4188. continue;
  4189. // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
  4190. // tail call @callee([4 x i64] undef, [4 x i64] %b)
  4191. // }
  4192. // 1st argument of callee is undef and has the same type as caller.
  4193. if (CalleeArg->getType() == CallerArg->getType() &&
  4194. isa<UndefValue>(CalleeArg))
  4195. continue;
  4196. return false;
  4197. }
  4198. return true;
  4199. }
  4200. // Returns true if TCO is possible between the callers and callees
  4201. // calling conventions.
  4202. static bool
  4203. areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
  4204. CallingConv::ID CalleeCC) {
  4205. // Tail calls are possible with fastcc and ccc.
  4206. auto isTailCallableCC = [] (CallingConv::ID CC){
  4207. return CC == CallingConv::C || CC == CallingConv::Fast;
  4208. };
  4209. if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
  4210. return false;
  4211. // We can safely tail call both fastcc and ccc callees from a c calling
  4212. // convention caller. If the caller is fastcc, we may have less stack space
  4213. // than a non-fastcc caller with the same signature so disable tail-calls in
  4214. // that case.
  4215. return CallerCC == CallingConv::C || CallerCC == CalleeCC;
  4216. }
  4217. bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
  4218. SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
  4219. const SmallVectorImpl<ISD::OutputArg> &Outs,
  4220. const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
  4221. bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
  4222. if (DisableSCO && !TailCallOpt) return false;
  4223. // Variadic argument functions are not supported.
  4224. if (isVarArg) return false;
  4225. auto &Caller = DAG.getMachineFunction().getFunction();
  4226. // Check that the calling conventions are compatible for tco.
  4227. if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
  4228. return false;
  4229. // Caller contains any byval parameter is not supported.
  4230. if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
  4231. return false;
  4232. // Callee contains any byval parameter is not supported, too.
  4233. // Note: This is a quick work around, because in some cases, e.g.
  4234. // caller's stack size > callee's stack size, we are still able to apply
  4235. // sibling call optimization. For example, gcc is able to do SCO for caller1
  4236. // in the following example, but not for caller2.
  4237. // struct test {
  4238. // long int a;
  4239. // char ary[56];
  4240. // } gTest;
  4241. // __attribute__((noinline)) int callee(struct test v, struct test *b) {
  4242. // b->a = v.a;
  4243. // return 0;
  4244. // }
  4245. // void caller1(struct test a, struct test c, struct test *b) {
  4246. // callee(gTest, b); }
  4247. // void caller2(struct test *b) { callee(gTest, b); }
  4248. if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
  4249. return false;
  4250. // If callee and caller use different calling conventions, we cannot pass
  4251. // parameters on stack since offsets for the parameter area may be different.
  4252. if (Caller.getCallingConv() != CalleeCC &&
  4253. needStackSlotPassParameters(Subtarget, Outs))
  4254. return false;
  4255. // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
  4256. // the caller and callee share the same TOC for TCO/SCO. If the caller and
  4257. // callee potentially have different TOC bases then we cannot tail call since
  4258. // we need to restore the TOC pointer after the call.
  4259. // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
  4260. // We cannot guarantee this for indirect calls or calls to external functions.
  4261. // When PC-Relative addressing is used, the concept of the TOC is no longer
  4262. // applicable so this check is not required.
  4263. // Check first for indirect calls.
  4264. if (!Subtarget.isUsingPCRelativeCalls() &&
  4265. !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
  4266. return false;
  4267. // Check if we share the TOC base.
  4268. if (!Subtarget.isUsingPCRelativeCalls() &&
  4269. !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
  4270. return false;
  4271. // TCO allows altering callee ABI, so we don't have to check further.
  4272. if (CalleeCC == CallingConv::Fast && TailCallOpt)
  4273. return true;
  4274. if (DisableSCO) return false;
  4275. // If callee use the same argument list that caller is using, then we can
  4276. // apply SCO on this case. If it is not, then we need to check if callee needs
  4277. // stack for passing arguments.
  4278. // PC Relative tail calls may not have a CallBase.
  4279. // If there is no CallBase we cannot verify if we have the same argument
  4280. // list so assume that we don't have the same argument list.
  4281. if (CB && !hasSameArgumentList(&Caller, *CB) &&
  4282. needStackSlotPassParameters(Subtarget, Outs))
  4283. return false;
  4284. else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
  4285. return false;
  4286. return true;
  4287. }
  4288. /// IsEligibleForTailCallOptimization - Check whether the call is eligible
  4289. /// for tail call optimization. Targets which want to do tail call
  4290. /// optimization should implement this function.
  4291. bool
  4292. PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
  4293. CallingConv::ID CalleeCC,
  4294. bool isVarArg,
  4295. const SmallVectorImpl<ISD::InputArg> &Ins,
  4296. SelectionDAG& DAG) const {
  4297. if (!getTargetMachine().Options.GuaranteedTailCallOpt)
  4298. return false;
  4299. // Variable argument functions are not supported.
  4300. if (isVarArg)
  4301. return false;
  4302. MachineFunction &MF = DAG.getMachineFunction();
  4303. CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
  4304. if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
  4305. // Functions containing by val parameters are not supported.
  4306. for (unsigned i = 0; i != Ins.size(); i++) {
  4307. ISD::ArgFlagsTy Flags = Ins[i].Flags;
  4308. if (Flags.isByVal()) return false;
  4309. }
  4310. // Non-PIC/GOT tail calls are supported.
  4311. if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
  4312. return true;
  4313. // At the moment we can only do local tail calls (in same module, hidden
  4314. // or protected) if we are generating PIC.
  4315. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
  4316. return G->getGlobal()->hasHiddenVisibility()
  4317. || G->getGlobal()->hasProtectedVisibility();
  4318. }
  4319. return false;
  4320. }
  4321. /// isCallCompatibleAddress - Return the immediate to use if the specified
  4322. /// 32-bit value is representable in the immediate field of a BxA instruction.
  4323. static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
  4324. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
  4325. if (!C) return nullptr;
  4326. int Addr = C->getZExtValue();
  4327. if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
  4328. SignExtend32<26>(Addr) != Addr)
  4329. return nullptr; // Top 6 bits have to be sext of immediate.
  4330. return DAG
  4331. .getConstant(
  4332. (int)C->getZExtValue() >> 2, SDLoc(Op),
  4333. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
  4334. .getNode();
  4335. }
  4336. namespace {
  4337. struct TailCallArgumentInfo {
  4338. SDValue Arg;
  4339. SDValue FrameIdxOp;
  4340. int FrameIdx = 0;
  4341. TailCallArgumentInfo() = default;
  4342. };
  4343. } // end anonymous namespace
  4344. /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
  4345. static void StoreTailCallArgumentsToStackSlot(
  4346. SelectionDAG &DAG, SDValue Chain,
  4347. const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
  4348. SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
  4349. for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
  4350. SDValue Arg = TailCallArgs[i].Arg;
  4351. SDValue FIN = TailCallArgs[i].FrameIdxOp;
  4352. int FI = TailCallArgs[i].FrameIdx;
  4353. // Store relative to framepointer.
  4354. MemOpChains.push_back(DAG.getStore(
  4355. Chain, dl, Arg, FIN,
  4356. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
  4357. }
  4358. }
  4359. /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
  4360. /// the appropriate stack slot for the tail call optimized function call.
  4361. static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
  4362. SDValue OldRetAddr, SDValue OldFP,
  4363. int SPDiff, const SDLoc &dl) {
  4364. if (SPDiff) {
  4365. // Calculate the new stack slot for the return address.
  4366. MachineFunction &MF = DAG.getMachineFunction();
  4367. const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
  4368. const PPCFrameLowering *FL = Subtarget.getFrameLowering();
  4369. bool isPPC64 = Subtarget.isPPC64();
  4370. int SlotSize = isPPC64 ? 8 : 4;
  4371. int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
  4372. int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
  4373. NewRetAddrLoc, true);
  4374. EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
  4375. SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
  4376. Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
  4377. MachinePointerInfo::getFixedStack(MF, NewRetAddr));
  4378. }
  4379. return Chain;
  4380. }
  4381. /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
  4382. /// the position of the argument.
  4383. static void
  4384. CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
  4385. SDValue Arg, int SPDiff, unsigned ArgOffset,
  4386. SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
  4387. int Offset = ArgOffset + SPDiff;
  4388. uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
  4389. int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
  4390. EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
  4391. SDValue FIN = DAG.getFrameIndex(FI, VT);
  4392. TailCallArgumentInfo Info;
  4393. Info.Arg = Arg;
  4394. Info.FrameIdxOp = FIN;
  4395. Info.FrameIdx = FI;
  4396. TailCallArguments.push_back(Info);
  4397. }
  4398. /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
  4399. /// stack slot. Returns the chain as result and the loaded frame pointers in
  4400. /// LROpOut/FPOpout. Used when tail calling.
  4401. SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
  4402. SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
  4403. SDValue &FPOpOut, const SDLoc &dl) const {
  4404. if (SPDiff) {
  4405. // Load the LR and FP stack slot for later adjusting.
  4406. EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
  4407. LROpOut = getReturnAddrFrameIndex(DAG);
  4408. LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
  4409. Chain = SDValue(LROpOut.getNode(), 1);
  4410. }
  4411. return Chain;
  4412. }
  4413. /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
  4414. /// by "Src" to address "Dst" of size "Size". Alignment information is
  4415. /// specified by the specific parameter attribute. The copy will be passed as
  4416. /// a byval function parameter.
  4417. /// Sometimes what we are copying is the end of a larger object, the part that
  4418. /// does not fit in registers.
  4419. static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
  4420. SDValue Chain, ISD::ArgFlagsTy Flags,
  4421. SelectionDAG &DAG, const SDLoc &dl) {
  4422. SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
  4423. return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
  4424. Flags.getNonZeroByValAlign(), false, false, false,
  4425. MachinePointerInfo(), MachinePointerInfo());
  4426. }
  4427. /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
  4428. /// tail calls.
  4429. static void LowerMemOpCallTo(
  4430. SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
  4431. SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
  4432. bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
  4433. SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
  4434. EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  4435. if (!isTailCall) {
  4436. if (isVector) {
  4437. SDValue StackPtr;
  4438. if (isPPC64)
  4439. StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
  4440. else
  4441. StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
  4442. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
  4443. DAG.getConstant(ArgOffset, dl, PtrVT));
  4444. }
  4445. MemOpChains.push_back(
  4446. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
  4447. // Calculate and remember argument location.
  4448. } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
  4449. TailCallArguments);
  4450. }
  4451. static void
  4452. PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
  4453. const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
  4454. SDValue FPOp,
  4455. SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
  4456. // Emit a sequence of copyto/copyfrom virtual registers for arguments that
  4457. // might overwrite each other in case of tail call optimization.
  4458. SmallVector<SDValue, 8> MemOpChains2;
  4459. // Do not flag preceding copytoreg stuff together with the following stuff.
  4460. InFlag = SDValue();
  4461. StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
  4462. MemOpChains2, dl);
  4463. if (!MemOpChains2.empty())
  4464. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
  4465. // Store the return address to the appropriate stack slot.
  4466. Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
  4467. // Emit callseq_end just before tailcall node.
  4468. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
  4469. DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
  4470. InFlag = Chain.getValue(1);
  4471. }
  4472. // Is this global address that of a function that can be called by name? (as
  4473. // opposed to something that must hold a descriptor for an indirect call).
  4474. static bool isFunctionGlobalAddress(SDValue Callee) {
  4475. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
  4476. if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
  4477. Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
  4478. return false;
  4479. return G->getGlobal()->getValueType()->isFunctionTy();
  4480. }
  4481. return false;
  4482. }
  4483. SDValue PPCTargetLowering::LowerCallResult(
  4484. SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
  4485. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  4486. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  4487. SmallVector<CCValAssign, 16> RVLocs;
  4488. CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
  4489. *DAG.getContext());
  4490. CCRetInfo.AnalyzeCallResult(
  4491. Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
  4492. ? RetCC_PPC_Cold
  4493. : RetCC_PPC);
  4494. // Copy all of the result registers out of their specified physreg.
  4495. for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
  4496. CCValAssign &VA = RVLocs[i];
  4497. assert(VA.isRegLoc() && "Can only return in registers!");
  4498. SDValue Val;
  4499. if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
  4500. SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
  4501. InFlag);
  4502. Chain = Lo.getValue(1);
  4503. InFlag = Lo.getValue(2);
  4504. VA = RVLocs[++i]; // skip ahead to next loc
  4505. SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
  4506. InFlag);
  4507. Chain = Hi.getValue(1);
  4508. InFlag = Hi.getValue(2);
  4509. if (!Subtarget.isLittleEndian())
  4510. std::swap (Lo, Hi);
  4511. Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
  4512. } else {
  4513. Val = DAG.getCopyFromReg(Chain, dl,
  4514. VA.getLocReg(), VA.getLocVT(), InFlag);
  4515. Chain = Val.getValue(1);
  4516. InFlag = Val.getValue(2);
  4517. }
  4518. switch (VA.getLocInfo()) {
  4519. default: llvm_unreachable("Unknown loc info!");
  4520. case CCValAssign::Full: break;
  4521. case CCValAssign::AExt:
  4522. Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
  4523. break;
  4524. case CCValAssign::ZExt:
  4525. Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
  4526. DAG.getValueType(VA.getValVT()));
  4527. Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
  4528. break;
  4529. case CCValAssign::SExt:
  4530. Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
  4531. DAG.getValueType(VA.getValVT()));
  4532. Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
  4533. break;
  4534. }
  4535. InVals.push_back(Val);
  4536. }
  4537. return Chain;
  4538. }
  4539. static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
  4540. const PPCSubtarget &Subtarget, bool isPatchPoint) {
  4541. // PatchPoint calls are not indirect.
  4542. if (isPatchPoint)
  4543. return false;
  4544. if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
  4545. return false;
  4546. // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
  4547. // becuase the immediate function pointer points to a descriptor instead of
  4548. // a function entry point. The ELFv2 ABI cannot use a BLA because the function
  4549. // pointer immediate points to the global entry point, while the BLA would
  4550. // need to jump to the local entry point (see rL211174).
  4551. if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
  4552. isBLACompatibleAddress(Callee, DAG))
  4553. return false;
  4554. return true;
  4555. }
  4556. // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
  4557. static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
  4558. return Subtarget.isAIXABI() ||
  4559. (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
  4560. }
  4561. static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
  4562. const Function &Caller, const SDValue &Callee,
  4563. const PPCSubtarget &Subtarget,
  4564. const TargetMachine &TM,
  4565. bool IsStrictFPCall = false) {
  4566. if (CFlags.IsTailCall)
  4567. return PPCISD::TC_RETURN;
  4568. unsigned RetOpc = 0;
  4569. // This is a call through a function pointer.
  4570. if (CFlags.IsIndirect) {
  4571. // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
  4572. // indirect calls. The save of the caller's TOC pointer to the stack will be
  4573. // inserted into the DAG as part of call lowering. The restore of the TOC
  4574. // pointer is modeled by using a pseudo instruction for the call opcode that
  4575. // represents the 2 instruction sequence of an indirect branch and link,
  4576. // immediately followed by a load of the TOC pointer from the the stack save
  4577. // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
  4578. // as it is not saved or used.
  4579. RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
  4580. : PPCISD::BCTRL;
  4581. } else if (Subtarget.isUsingPCRelativeCalls()) {
  4582. assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
  4583. RetOpc = PPCISD::CALL_NOTOC;
  4584. } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
  4585. // The ABIs that maintain a TOC pointer accross calls need to have a nop
  4586. // immediately following the call instruction if the caller and callee may
  4587. // have different TOC bases. At link time if the linker determines the calls
  4588. // may not share a TOC base, the call is redirected to a trampoline inserted
  4589. // by the linker. The trampoline will (among other things) save the callers
  4590. // TOC pointer at an ABI designated offset in the linkage area and the
  4591. // linker will rewrite the nop to be a load of the TOC pointer from the
  4592. // linkage area into gpr2.
  4593. RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
  4594. : PPCISD::CALL_NOP;
  4595. else
  4596. RetOpc = PPCISD::CALL;
  4597. if (IsStrictFPCall) {
  4598. switch (RetOpc) {
  4599. default:
  4600. llvm_unreachable("Unknown call opcode");
  4601. case PPCISD::BCTRL_LOAD_TOC:
  4602. RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
  4603. break;
  4604. case PPCISD::BCTRL:
  4605. RetOpc = PPCISD::BCTRL_RM;
  4606. break;
  4607. case PPCISD::CALL_NOTOC:
  4608. RetOpc = PPCISD::CALL_NOTOC_RM;
  4609. break;
  4610. case PPCISD::CALL:
  4611. RetOpc = PPCISD::CALL_RM;
  4612. break;
  4613. case PPCISD::CALL_NOP:
  4614. RetOpc = PPCISD::CALL_NOP_RM;
  4615. break;
  4616. }
  4617. }
  4618. return RetOpc;
  4619. }
  4620. static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
  4621. const SDLoc &dl, const PPCSubtarget &Subtarget) {
  4622. if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
  4623. if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
  4624. return SDValue(Dest, 0);
  4625. // Returns true if the callee is local, and false otherwise.
  4626. auto isLocalCallee = [&]() {
  4627. const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
  4628. const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
  4629. const GlobalValue *GV = G ? G->getGlobal() : nullptr;
  4630. return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
  4631. !isa_and_nonnull<GlobalIFunc>(GV);
  4632. };
  4633. // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
  4634. // a static relocation model causes some versions of GNU LD (2.17.50, at
  4635. // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
  4636. // built with secure-PLT.
  4637. bool UsePlt =
  4638. Subtarget.is32BitELFABI() && !isLocalCallee() &&
  4639. Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
  4640. const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
  4641. const TargetMachine &TM = Subtarget.getTargetMachine();
  4642. const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
  4643. MCSymbolXCOFF *S =
  4644. cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
  4645. MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  4646. return DAG.getMCSymbol(S, PtrVT);
  4647. };
  4648. if (isFunctionGlobalAddress(Callee)) {
  4649. const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
  4650. if (Subtarget.isAIXABI()) {
  4651. assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
  4652. return getAIXFuncEntryPointSymbolSDNode(GV);
  4653. }
  4654. return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
  4655. UsePlt ? PPCII::MO_PLT : 0);
  4656. }
  4657. if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
  4658. const char *SymName = S->getSymbol();
  4659. if (Subtarget.isAIXABI()) {
  4660. // If there exists a user-declared function whose name is the same as the
  4661. // ExternalSymbol's, then we pick up the user-declared version.
  4662. const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
  4663. if (const Function *F =
  4664. dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
  4665. return getAIXFuncEntryPointSymbolSDNode(F);
  4666. // On AIX, direct function calls reference the symbol for the function's
  4667. // entry point, which is named by prepending a "." before the function's
  4668. // C-linkage name. A Qualname is returned here because an external
  4669. // function entry point is a csect with XTY_ER property.
  4670. const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
  4671. auto &Context = DAG.getMachineFunction().getMMI().getContext();
  4672. MCSectionXCOFF *Sec = Context.getXCOFFSection(
  4673. (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
  4674. XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
  4675. return Sec->getQualNameSymbol();
  4676. };
  4677. SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
  4678. }
  4679. return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
  4680. UsePlt ? PPCII::MO_PLT : 0);
  4681. }
  4682. // No transformation needed.
  4683. assert(Callee.getNode() && "What no callee?");
  4684. return Callee;
  4685. }
  4686. static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
  4687. assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
  4688. "Expected a CALLSEQ_STARTSDNode.");
  4689. // The last operand is the chain, except when the node has glue. If the node
  4690. // has glue, then the last operand is the glue, and the chain is the second
  4691. // last operand.
  4692. SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
  4693. if (LastValue.getValueType() != MVT::Glue)
  4694. return LastValue;
  4695. return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
  4696. }
  4697. // Creates the node that moves a functions address into the count register
  4698. // to prepare for an indirect call instruction.
  4699. static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
  4700. SDValue &Glue, SDValue &Chain,
  4701. const SDLoc &dl) {
  4702. SDValue MTCTROps[] = {Chain, Callee, Glue};
  4703. EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
  4704. Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
  4705. makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
  4706. // The glue is the second value produced.
  4707. Glue = Chain.getValue(1);
  4708. }
  4709. static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
  4710. SDValue &Glue, SDValue &Chain,
  4711. SDValue CallSeqStart,
  4712. const CallBase *CB, const SDLoc &dl,
  4713. bool hasNest,
  4714. const PPCSubtarget &Subtarget) {
  4715. // Function pointers in the 64-bit SVR4 ABI do not point to the function
  4716. // entry point, but to the function descriptor (the function entry point
  4717. // address is part of the function descriptor though).
  4718. // The function descriptor is a three doubleword structure with the
  4719. // following fields: function entry point, TOC base address and
  4720. // environment pointer.
  4721. // Thus for a call through a function pointer, the following actions need
  4722. // to be performed:
  4723. // 1. Save the TOC of the caller in the TOC save area of its stack
  4724. // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
  4725. // 2. Load the address of the function entry point from the function
  4726. // descriptor.
  4727. // 3. Load the TOC of the callee from the function descriptor into r2.
  4728. // 4. Load the environment pointer from the function descriptor into
  4729. // r11.
  4730. // 5. Branch to the function entry point address.
  4731. // 6. On return of the callee, the TOC of the caller needs to be
  4732. // restored (this is done in FinishCall()).
  4733. //
  4734. // The loads are scheduled at the beginning of the call sequence, and the
  4735. // register copies are flagged together to ensure that no other
  4736. // operations can be scheduled in between. E.g. without flagging the
  4737. // copies together, a TOC access in the caller could be scheduled between
  4738. // the assignment of the callee TOC and the branch to the callee, which leads
  4739. // to incorrect code.
  4740. // Start by loading the function address from the descriptor.
  4741. SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
  4742. auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
  4743. ? (MachineMemOperand::MODereferenceable |
  4744. MachineMemOperand::MOInvariant)
  4745. : MachineMemOperand::MONone;
  4746. MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
  4747. // Registers used in building the DAG.
  4748. const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
  4749. const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
  4750. // Offsets of descriptor members.
  4751. const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
  4752. const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
  4753. const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
  4754. const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
  4755. // One load for the functions entry point address.
  4756. SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
  4757. Alignment, MMOFlags);
  4758. // One for loading the TOC anchor for the module that contains the called
  4759. // function.
  4760. SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
  4761. SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
  4762. SDValue TOCPtr =
  4763. DAG.getLoad(RegVT, dl, LDChain, AddTOC,
  4764. MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
  4765. // One for loading the environment pointer.
  4766. SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
  4767. SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
  4768. SDValue LoadEnvPtr =
  4769. DAG.getLoad(RegVT, dl, LDChain, AddPtr,
  4770. MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
  4771. // Then copy the newly loaded TOC anchor to the TOC pointer.
  4772. SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
  4773. Chain = TOCVal.getValue(0);
  4774. Glue = TOCVal.getValue(1);
  4775. // If the function call has an explicit 'nest' parameter, it takes the
  4776. // place of the environment pointer.
  4777. assert((!hasNest || !Subtarget.isAIXABI()) &&
  4778. "Nest parameter is not supported on AIX.");
  4779. if (!hasNest) {
  4780. SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
  4781. Chain = EnvVal.getValue(0);
  4782. Glue = EnvVal.getValue(1);
  4783. }
  4784. // The rest of the indirect call sequence is the same as the non-descriptor
  4785. // DAG.
  4786. prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
  4787. }
  4788. static void
  4789. buildCallOperands(SmallVectorImpl<SDValue> &Ops,
  4790. PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
  4791. SelectionDAG &DAG,
  4792. SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
  4793. SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
  4794. const PPCSubtarget &Subtarget) {
  4795. const bool IsPPC64 = Subtarget.isPPC64();
  4796. // MVT for a general purpose register.
  4797. const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
  4798. // First operand is always the chain.
  4799. Ops.push_back(Chain);
  4800. // If it's a direct call pass the callee as the second operand.
  4801. if (!CFlags.IsIndirect)
  4802. Ops.push_back(Callee);
  4803. else {
  4804. assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
  4805. // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
  4806. // on the stack (this would have been done in `LowerCall_64SVR4` or
  4807. // `LowerCall_AIX`). The call instruction is a pseudo instruction that
  4808. // represents both the indirect branch and a load that restores the TOC
  4809. // pointer from the linkage area. The operand for the TOC restore is an add
  4810. // of the TOC save offset to the stack pointer. This must be the second
  4811. // operand: after the chain input but before any other variadic arguments.
  4812. // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
  4813. // saved or used.
  4814. if (isTOCSaveRestoreRequired(Subtarget)) {
  4815. const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
  4816. SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
  4817. unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
  4818. SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
  4819. SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
  4820. Ops.push_back(AddTOC);
  4821. }
  4822. // Add the register used for the environment pointer.
  4823. if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
  4824. Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
  4825. RegVT));
  4826. // Add CTR register as callee so a bctr can be emitted later.
  4827. if (CFlags.IsTailCall)
  4828. Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
  4829. }
  4830. // If this is a tail call add stack pointer delta.
  4831. if (CFlags.IsTailCall)
  4832. Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
  4833. // Add argument registers to the end of the list so that they are known live
  4834. // into the call.
  4835. for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
  4836. Ops.push_back(DAG.getRegister(RegsToPass[i].first,
  4837. RegsToPass[i].second.getValueType()));
  4838. // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
  4839. // no way to mark dependencies as implicit here.
  4840. // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
  4841. if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
  4842. !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
  4843. Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
  4844. // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
  4845. if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
  4846. Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
  4847. // Add a register mask operand representing the call-preserved registers.
  4848. const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
  4849. const uint32_t *Mask =
  4850. TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
  4851. assert(Mask && "Missing call preserved mask for calling convention");
  4852. Ops.push_back(DAG.getRegisterMask(Mask));
  4853. // If the glue is valid, it is the last operand.
  4854. if (Glue.getNode())
  4855. Ops.push_back(Glue);
  4856. }
  4857. SDValue PPCTargetLowering::FinishCall(
  4858. CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
  4859. SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
  4860. SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
  4861. unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
  4862. SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
  4863. if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
  4864. Subtarget.isAIXABI())
  4865. setUsesTOCBasePtr(DAG);
  4866. unsigned CallOpc =
  4867. getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
  4868. Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
  4869. if (!CFlags.IsIndirect)
  4870. Callee = transformCallee(Callee, DAG, dl, Subtarget);
  4871. else if (Subtarget.usesFunctionDescriptors())
  4872. prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
  4873. dl, CFlags.HasNest, Subtarget);
  4874. else
  4875. prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
  4876. // Build the operand list for the call instruction.
  4877. SmallVector<SDValue, 8> Ops;
  4878. buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
  4879. SPDiff, Subtarget);
  4880. // Emit tail call.
  4881. if (CFlags.IsTailCall) {
  4882. // Indirect tail call when using PC Relative calls do not have the same
  4883. // constraints.
  4884. assert(((Callee.getOpcode() == ISD::Register &&
  4885. cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
  4886. Callee.getOpcode() == ISD::TargetExternalSymbol ||
  4887. Callee.getOpcode() == ISD::TargetGlobalAddress ||
  4888. isa<ConstantSDNode>(Callee) ||
  4889. (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
  4890. "Expecting a global address, external symbol, absolute value, "
  4891. "register or an indirect tail call when PC Relative calls are "
  4892. "used.");
  4893. // PC Relative calls also use TC_RETURN as the way to mark tail calls.
  4894. assert(CallOpc == PPCISD::TC_RETURN &&
  4895. "Unexpected call opcode for a tail call.");
  4896. DAG.getMachineFunction().getFrameInfo().setHasTailCall();
  4897. return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
  4898. }
  4899. std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
  4900. Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
  4901. DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
  4902. Glue = Chain.getValue(1);
  4903. // When performing tail call optimization the callee pops its arguments off
  4904. // the stack. Account for this here so these bytes can be pushed back on in
  4905. // PPCFrameLowering::eliminateCallFramePseudoInstr.
  4906. int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
  4907. getTargetMachine().Options.GuaranteedTailCallOpt)
  4908. ? NumBytes
  4909. : 0;
  4910. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
  4911. DAG.getIntPtrConstant(BytesCalleePops, dl, true),
  4912. Glue, dl);
  4913. Glue = Chain.getValue(1);
  4914. return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
  4915. DAG, InVals);
  4916. }
  4917. SDValue
  4918. PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
  4919. SmallVectorImpl<SDValue> &InVals) const {
  4920. SelectionDAG &DAG = CLI.DAG;
  4921. SDLoc &dl = CLI.DL;
  4922. SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
  4923. SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
  4924. SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
  4925. SDValue Chain = CLI.Chain;
  4926. SDValue Callee = CLI.Callee;
  4927. bool &isTailCall = CLI.IsTailCall;
  4928. CallingConv::ID CallConv = CLI.CallConv;
  4929. bool isVarArg = CLI.IsVarArg;
  4930. bool isPatchPoint = CLI.IsPatchPoint;
  4931. const CallBase *CB = CLI.CB;
  4932. if (isTailCall) {
  4933. if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
  4934. isTailCall = false;
  4935. else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
  4936. isTailCall = IsEligibleForTailCallOptimization_64SVR4(
  4937. Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
  4938. else
  4939. isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
  4940. Ins, DAG);
  4941. if (isTailCall) {
  4942. ++NumTailCalls;
  4943. if (!getTargetMachine().Options.GuaranteedTailCallOpt)
  4944. ++NumSiblingCalls;
  4945. // PC Relative calls no longer guarantee that the callee is a Global
  4946. // Address Node. The callee could be an indirect tail call in which
  4947. // case the SDValue for the callee could be a load (to load the address
  4948. // of a function pointer) or it may be a register copy (to move the
  4949. // address of the callee from a function parameter into a virtual
  4950. // register). It may also be an ExternalSymbolSDNode (ex memcopy).
  4951. assert((Subtarget.isUsingPCRelativeCalls() ||
  4952. isa<GlobalAddressSDNode>(Callee)) &&
  4953. "Callee should be an llvm::Function object.");
  4954. LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
  4955. << "\nTCO callee: ");
  4956. LLVM_DEBUG(Callee.dump());
  4957. }
  4958. }
  4959. if (!isTailCall && CB && CB->isMustTailCall())
  4960. report_fatal_error("failed to perform tail call elimination on a call "
  4961. "site marked musttail");
  4962. // When long calls (i.e. indirect calls) are always used, calls are always
  4963. // made via function pointer. If we have a function name, first translate it
  4964. // into a pointer.
  4965. if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
  4966. !isTailCall)
  4967. Callee = LowerGlobalAddress(Callee, DAG);
  4968. CallFlags CFlags(
  4969. CallConv, isTailCall, isVarArg, isPatchPoint,
  4970. isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
  4971. // hasNest
  4972. Subtarget.is64BitELFABI() &&
  4973. any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
  4974. CLI.NoMerge);
  4975. if (Subtarget.isAIXABI())
  4976. return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
  4977. InVals, CB);
  4978. assert(Subtarget.isSVR4ABI());
  4979. if (Subtarget.isPPC64())
  4980. return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
  4981. InVals, CB);
  4982. return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
  4983. InVals, CB);
  4984. }
  4985. SDValue PPCTargetLowering::LowerCall_32SVR4(
  4986. SDValue Chain, SDValue Callee, CallFlags CFlags,
  4987. const SmallVectorImpl<ISD::OutputArg> &Outs,
  4988. const SmallVectorImpl<SDValue> &OutVals,
  4989. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  4990. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
  4991. const CallBase *CB) const {
  4992. // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
  4993. // of the 32-bit SVR4 ABI stack frame layout.
  4994. const CallingConv::ID CallConv = CFlags.CallConv;
  4995. const bool IsVarArg = CFlags.IsVarArg;
  4996. const bool IsTailCall = CFlags.IsTailCall;
  4997. assert((CallConv == CallingConv::C ||
  4998. CallConv == CallingConv::Cold ||
  4999. CallConv == CallingConv::Fast) && "Unknown calling convention!");
  5000. const Align PtrAlign(4);
  5001. MachineFunction &MF = DAG.getMachineFunction();
  5002. // Mark this function as potentially containing a function that contains a
  5003. // tail call. As a consequence the frame pointer will be used for dynamicalloc
  5004. // and restoring the callers stack pointer in this functions epilog. This is
  5005. // done because by tail calling the called function might overwrite the value
  5006. // in this function's (MF) stack pointer stack slot 0(SP).
  5007. if (getTargetMachine().Options.GuaranteedTailCallOpt &&
  5008. CallConv == CallingConv::Fast)
  5009. MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
  5010. // Count how many bytes are to be pushed on the stack, including the linkage
  5011. // area, parameter list area and the part of the local variable space which
  5012. // contains copies of aggregates which are passed by value.
  5013. // Assign locations to all of the outgoing arguments.
  5014. SmallVector<CCValAssign, 16> ArgLocs;
  5015. PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
  5016. // Reserve space for the linkage area on the stack.
  5017. CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
  5018. PtrAlign);
  5019. if (useSoftFloat())
  5020. CCInfo.PreAnalyzeCallOperands(Outs);
  5021. if (IsVarArg) {
  5022. // Handle fixed and variable vector arguments differently.
  5023. // Fixed vector arguments go into registers as long as registers are
  5024. // available. Variable vector arguments always go into memory.
  5025. unsigned NumArgs = Outs.size();
  5026. for (unsigned i = 0; i != NumArgs; ++i) {
  5027. MVT ArgVT = Outs[i].VT;
  5028. ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
  5029. bool Result;
  5030. if (Outs[i].IsFixed) {
  5031. Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
  5032. CCInfo);
  5033. } else {
  5034. Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
  5035. ArgFlags, CCInfo);
  5036. }
  5037. if (Result) {
  5038. #ifndef NDEBUG
  5039. errs() << "Call operand #" << i << " has unhandled type "
  5040. << EVT(ArgVT).getEVTString() << "\n";
  5041. #endif
  5042. llvm_unreachable(nullptr);
  5043. }
  5044. }
  5045. } else {
  5046. // All arguments are treated the same.
  5047. CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
  5048. }
  5049. CCInfo.clearWasPPCF128();
  5050. // Assign locations to all of the outgoing aggregate by value arguments.
  5051. SmallVector<CCValAssign, 16> ByValArgLocs;
  5052. CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
  5053. // Reserve stack space for the allocations in CCInfo.
  5054. CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
  5055. CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
  5056. // Size of the linkage area, parameter list area and the part of the local
  5057. // space variable where copies of aggregates which are passed by value are
  5058. // stored.
  5059. unsigned NumBytes = CCByValInfo.getNextStackOffset();
  5060. // Calculate by how many bytes the stack has to be adjusted in case of tail
  5061. // call optimization.
  5062. int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
  5063. // Adjust the stack pointer for the new arguments...
  5064. // These operations are automatically eliminated by the prolog/epilog pass
  5065. Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
  5066. SDValue CallSeqStart = Chain;
  5067. // Load the return address and frame pointer so it can be moved somewhere else
  5068. // later.
  5069. SDValue LROp, FPOp;
  5070. Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
  5071. // Set up a copy of the stack pointer for use loading and storing any
  5072. // arguments that may not fit in the registers available for argument
  5073. // passing.
  5074. SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
  5075. SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
  5076. SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
  5077. SmallVector<SDValue, 8> MemOpChains;
  5078. bool seenFloatArg = false;
  5079. // Walk the register/memloc assignments, inserting copies/loads.
  5080. // i - Tracks the index into the list of registers allocated for the call
  5081. // RealArgIdx - Tracks the index into the list of actual function arguments
  5082. // j - Tracks the index into the list of byval arguments
  5083. for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
  5084. i != e;
  5085. ++i, ++RealArgIdx) {
  5086. CCValAssign &VA = ArgLocs[i];
  5087. SDValue Arg = OutVals[RealArgIdx];
  5088. ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
  5089. if (Flags.isByVal()) {
  5090. // Argument is an aggregate which is passed by value, thus we need to
  5091. // create a copy of it in the local variable space of the current stack
  5092. // frame (which is the stack frame of the caller) and pass the address of
  5093. // this copy to the callee.
  5094. assert((j < ByValArgLocs.size()) && "Index out of bounds!");
  5095. CCValAssign &ByValVA = ByValArgLocs[j++];
  5096. assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
  5097. // Memory reserved in the local variable space of the callers stack frame.
  5098. unsigned LocMemOffset = ByValVA.getLocMemOffset();
  5099. SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
  5100. PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
  5101. StackPtr, PtrOff);
  5102. // Create a copy of the argument in the local area of the current
  5103. // stack frame.
  5104. SDValue MemcpyCall =
  5105. CreateCopyOfByValArgument(Arg, PtrOff,
  5106. CallSeqStart.getNode()->getOperand(0),
  5107. Flags, DAG, dl);
  5108. // This must go outside the CALLSEQ_START..END.
  5109. SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
  5110. SDLoc(MemcpyCall));
  5111. DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
  5112. NewCallSeqStart.getNode());
  5113. Chain = CallSeqStart = NewCallSeqStart;
  5114. // Pass the address of the aggregate copy on the stack either in a
  5115. // physical register or in the parameter list area of the current stack
  5116. // frame to the callee.
  5117. Arg = PtrOff;
  5118. }
  5119. // When useCRBits() is true, there can be i1 arguments.
  5120. // It is because getRegisterType(MVT::i1) => MVT::i1,
  5121. // and for other integer types getRegisterType() => MVT::i32.
  5122. // Extend i1 and ensure callee will get i32.
  5123. if (Arg.getValueType() == MVT::i1)
  5124. Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
  5125. dl, MVT::i32, Arg);
  5126. if (VA.isRegLoc()) {
  5127. seenFloatArg |= VA.getLocVT().isFloatingPoint();
  5128. // Put argument in a physical register.
  5129. if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
  5130. bool IsLE = Subtarget.isLittleEndian();
  5131. SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
  5132. DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
  5133. RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
  5134. SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
  5135. DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
  5136. RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
  5137. SVal.getValue(0)));
  5138. } else
  5139. RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
  5140. } else {
  5141. // Put argument in the parameter list area of the current stack frame.
  5142. assert(VA.isMemLoc());
  5143. unsigned LocMemOffset = VA.getLocMemOffset();
  5144. if (!IsTailCall) {
  5145. SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
  5146. PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
  5147. StackPtr, PtrOff);
  5148. MemOpChains.push_back(
  5149. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
  5150. } else {
  5151. // Calculate and remember argument location.
  5152. CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
  5153. TailCallArguments);
  5154. }
  5155. }
  5156. }
  5157. if (!MemOpChains.empty())
  5158. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
  5159. // Build a sequence of copy-to-reg nodes chained together with token chain
  5160. // and flag operands which copy the outgoing args into the appropriate regs.
  5161. SDValue InFlag;
  5162. for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
  5163. Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
  5164. RegsToPass[i].second, InFlag);
  5165. InFlag = Chain.getValue(1);
  5166. }
  5167. // Set CR bit 6 to true if this is a vararg call with floating args passed in
  5168. // registers.
  5169. if (IsVarArg) {
  5170. SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
  5171. SDValue Ops[] = { Chain, InFlag };
  5172. Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
  5173. dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
  5174. InFlag = Chain.getValue(1);
  5175. }
  5176. if (IsTailCall)
  5177. PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
  5178. TailCallArguments);
  5179. return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
  5180. Callee, SPDiff, NumBytes, Ins, InVals, CB);
  5181. }
  5182. // Copy an argument into memory, being careful to do this outside the
  5183. // call sequence for the call to which the argument belongs.
  5184. SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
  5185. SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
  5186. SelectionDAG &DAG, const SDLoc &dl) const {
  5187. SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
  5188. CallSeqStart.getNode()->getOperand(0),
  5189. Flags, DAG, dl);
  5190. // The MEMCPY must go outside the CALLSEQ_START..END.
  5191. int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
  5192. SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
  5193. SDLoc(MemcpyCall));
  5194. DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
  5195. NewCallSeqStart.getNode());
  5196. return NewCallSeqStart;
  5197. }
  5198. SDValue PPCTargetLowering::LowerCall_64SVR4(
  5199. SDValue Chain, SDValue Callee, CallFlags CFlags,
  5200. const SmallVectorImpl<ISD::OutputArg> &Outs,
  5201. const SmallVectorImpl<SDValue> &OutVals,
  5202. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  5203. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
  5204. const CallBase *CB) const {
  5205. bool isELFv2ABI = Subtarget.isELFv2ABI();
  5206. bool isLittleEndian = Subtarget.isLittleEndian();
  5207. unsigned NumOps = Outs.size();
  5208. bool IsSibCall = false;
  5209. bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
  5210. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  5211. unsigned PtrByteSize = 8;
  5212. MachineFunction &MF = DAG.getMachineFunction();
  5213. if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
  5214. IsSibCall = true;
  5215. // Mark this function as potentially containing a function that contains a
  5216. // tail call. As a consequence the frame pointer will be used for dynamicalloc
  5217. // and restoring the callers stack pointer in this functions epilog. This is
  5218. // done because by tail calling the called function might overwrite the value
  5219. // in this function's (MF) stack pointer stack slot 0(SP).
  5220. if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
  5221. MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
  5222. assert(!(IsFastCall && CFlags.IsVarArg) &&
  5223. "fastcc not supported on varargs functions");
  5224. // Count how many bytes are to be pushed on the stack, including the linkage
  5225. // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
  5226. // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
  5227. // area is 32 bytes reserved space for [SP][CR][LR][TOC].
  5228. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  5229. unsigned NumBytes = LinkageSize;
  5230. unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
  5231. static const MCPhysReg GPR[] = {
  5232. PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  5233. PPC::X7, PPC::X8, PPC::X9, PPC::X10,
  5234. };
  5235. static const MCPhysReg VR[] = {
  5236. PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
  5237. PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
  5238. };
  5239. const unsigned NumGPRs = array_lengthof(GPR);
  5240. const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
  5241. const unsigned NumVRs = array_lengthof(VR);
  5242. // On ELFv2, we can avoid allocating the parameter area if all the arguments
  5243. // can be passed to the callee in registers.
  5244. // For the fast calling convention, there is another check below.
  5245. // Note: We should keep consistent with LowerFormalArguments_64SVR4()
  5246. bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
  5247. if (!HasParameterArea) {
  5248. unsigned ParamAreaSize = NumGPRs * PtrByteSize;
  5249. unsigned AvailableFPRs = NumFPRs;
  5250. unsigned AvailableVRs = NumVRs;
  5251. unsigned NumBytesTmp = NumBytes;
  5252. for (unsigned i = 0; i != NumOps; ++i) {
  5253. if (Outs[i].Flags.isNest()) continue;
  5254. if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
  5255. PtrByteSize, LinkageSize, ParamAreaSize,
  5256. NumBytesTmp, AvailableFPRs, AvailableVRs))
  5257. HasParameterArea = true;
  5258. }
  5259. }
  5260. // When using the fast calling convention, we don't provide backing for
  5261. // arguments that will be in registers.
  5262. unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
  5263. // Avoid allocating parameter area for fastcc functions if all the arguments
  5264. // can be passed in the registers.
  5265. if (IsFastCall)
  5266. HasParameterArea = false;
  5267. // Add up all the space actually used.
  5268. for (unsigned i = 0; i != NumOps; ++i) {
  5269. ISD::ArgFlagsTy Flags = Outs[i].Flags;
  5270. EVT ArgVT = Outs[i].VT;
  5271. EVT OrigVT = Outs[i].ArgVT;
  5272. if (Flags.isNest())
  5273. continue;
  5274. if (IsFastCall) {
  5275. if (Flags.isByVal()) {
  5276. NumGPRsUsed += (Flags.getByValSize()+7)/8;
  5277. if (NumGPRsUsed > NumGPRs)
  5278. HasParameterArea = true;
  5279. } else {
  5280. switch (ArgVT.getSimpleVT().SimpleTy) {
  5281. default: llvm_unreachable("Unexpected ValueType for argument!");
  5282. case MVT::i1:
  5283. case MVT::i32:
  5284. case MVT::i64:
  5285. if (++NumGPRsUsed <= NumGPRs)
  5286. continue;
  5287. break;
  5288. case MVT::v4i32:
  5289. case MVT::v8i16:
  5290. case MVT::v16i8:
  5291. case MVT::v2f64:
  5292. case MVT::v2i64:
  5293. case MVT::v1i128:
  5294. case MVT::f128:
  5295. if (++NumVRsUsed <= NumVRs)
  5296. continue;
  5297. break;
  5298. case MVT::v4f32:
  5299. if (++NumVRsUsed <= NumVRs)
  5300. continue;
  5301. break;
  5302. case MVT::f32:
  5303. case MVT::f64:
  5304. if (++NumFPRsUsed <= NumFPRs)
  5305. continue;
  5306. break;
  5307. }
  5308. HasParameterArea = true;
  5309. }
  5310. }
  5311. /* Respect alignment of argument on the stack. */
  5312. auto Alignement =
  5313. CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
  5314. NumBytes = alignTo(NumBytes, Alignement);
  5315. NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
  5316. if (Flags.isInConsecutiveRegsLast())
  5317. NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  5318. }
  5319. unsigned NumBytesActuallyUsed = NumBytes;
  5320. // In the old ELFv1 ABI,
  5321. // the prolog code of the callee may store up to 8 GPR argument registers to
  5322. // the stack, allowing va_start to index over them in memory if its varargs.
  5323. // Because we cannot tell if this is needed on the caller side, we have to
  5324. // conservatively assume that it is needed. As such, make sure we have at
  5325. // least enough stack space for the caller to store the 8 GPRs.
  5326. // In the ELFv2 ABI, we allocate the parameter area iff a callee
  5327. // really requires memory operands, e.g. a vararg function.
  5328. if (HasParameterArea)
  5329. NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
  5330. else
  5331. NumBytes = LinkageSize;
  5332. // Tail call needs the stack to be aligned.
  5333. if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
  5334. NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
  5335. int SPDiff = 0;
  5336. // Calculate by how many bytes the stack has to be adjusted in case of tail
  5337. // call optimization.
  5338. if (!IsSibCall)
  5339. SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
  5340. // To protect arguments on the stack from being clobbered in a tail call,
  5341. // force all the loads to happen before doing any other lowering.
  5342. if (CFlags.IsTailCall)
  5343. Chain = DAG.getStackArgumentTokenFactor(Chain);
  5344. // Adjust the stack pointer for the new arguments...
  5345. // These operations are automatically eliminated by the prolog/epilog pass
  5346. if (!IsSibCall)
  5347. Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
  5348. SDValue CallSeqStart = Chain;
  5349. // Load the return address and frame pointer so it can be move somewhere else
  5350. // later.
  5351. SDValue LROp, FPOp;
  5352. Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
  5353. // Set up a copy of the stack pointer for use loading and storing any
  5354. // arguments that may not fit in the registers available for argument
  5355. // passing.
  5356. SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
  5357. // Figure out which arguments are going to go in registers, and which in
  5358. // memory. Also, if this is a vararg function, floating point operations
  5359. // must be stored to our stack, and loaded into integer regs as well, if
  5360. // any integer regs are available for argument passing.
  5361. unsigned ArgOffset = LinkageSize;
  5362. SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
  5363. SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
  5364. SmallVector<SDValue, 8> MemOpChains;
  5365. for (unsigned i = 0; i != NumOps; ++i) {
  5366. SDValue Arg = OutVals[i];
  5367. ISD::ArgFlagsTy Flags = Outs[i].Flags;
  5368. EVT ArgVT = Outs[i].VT;
  5369. EVT OrigVT = Outs[i].ArgVT;
  5370. // PtrOff will be used to store the current argument to the stack if a
  5371. // register cannot be found for it.
  5372. SDValue PtrOff;
  5373. // We re-align the argument offset for each argument, except when using the
  5374. // fast calling convention, when we need to make sure we do that only when
  5375. // we'll actually use a stack slot.
  5376. auto ComputePtrOff = [&]() {
  5377. /* Respect alignment of argument on the stack. */
  5378. auto Alignment =
  5379. CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
  5380. ArgOffset = alignTo(ArgOffset, Alignment);
  5381. PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
  5382. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  5383. };
  5384. if (!IsFastCall) {
  5385. ComputePtrOff();
  5386. /* Compute GPR index associated with argument offset. */
  5387. GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
  5388. GPR_idx = std::min(GPR_idx, NumGPRs);
  5389. }
  5390. // Promote integers to 64-bit values.
  5391. if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
  5392. // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
  5393. unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  5394. Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
  5395. }
  5396. // FIXME memcpy is used way more than necessary. Correctness first.
  5397. // Note: "by value" is code for passing a structure by value, not
  5398. // basic types.
  5399. if (Flags.isByVal()) {
  5400. // Note: Size includes alignment padding, so
  5401. // struct x { short a; char b; }
  5402. // will have Size = 4. With #pragma pack(1), it will have Size = 3.
  5403. // These are the proper values we need for right-justifying the
  5404. // aggregate in a parameter register.
  5405. unsigned Size = Flags.getByValSize();
  5406. // An empty aggregate parameter takes up no storage and no
  5407. // registers.
  5408. if (Size == 0)
  5409. continue;
  5410. if (IsFastCall)
  5411. ComputePtrOff();
  5412. // All aggregates smaller than 8 bytes must be passed right-justified.
  5413. if (Size==1 || Size==2 || Size==4) {
  5414. EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
  5415. if (GPR_idx != NumGPRs) {
  5416. SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
  5417. MachinePointerInfo(), VT);
  5418. MemOpChains.push_back(Load.getValue(1));
  5419. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
  5420. ArgOffset += PtrByteSize;
  5421. continue;
  5422. }
  5423. }
  5424. if (GPR_idx == NumGPRs && Size < 8) {
  5425. SDValue AddPtr = PtrOff;
  5426. if (!isLittleEndian) {
  5427. SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
  5428. PtrOff.getValueType());
  5429. AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
  5430. }
  5431. Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
  5432. CallSeqStart,
  5433. Flags, DAG, dl);
  5434. ArgOffset += PtrByteSize;
  5435. continue;
  5436. }
  5437. // Copy the object to parameter save area if it can not be entirely passed
  5438. // by registers.
  5439. // FIXME: we only need to copy the parts which need to be passed in
  5440. // parameter save area. For the parts passed by registers, we don't need
  5441. // to copy them to the stack although we need to allocate space for them
  5442. // in parameter save area.
  5443. if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
  5444. Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
  5445. CallSeqStart,
  5446. Flags, DAG, dl);
  5447. // When a register is available, pass a small aggregate right-justified.
  5448. if (Size < 8 && GPR_idx != NumGPRs) {
  5449. // The easiest way to get this right-justified in a register
  5450. // is to copy the structure into the rightmost portion of a
  5451. // local variable slot, then load the whole slot into the
  5452. // register.
  5453. // FIXME: The memcpy seems to produce pretty awful code for
  5454. // small aggregates, particularly for packed ones.
  5455. // FIXME: It would be preferable to use the slot in the
  5456. // parameter save area instead of a new local variable.
  5457. SDValue AddPtr = PtrOff;
  5458. if (!isLittleEndian) {
  5459. SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
  5460. AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
  5461. }
  5462. Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
  5463. CallSeqStart,
  5464. Flags, DAG, dl);
  5465. // Load the slot into the register.
  5466. SDValue Load =
  5467. DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
  5468. MemOpChains.push_back(Load.getValue(1));
  5469. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
  5470. // Done with this argument.
  5471. ArgOffset += PtrByteSize;
  5472. continue;
  5473. }
  5474. // For aggregates larger than PtrByteSize, copy the pieces of the
  5475. // object that fit into registers from the parameter save area.
  5476. for (unsigned j=0; j<Size; j+=PtrByteSize) {
  5477. SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
  5478. SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
  5479. if (GPR_idx != NumGPRs) {
  5480. SDValue Load =
  5481. DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
  5482. MemOpChains.push_back(Load.getValue(1));
  5483. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
  5484. ArgOffset += PtrByteSize;
  5485. } else {
  5486. ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
  5487. break;
  5488. }
  5489. }
  5490. continue;
  5491. }
  5492. switch (Arg.getSimpleValueType().SimpleTy) {
  5493. default: llvm_unreachable("Unexpected ValueType for argument!");
  5494. case MVT::i1:
  5495. case MVT::i32:
  5496. case MVT::i64:
  5497. if (Flags.isNest()) {
  5498. // The 'nest' parameter, if any, is passed in R11.
  5499. RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
  5500. break;
  5501. }
  5502. // These can be scalar arguments or elements of an integer array type
  5503. // passed directly. Clang may use those instead of "byval" aggregate
  5504. // types to avoid forcing arguments to memory unnecessarily.
  5505. if (GPR_idx != NumGPRs) {
  5506. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
  5507. } else {
  5508. if (IsFastCall)
  5509. ComputePtrOff();
  5510. assert(HasParameterArea &&
  5511. "Parameter area must exist to pass an argument in memory.");
  5512. LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
  5513. true, CFlags.IsTailCall, false, MemOpChains,
  5514. TailCallArguments, dl);
  5515. if (IsFastCall)
  5516. ArgOffset += PtrByteSize;
  5517. }
  5518. if (!IsFastCall)
  5519. ArgOffset += PtrByteSize;
  5520. break;
  5521. case MVT::f32:
  5522. case MVT::f64: {
  5523. // These can be scalar arguments or elements of a float array type
  5524. // passed directly. The latter are used to implement ELFv2 homogenous
  5525. // float aggregates.
  5526. // Named arguments go into FPRs first, and once they overflow, the
  5527. // remaining arguments go into GPRs and then the parameter save area.
  5528. // Unnamed arguments for vararg functions always go to GPRs and
  5529. // then the parameter save area. For now, put all arguments to vararg
  5530. // routines always in both locations (FPR *and* GPR or stack slot).
  5531. bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
  5532. bool NeededLoad = false;
  5533. // First load the argument into the next available FPR.
  5534. if (FPR_idx != NumFPRs)
  5535. RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
  5536. // Next, load the argument into GPR or stack slot if needed.
  5537. if (!NeedGPROrStack)
  5538. ;
  5539. else if (GPR_idx != NumGPRs && !IsFastCall) {
  5540. // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
  5541. // once we support fp <-> gpr moves.
  5542. // In the non-vararg case, this can only ever happen in the
  5543. // presence of f32 array types, since otherwise we never run
  5544. // out of FPRs before running out of GPRs.
  5545. SDValue ArgVal;
  5546. // Double values are always passed in a single GPR.
  5547. if (Arg.getValueType() != MVT::f32) {
  5548. ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
  5549. // Non-array float values are extended and passed in a GPR.
  5550. } else if (!Flags.isInConsecutiveRegs()) {
  5551. ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
  5552. ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
  5553. // If we have an array of floats, we collect every odd element
  5554. // together with its predecessor into one GPR.
  5555. } else if (ArgOffset % PtrByteSize != 0) {
  5556. SDValue Lo, Hi;
  5557. Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
  5558. Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
  5559. if (!isLittleEndian)
  5560. std::swap(Lo, Hi);
  5561. ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
  5562. // The final element, if even, goes into the first half of a GPR.
  5563. } else if (Flags.isInConsecutiveRegsLast()) {
  5564. ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
  5565. ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
  5566. if (!isLittleEndian)
  5567. ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
  5568. DAG.getConstant(32, dl, MVT::i32));
  5569. // Non-final even elements are skipped; they will be handled
  5570. // together the with subsequent argument on the next go-around.
  5571. } else
  5572. ArgVal = SDValue();
  5573. if (ArgVal.getNode())
  5574. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
  5575. } else {
  5576. if (IsFastCall)
  5577. ComputePtrOff();
  5578. // Single-precision floating-point values are mapped to the
  5579. // second (rightmost) word of the stack doubleword.
  5580. if (Arg.getValueType() == MVT::f32 &&
  5581. !isLittleEndian && !Flags.isInConsecutiveRegs()) {
  5582. SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
  5583. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
  5584. }
  5585. assert(HasParameterArea &&
  5586. "Parameter area must exist to pass an argument in memory.");
  5587. LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
  5588. true, CFlags.IsTailCall, false, MemOpChains,
  5589. TailCallArguments, dl);
  5590. NeededLoad = true;
  5591. }
  5592. // When passing an array of floats, the array occupies consecutive
  5593. // space in the argument area; only round up to the next doubleword
  5594. // at the end of the array. Otherwise, each float takes 8 bytes.
  5595. if (!IsFastCall || NeededLoad) {
  5596. ArgOffset += (Arg.getValueType() == MVT::f32 &&
  5597. Flags.isInConsecutiveRegs()) ? 4 : 8;
  5598. if (Flags.isInConsecutiveRegsLast())
  5599. ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
  5600. }
  5601. break;
  5602. }
  5603. case MVT::v4f32:
  5604. case MVT::v4i32:
  5605. case MVT::v8i16:
  5606. case MVT::v16i8:
  5607. case MVT::v2f64:
  5608. case MVT::v2i64:
  5609. case MVT::v1i128:
  5610. case MVT::f128:
  5611. // These can be scalar arguments or elements of a vector array type
  5612. // passed directly. The latter are used to implement ELFv2 homogenous
  5613. // vector aggregates.
  5614. // For a varargs call, named arguments go into VRs or on the stack as
  5615. // usual; unnamed arguments always go to the stack or the corresponding
  5616. // GPRs when within range. For now, we always put the value in both
  5617. // locations (or even all three).
  5618. if (CFlags.IsVarArg) {
  5619. assert(HasParameterArea &&
  5620. "Parameter area must exist if we have a varargs call.");
  5621. // We could elide this store in the case where the object fits
  5622. // entirely in R registers. Maybe later.
  5623. SDValue Store =
  5624. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
  5625. MemOpChains.push_back(Store);
  5626. if (VR_idx != NumVRs) {
  5627. SDValue Load =
  5628. DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
  5629. MemOpChains.push_back(Load.getValue(1));
  5630. RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
  5631. }
  5632. ArgOffset += 16;
  5633. for (unsigned i=0; i<16; i+=PtrByteSize) {
  5634. if (GPR_idx == NumGPRs)
  5635. break;
  5636. SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
  5637. DAG.getConstant(i, dl, PtrVT));
  5638. SDValue Load =
  5639. DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
  5640. MemOpChains.push_back(Load.getValue(1));
  5641. RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
  5642. }
  5643. break;
  5644. }
  5645. // Non-varargs Altivec params go into VRs or on the stack.
  5646. if (VR_idx != NumVRs) {
  5647. RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
  5648. } else {
  5649. if (IsFastCall)
  5650. ComputePtrOff();
  5651. assert(HasParameterArea &&
  5652. "Parameter area must exist to pass an argument in memory.");
  5653. LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
  5654. true, CFlags.IsTailCall, true, MemOpChains,
  5655. TailCallArguments, dl);
  5656. if (IsFastCall)
  5657. ArgOffset += 16;
  5658. }
  5659. if (!IsFastCall)
  5660. ArgOffset += 16;
  5661. break;
  5662. }
  5663. }
  5664. assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
  5665. "mismatch in size of parameter area");
  5666. (void)NumBytesActuallyUsed;
  5667. if (!MemOpChains.empty())
  5668. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
  5669. // Check if this is an indirect call (MTCTR/BCTRL).
  5670. // See prepareDescriptorIndirectCall and buildCallOperands for more
  5671. // information about calls through function pointers in the 64-bit SVR4 ABI.
  5672. if (CFlags.IsIndirect) {
  5673. // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
  5674. // caller in the TOC save area.
  5675. if (isTOCSaveRestoreRequired(Subtarget)) {
  5676. assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
  5677. // Load r2 into a virtual register and store it to the TOC save area.
  5678. setUsesTOCBasePtr(DAG);
  5679. SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
  5680. // TOC save area offset.
  5681. unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
  5682. SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
  5683. SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  5684. Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
  5685. MachinePointerInfo::getStack(
  5686. DAG.getMachineFunction(), TOCSaveOffset));
  5687. }
  5688. // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
  5689. // This does not mean the MTCTR instruction must use R12; it's easier
  5690. // to model this as an extra parameter, so do that.
  5691. if (isELFv2ABI && !CFlags.IsPatchPoint)
  5692. RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
  5693. }
  5694. // Build a sequence of copy-to-reg nodes chained together with token chain
  5695. // and flag operands which copy the outgoing args into the appropriate regs.
  5696. SDValue InFlag;
  5697. for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
  5698. Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
  5699. RegsToPass[i].second, InFlag);
  5700. InFlag = Chain.getValue(1);
  5701. }
  5702. if (CFlags.IsTailCall && !IsSibCall)
  5703. PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
  5704. TailCallArguments);
  5705. return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
  5706. Callee, SPDiff, NumBytes, Ins, InVals, CB);
  5707. }
  5708. // Returns true when the shadow of a general purpose argument register
  5709. // in the parameter save area is aligned to at least 'RequiredAlign'.
  5710. static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
  5711. assert(RequiredAlign.value() <= 16 &&
  5712. "Required alignment greater than stack alignment.");
  5713. switch (Reg) {
  5714. default:
  5715. report_fatal_error("called on invalid register.");
  5716. case PPC::R5:
  5717. case PPC::R9:
  5718. case PPC::X3:
  5719. case PPC::X5:
  5720. case PPC::X7:
  5721. case PPC::X9:
  5722. // These registers are 16 byte aligned which is the most strict aligment
  5723. // we can support.
  5724. return true;
  5725. case PPC::R3:
  5726. case PPC::R7:
  5727. case PPC::X4:
  5728. case PPC::X6:
  5729. case PPC::X8:
  5730. case PPC::X10:
  5731. // The shadow of these registers in the PSA is 8 byte aligned.
  5732. return RequiredAlign <= 8;
  5733. case PPC::R4:
  5734. case PPC::R6:
  5735. case PPC::R8:
  5736. case PPC::R10:
  5737. return RequiredAlign <= 4;
  5738. }
  5739. }
  5740. static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
  5741. CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
  5742. CCState &S) {
  5743. AIXCCState &State = static_cast<AIXCCState &>(S);
  5744. const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
  5745. State.getMachineFunction().getSubtarget());
  5746. const bool IsPPC64 = Subtarget.isPPC64();
  5747. const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
  5748. const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
  5749. if (ValVT == MVT::f128)
  5750. report_fatal_error("f128 is unimplemented on AIX.");
  5751. if (ArgFlags.isNest())
  5752. report_fatal_error("Nest arguments are unimplemented.");
  5753. static const MCPhysReg GPR_32[] = {// 32-bit registers.
  5754. PPC::R3, PPC::R4, PPC::R5, PPC::R6,
  5755. PPC::R7, PPC::R8, PPC::R9, PPC::R10};
  5756. static const MCPhysReg GPR_64[] = {// 64-bit registers.
  5757. PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  5758. PPC::X7, PPC::X8, PPC::X9, PPC::X10};
  5759. static const MCPhysReg VR[] = {// Vector registers.
  5760. PPC::V2, PPC::V3, PPC::V4, PPC::V5,
  5761. PPC::V6, PPC::V7, PPC::V8, PPC::V9,
  5762. PPC::V10, PPC::V11, PPC::V12, PPC::V13};
  5763. if (ArgFlags.isByVal()) {
  5764. if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
  5765. report_fatal_error("Pass-by-value arguments with alignment greater than "
  5766. "register width are not supported.");
  5767. const unsigned ByValSize = ArgFlags.getByValSize();
  5768. // An empty aggregate parameter takes up no storage and no registers,
  5769. // but needs a MemLoc for a stack slot for the formal arguments side.
  5770. if (ByValSize == 0) {
  5771. State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
  5772. State.getNextStackOffset(), RegVT,
  5773. LocInfo));
  5774. return false;
  5775. }
  5776. const unsigned StackSize = alignTo(ByValSize, PtrAlign);
  5777. unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
  5778. for (const unsigned E = Offset + StackSize; Offset < E;
  5779. Offset += PtrAlign.value()) {
  5780. if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
  5781. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
  5782. else {
  5783. State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
  5784. Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
  5785. LocInfo));
  5786. break;
  5787. }
  5788. }
  5789. return false;
  5790. }
  5791. // Arguments always reserve parameter save area.
  5792. switch (ValVT.SimpleTy) {
  5793. default:
  5794. report_fatal_error("Unhandled value type for argument.");
  5795. case MVT::i64:
  5796. // i64 arguments should have been split to i32 for PPC32.
  5797. assert(IsPPC64 && "PPC32 should have split i64 values.");
  5798. LLVM_FALLTHROUGH;
  5799. case MVT::i1:
  5800. case MVT::i32: {
  5801. const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
  5802. // AIX integer arguments are always passed in register width.
  5803. if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
  5804. LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
  5805. : CCValAssign::LocInfo::ZExt;
  5806. if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
  5807. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
  5808. else
  5809. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
  5810. return false;
  5811. }
  5812. case MVT::f32:
  5813. case MVT::f64: {
  5814. // Parameter save area (PSA) is reserved even if the float passes in fpr.
  5815. const unsigned StoreSize = LocVT.getStoreSize();
  5816. // Floats are always 4-byte aligned in the PSA on AIX.
  5817. // This includes f64 in 64-bit mode for ABI compatibility.
  5818. const unsigned Offset =
  5819. State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
  5820. unsigned FReg = State.AllocateReg(FPR);
  5821. if (FReg)
  5822. State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
  5823. // Reserve and initialize GPRs or initialize the PSA as required.
  5824. for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
  5825. if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
  5826. assert(FReg && "An FPR should be available when a GPR is reserved.");
  5827. if (State.isVarArg()) {
  5828. // Successfully reserved GPRs are only initialized for vararg calls.
  5829. // Custom handling is required for:
  5830. // f64 in PPC32 needs to be split into 2 GPRs.
  5831. // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
  5832. State.addLoc(
  5833. CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
  5834. }
  5835. } else {
  5836. // If there are insufficient GPRs, the PSA needs to be initialized.
  5837. // Initialization occurs even if an FPR was initialized for
  5838. // compatibility with the AIX XL compiler. The full memory for the
  5839. // argument will be initialized even if a prior word is saved in GPR.
  5840. // A custom memLoc is used when the argument also passes in FPR so
  5841. // that the callee handling can skip over it easily.
  5842. State.addLoc(
  5843. FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
  5844. LocInfo)
  5845. : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5846. break;
  5847. }
  5848. }
  5849. return false;
  5850. }
  5851. case MVT::v4f32:
  5852. case MVT::v4i32:
  5853. case MVT::v8i16:
  5854. case MVT::v16i8:
  5855. case MVT::v2i64:
  5856. case MVT::v2f64:
  5857. case MVT::v1i128: {
  5858. const unsigned VecSize = 16;
  5859. const Align VecAlign(VecSize);
  5860. if (!State.isVarArg()) {
  5861. // If there are vector registers remaining we don't consume any stack
  5862. // space.
  5863. if (unsigned VReg = State.AllocateReg(VR)) {
  5864. State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
  5865. return false;
  5866. }
  5867. // Vectors passed on the stack do not shadow GPRs or FPRs even though they
  5868. // might be allocated in the portion of the PSA that is shadowed by the
  5869. // GPRs.
  5870. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5871. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5872. return false;
  5873. }
  5874. const unsigned PtrSize = IsPPC64 ? 8 : 4;
  5875. ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
  5876. unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
  5877. // Burn any underaligned registers and their shadowed stack space until
  5878. // we reach the required alignment.
  5879. while (NextRegIndex != GPRs.size() &&
  5880. !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
  5881. // Shadow allocate register and its stack shadow.
  5882. unsigned Reg = State.AllocateReg(GPRs);
  5883. State.AllocateStack(PtrSize, PtrAlign);
  5884. assert(Reg && "Allocating register unexpectedly failed.");
  5885. (void)Reg;
  5886. NextRegIndex = State.getFirstUnallocated(GPRs);
  5887. }
  5888. // Vectors that are passed as fixed arguments are handled differently.
  5889. // They are passed in VRs if any are available (unlike arguments passed
  5890. // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
  5891. // functions)
  5892. if (State.isFixed(ValNo)) {
  5893. if (unsigned VReg = State.AllocateReg(VR)) {
  5894. State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
  5895. // Shadow allocate GPRs and stack space even though we pass in a VR.
  5896. for (unsigned I = 0; I != VecSize; I += PtrSize)
  5897. State.AllocateReg(GPRs);
  5898. State.AllocateStack(VecSize, VecAlign);
  5899. return false;
  5900. }
  5901. // No vector registers remain so pass on the stack.
  5902. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5903. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5904. return false;
  5905. }
  5906. // If all GPRS are consumed then we pass the argument fully on the stack.
  5907. if (NextRegIndex == GPRs.size()) {
  5908. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5909. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5910. return false;
  5911. }
  5912. // Corner case for 32-bit codegen. We have 2 registers to pass the first
  5913. // half of the argument, and then need to pass the remaining half on the
  5914. // stack.
  5915. if (GPRs[NextRegIndex] == PPC::R9) {
  5916. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5917. State.addLoc(
  5918. CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5919. const unsigned FirstReg = State.AllocateReg(PPC::R9);
  5920. const unsigned SecondReg = State.AllocateReg(PPC::R10);
  5921. assert(FirstReg && SecondReg &&
  5922. "Allocating R9 or R10 unexpectedly failed.");
  5923. State.addLoc(
  5924. CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
  5925. State.addLoc(
  5926. CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
  5927. return false;
  5928. }
  5929. // We have enough GPRs to fully pass the vector argument, and we have
  5930. // already consumed any underaligned registers. Start with the custom
  5931. // MemLoc and then the custom RegLocs.
  5932. const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
  5933. State.addLoc(
  5934. CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
  5935. for (unsigned I = 0; I != VecSize; I += PtrSize) {
  5936. const unsigned Reg = State.AllocateReg(GPRs);
  5937. assert(Reg && "Failed to allocated register for vararg vector argument");
  5938. State.addLoc(
  5939. CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
  5940. }
  5941. return false;
  5942. }
  5943. }
  5944. return true;
  5945. }
  5946. // So far, this function is only used by LowerFormalArguments_AIX()
  5947. static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
  5948. bool IsPPC64,
  5949. bool HasP8Vector,
  5950. bool HasVSX) {
  5951. assert((IsPPC64 || SVT != MVT::i64) &&
  5952. "i64 should have been split for 32-bit codegen.");
  5953. switch (SVT) {
  5954. default:
  5955. report_fatal_error("Unexpected value type for formal argument");
  5956. case MVT::i1:
  5957. case MVT::i32:
  5958. case MVT::i64:
  5959. return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  5960. case MVT::f32:
  5961. return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
  5962. case MVT::f64:
  5963. return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
  5964. case MVT::v4f32:
  5965. case MVT::v4i32:
  5966. case MVT::v8i16:
  5967. case MVT::v16i8:
  5968. case MVT::v2i64:
  5969. case MVT::v2f64:
  5970. case MVT::v1i128:
  5971. return &PPC::VRRCRegClass;
  5972. }
  5973. }
  5974. static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
  5975. SelectionDAG &DAG, SDValue ArgValue,
  5976. MVT LocVT, const SDLoc &dl) {
  5977. assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
  5978. assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
  5979. if (Flags.isSExt())
  5980. ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
  5981. DAG.getValueType(ValVT));
  5982. else if (Flags.isZExt())
  5983. ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
  5984. DAG.getValueType(ValVT));
  5985. return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
  5986. }
  5987. static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
  5988. const unsigned LASize = FL->getLinkageSize();
  5989. if (PPC::GPRCRegClass.contains(Reg)) {
  5990. assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
  5991. "Reg must be a valid argument register!");
  5992. return LASize + 4 * (Reg - PPC::R3);
  5993. }
  5994. if (PPC::G8RCRegClass.contains(Reg)) {
  5995. assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
  5996. "Reg must be a valid argument register!");
  5997. return LASize + 8 * (Reg - PPC::X3);
  5998. }
  5999. llvm_unreachable("Only general purpose registers expected.");
  6000. }
  6001. // AIX ABI Stack Frame Layout:
  6002. //
  6003. // Low Memory +--------------------------------------------+
  6004. // SP +---> | Back chain | ---+
  6005. // | +--------------------------------------------+ |
  6006. // | | Saved Condition Register | |
  6007. // | +--------------------------------------------+ |
  6008. // | | Saved Linkage Register | |
  6009. // | +--------------------------------------------+ | Linkage Area
  6010. // | | Reserved for compilers | |
  6011. // | +--------------------------------------------+ |
  6012. // | | Reserved for binders | |
  6013. // | +--------------------------------------------+ |
  6014. // | | Saved TOC pointer | ---+
  6015. // | +--------------------------------------------+
  6016. // | | Parameter save area |
  6017. // | +--------------------------------------------+
  6018. // | | Alloca space |
  6019. // | +--------------------------------------------+
  6020. // | | Local variable space |
  6021. // | +--------------------------------------------+
  6022. // | | Float/int conversion temporary |
  6023. // | +--------------------------------------------+
  6024. // | | Save area for AltiVec registers |
  6025. // | +--------------------------------------------+
  6026. // | | AltiVec alignment padding |
  6027. // | +--------------------------------------------+
  6028. // | | Save area for VRSAVE register |
  6029. // | +--------------------------------------------+
  6030. // | | Save area for General Purpose registers |
  6031. // | +--------------------------------------------+
  6032. // | | Save area for Floating Point registers |
  6033. // | +--------------------------------------------+
  6034. // +---- | Back chain |
  6035. // High Memory +--------------------------------------------+
  6036. //
  6037. // Specifications:
  6038. // AIX 7.2 Assembler Language Reference
  6039. // Subroutine linkage convention
  6040. SDValue PPCTargetLowering::LowerFormalArguments_AIX(
  6041. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  6042. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  6043. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  6044. assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
  6045. CallConv == CallingConv::Fast) &&
  6046. "Unexpected calling convention!");
  6047. if (getTargetMachine().Options.GuaranteedTailCallOpt)
  6048. report_fatal_error("Tail call support is unimplemented on AIX.");
  6049. if (useSoftFloat())
  6050. report_fatal_error("Soft float support is unimplemented on AIX.");
  6051. const PPCSubtarget &Subtarget =
  6052. static_cast<const PPCSubtarget &>(DAG.getSubtarget());
  6053. const bool IsPPC64 = Subtarget.isPPC64();
  6054. const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
  6055. // Assign locations to all of the incoming arguments.
  6056. SmallVector<CCValAssign, 16> ArgLocs;
  6057. MachineFunction &MF = DAG.getMachineFunction();
  6058. MachineFrameInfo &MFI = MF.getFrameInfo();
  6059. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  6060. AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
  6061. const EVT PtrVT = getPointerTy(MF.getDataLayout());
  6062. // Reserve space for the linkage area on the stack.
  6063. const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  6064. CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
  6065. CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
  6066. SmallVector<SDValue, 8> MemOps;
  6067. for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
  6068. CCValAssign &VA = ArgLocs[I++];
  6069. MVT LocVT = VA.getLocVT();
  6070. MVT ValVT = VA.getValVT();
  6071. ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
  6072. // For compatibility with the AIX XL compiler, the float args in the
  6073. // parameter save area are initialized even if the argument is available
  6074. // in register. The caller is required to initialize both the register
  6075. // and memory, however, the callee can choose to expect it in either.
  6076. // The memloc is dismissed here because the argument is retrieved from
  6077. // the register.
  6078. if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
  6079. continue;
  6080. auto HandleMemLoc = [&]() {
  6081. const unsigned LocSize = LocVT.getStoreSize();
  6082. const unsigned ValSize = ValVT.getStoreSize();
  6083. assert((ValSize <= LocSize) &&
  6084. "Object size is larger than size of MemLoc");
  6085. int CurArgOffset = VA.getLocMemOffset();
  6086. // Objects are right-justified because AIX is big-endian.
  6087. if (LocSize > ValSize)
  6088. CurArgOffset += LocSize - ValSize;
  6089. // Potential tail calls could cause overwriting of argument stack slots.
  6090. const bool IsImmutable =
  6091. !(getTargetMachine().Options.GuaranteedTailCallOpt &&
  6092. (CallConv == CallingConv::Fast));
  6093. int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
  6094. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  6095. SDValue ArgValue =
  6096. DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
  6097. InVals.push_back(ArgValue);
  6098. };
  6099. // Vector arguments to VaArg functions are passed both on the stack, and
  6100. // in any available GPRs. Load the value from the stack and add the GPRs
  6101. // as live ins.
  6102. if (VA.isMemLoc() && VA.needsCustom()) {
  6103. assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
  6104. assert(isVarArg && "Only use custom memloc for vararg.");
  6105. // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
  6106. // matching custom RegLocs.
  6107. const unsigned OriginalValNo = VA.getValNo();
  6108. (void)OriginalValNo;
  6109. auto HandleCustomVecRegLoc = [&]() {
  6110. assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
  6111. "Missing custom RegLoc.");
  6112. VA = ArgLocs[I++];
  6113. assert(VA.getValVT().isVector() &&
  6114. "Unexpected Val type for custom RegLoc.");
  6115. assert(VA.getValNo() == OriginalValNo &&
  6116. "ValNo mismatch between custom MemLoc and RegLoc.");
  6117. MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
  6118. MF.addLiveIn(VA.getLocReg(),
  6119. getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
  6120. Subtarget.hasVSX()));
  6121. };
  6122. HandleMemLoc();
  6123. // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
  6124. // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
  6125. // R10.
  6126. HandleCustomVecRegLoc();
  6127. HandleCustomVecRegLoc();
  6128. // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
  6129. // we passed the vector in R5, R6, R7 and R8.
  6130. if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
  6131. assert(!IsPPC64 &&
  6132. "Only 2 custom RegLocs expected for 64-bit codegen.");
  6133. HandleCustomVecRegLoc();
  6134. HandleCustomVecRegLoc();
  6135. }
  6136. continue;
  6137. }
  6138. if (VA.isRegLoc()) {
  6139. if (VA.getValVT().isScalarInteger())
  6140. FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
  6141. else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
  6142. switch (VA.getValVT().SimpleTy) {
  6143. default:
  6144. report_fatal_error("Unhandled value type for argument.");
  6145. case MVT::f32:
  6146. FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
  6147. break;
  6148. case MVT::f64:
  6149. FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
  6150. break;
  6151. }
  6152. } else if (VA.getValVT().isVector()) {
  6153. switch (VA.getValVT().SimpleTy) {
  6154. default:
  6155. report_fatal_error("Unhandled value type for argument.");
  6156. case MVT::v16i8:
  6157. FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
  6158. break;
  6159. case MVT::v8i16:
  6160. FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
  6161. break;
  6162. case MVT::v4i32:
  6163. case MVT::v2i64:
  6164. case MVT::v1i128:
  6165. FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
  6166. break;
  6167. case MVT::v4f32:
  6168. case MVT::v2f64:
  6169. FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
  6170. break;
  6171. }
  6172. }
  6173. }
  6174. if (Flags.isByVal() && VA.isMemLoc()) {
  6175. const unsigned Size =
  6176. alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
  6177. PtrByteSize);
  6178. const int FI = MF.getFrameInfo().CreateFixedObject(
  6179. Size, VA.getLocMemOffset(), /* IsImmutable */ false,
  6180. /* IsAliased */ true);
  6181. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  6182. InVals.push_back(FIN);
  6183. continue;
  6184. }
  6185. if (Flags.isByVal()) {
  6186. assert(VA.isRegLoc() && "MemLocs should already be handled.");
  6187. const MCPhysReg ArgReg = VA.getLocReg();
  6188. const PPCFrameLowering *FL = Subtarget.getFrameLowering();
  6189. if (Flags.getNonZeroByValAlign() > PtrByteSize)
  6190. report_fatal_error("Over aligned byvals not supported yet.");
  6191. const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
  6192. const int FI = MF.getFrameInfo().CreateFixedObject(
  6193. StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
  6194. /* IsAliased */ true);
  6195. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  6196. InVals.push_back(FIN);
  6197. // Add live ins for all the RegLocs for the same ByVal.
  6198. const TargetRegisterClass *RegClass =
  6199. IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  6200. auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
  6201. unsigned Offset) {
  6202. const Register VReg = MF.addLiveIn(PhysReg, RegClass);
  6203. // Since the callers side has left justified the aggregate in the
  6204. // register, we can simply store the entire register into the stack
  6205. // slot.
  6206. SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
  6207. // The store to the fixedstack object is needed becuase accessing a
  6208. // field of the ByVal will use a gep and load. Ideally we will optimize
  6209. // to extracting the value from the register directly, and elide the
  6210. // stores when the arguments address is not taken, but that will need to
  6211. // be future work.
  6212. SDValue Store = DAG.getStore(
  6213. CopyFrom.getValue(1), dl, CopyFrom,
  6214. DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
  6215. MachinePointerInfo::getFixedStack(MF, FI, Offset));
  6216. MemOps.push_back(Store);
  6217. };
  6218. unsigned Offset = 0;
  6219. HandleRegLoc(VA.getLocReg(), Offset);
  6220. Offset += PtrByteSize;
  6221. for (; Offset != StackSize && ArgLocs[I].isRegLoc();
  6222. Offset += PtrByteSize) {
  6223. assert(ArgLocs[I].getValNo() == VA.getValNo() &&
  6224. "RegLocs should be for ByVal argument.");
  6225. const CCValAssign RL = ArgLocs[I++];
  6226. HandleRegLoc(RL.getLocReg(), Offset);
  6227. FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
  6228. }
  6229. if (Offset != StackSize) {
  6230. assert(ArgLocs[I].getValNo() == VA.getValNo() &&
  6231. "Expected MemLoc for remaining bytes.");
  6232. assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
  6233. // Consume the MemLoc.The InVal has already been emitted, so nothing
  6234. // more needs to be done.
  6235. ++I;
  6236. }
  6237. continue;
  6238. }
  6239. if (VA.isRegLoc() && !VA.needsCustom()) {
  6240. MVT::SimpleValueType SVT = ValVT.SimpleTy;
  6241. Register VReg =
  6242. MF.addLiveIn(VA.getLocReg(),
  6243. getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
  6244. Subtarget.hasVSX()));
  6245. SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
  6246. if (ValVT.isScalarInteger() &&
  6247. (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
  6248. ArgValue =
  6249. truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
  6250. }
  6251. InVals.push_back(ArgValue);
  6252. continue;
  6253. }
  6254. if (VA.isMemLoc()) {
  6255. HandleMemLoc();
  6256. continue;
  6257. }
  6258. }
  6259. // On AIX a minimum of 8 words is saved to the parameter save area.
  6260. const unsigned MinParameterSaveArea = 8 * PtrByteSize;
  6261. // Area that is at least reserved in the caller of this function.
  6262. unsigned CallerReservedArea =
  6263. std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
  6264. // Set the size that is at least reserved in caller of this function. Tail
  6265. // call optimized function's reserved stack space needs to be aligned so
  6266. // that taking the difference between two stack areas will result in an
  6267. // aligned stack.
  6268. CallerReservedArea =
  6269. EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
  6270. FuncInfo->setMinReservedArea(CallerReservedArea);
  6271. if (isVarArg) {
  6272. FuncInfo->setVarArgsFrameIndex(
  6273. MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
  6274. SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
  6275. static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
  6276. PPC::R7, PPC::R8, PPC::R9, PPC::R10};
  6277. static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
  6278. PPC::X7, PPC::X8, PPC::X9, PPC::X10};
  6279. const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
  6280. // The fixed integer arguments of a variadic function are stored to the
  6281. // VarArgsFrameIndex on the stack so that they may be loaded by
  6282. // dereferencing the result of va_next.
  6283. for (unsigned GPRIndex =
  6284. (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
  6285. GPRIndex < NumGPArgRegs; ++GPRIndex) {
  6286. const Register VReg =
  6287. IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
  6288. : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
  6289. SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
  6290. SDValue Store =
  6291. DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
  6292. MemOps.push_back(Store);
  6293. // Increment the address for the next argument to store.
  6294. SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
  6295. FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
  6296. }
  6297. }
  6298. if (!MemOps.empty())
  6299. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
  6300. return Chain;
  6301. }
  6302. SDValue PPCTargetLowering::LowerCall_AIX(
  6303. SDValue Chain, SDValue Callee, CallFlags CFlags,
  6304. const SmallVectorImpl<ISD::OutputArg> &Outs,
  6305. const SmallVectorImpl<SDValue> &OutVals,
  6306. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
  6307. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
  6308. const CallBase *CB) const {
  6309. // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
  6310. // AIX ABI stack frame layout.
  6311. assert((CFlags.CallConv == CallingConv::C ||
  6312. CFlags.CallConv == CallingConv::Cold ||
  6313. CFlags.CallConv == CallingConv::Fast) &&
  6314. "Unexpected calling convention!");
  6315. if (CFlags.IsPatchPoint)
  6316. report_fatal_error("This call type is unimplemented on AIX.");
  6317. const PPCSubtarget& Subtarget =
  6318. static_cast<const PPCSubtarget&>(DAG.getSubtarget());
  6319. MachineFunction &MF = DAG.getMachineFunction();
  6320. SmallVector<CCValAssign, 16> ArgLocs;
  6321. AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
  6322. *DAG.getContext());
  6323. // Reserve space for the linkage save area (LSA) on the stack.
  6324. // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
  6325. // [SP][CR][LR][2 x reserved][TOC].
  6326. // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
  6327. const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
  6328. const bool IsPPC64 = Subtarget.isPPC64();
  6329. const EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6330. const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
  6331. CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
  6332. CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
  6333. // The prolog code of the callee may store up to 8 GPR argument registers to
  6334. // the stack, allowing va_start to index over them in memory if the callee
  6335. // is variadic.
  6336. // Because we cannot tell if this is needed on the caller side, we have to
  6337. // conservatively assume that it is needed. As such, make sure we have at
  6338. // least enough stack space for the caller to store the 8 GPRs.
  6339. const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
  6340. const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
  6341. CCInfo.getNextStackOffset());
  6342. // Adjust the stack pointer for the new arguments...
  6343. // These operations are automatically eliminated by the prolog/epilog pass.
  6344. Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
  6345. SDValue CallSeqStart = Chain;
  6346. SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
  6347. SmallVector<SDValue, 8> MemOpChains;
  6348. // Set up a copy of the stack pointer for loading and storing any
  6349. // arguments that may not fit in the registers available for argument
  6350. // passing.
  6351. const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
  6352. : DAG.getRegister(PPC::R1, MVT::i32);
  6353. for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
  6354. const unsigned ValNo = ArgLocs[I].getValNo();
  6355. SDValue Arg = OutVals[ValNo];
  6356. ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
  6357. if (Flags.isByVal()) {
  6358. const unsigned ByValSize = Flags.getByValSize();
  6359. // Nothing to do for zero-sized ByVals on the caller side.
  6360. if (!ByValSize) {
  6361. ++I;
  6362. continue;
  6363. }
  6364. auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
  6365. return DAG.getExtLoad(
  6366. ISD::ZEXTLOAD, dl, PtrVT, Chain,
  6367. (LoadOffset != 0)
  6368. ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
  6369. : Arg,
  6370. MachinePointerInfo(), VT);
  6371. };
  6372. unsigned LoadOffset = 0;
  6373. // Initialize registers, which are fully occupied by the by-val argument.
  6374. while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
  6375. SDValue Load = GetLoad(PtrVT, LoadOffset);
  6376. MemOpChains.push_back(Load.getValue(1));
  6377. LoadOffset += PtrByteSize;
  6378. const CCValAssign &ByValVA = ArgLocs[I++];
  6379. assert(ByValVA.getValNo() == ValNo &&
  6380. "Unexpected location for pass-by-value argument.");
  6381. RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
  6382. }
  6383. if (LoadOffset == ByValSize)
  6384. continue;
  6385. // There must be one more loc to handle the remainder.
  6386. assert(ArgLocs[I].getValNo() == ValNo &&
  6387. "Expected additional location for by-value argument.");
  6388. if (ArgLocs[I].isMemLoc()) {
  6389. assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
  6390. const CCValAssign &ByValVA = ArgLocs[I++];
  6391. ISD::ArgFlagsTy MemcpyFlags = Flags;
  6392. // Only memcpy the bytes that don't pass in register.
  6393. MemcpyFlags.setByValSize(ByValSize - LoadOffset);
  6394. Chain = CallSeqStart = createMemcpyOutsideCallSeq(
  6395. (LoadOffset != 0)
  6396. ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
  6397. : Arg,
  6398. DAG.getObjectPtrOffset(dl, StackPtr,
  6399. TypeSize::Fixed(ByValVA.getLocMemOffset())),
  6400. CallSeqStart, MemcpyFlags, DAG, dl);
  6401. continue;
  6402. }
  6403. // Initialize the final register residue.
  6404. // Any residue that occupies the final by-val arg register must be
  6405. // left-justified on AIX. Loads must be a power-of-2 size and cannot be
  6406. // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
  6407. // 2 and 1 byte loads.
  6408. const unsigned ResidueBytes = ByValSize % PtrByteSize;
  6409. assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
  6410. "Unexpected register residue for by-value argument.");
  6411. SDValue ResidueVal;
  6412. for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
  6413. const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
  6414. const MVT VT =
  6415. N == 1 ? MVT::i8
  6416. : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
  6417. SDValue Load = GetLoad(VT, LoadOffset);
  6418. MemOpChains.push_back(Load.getValue(1));
  6419. LoadOffset += N;
  6420. Bytes += N;
  6421. // By-val arguments are passed left-justfied in register.
  6422. // Every load here needs to be shifted, otherwise a full register load
  6423. // should have been used.
  6424. assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
  6425. "Unexpected load emitted during handling of pass-by-value "
  6426. "argument.");
  6427. unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
  6428. EVT ShiftAmountTy =
  6429. getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
  6430. SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
  6431. SDValue ShiftedLoad =
  6432. DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
  6433. ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
  6434. ShiftedLoad)
  6435. : ShiftedLoad;
  6436. }
  6437. const CCValAssign &ByValVA = ArgLocs[I++];
  6438. RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
  6439. continue;
  6440. }
  6441. CCValAssign &VA = ArgLocs[I++];
  6442. const MVT LocVT = VA.getLocVT();
  6443. const MVT ValVT = VA.getValVT();
  6444. switch (VA.getLocInfo()) {
  6445. default:
  6446. report_fatal_error("Unexpected argument extension type.");
  6447. case CCValAssign::Full:
  6448. break;
  6449. case CCValAssign::ZExt:
  6450. Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
  6451. break;
  6452. case CCValAssign::SExt:
  6453. Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
  6454. break;
  6455. }
  6456. if (VA.isRegLoc() && !VA.needsCustom()) {
  6457. RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
  6458. continue;
  6459. }
  6460. // Vector arguments passed to VarArg functions need custom handling when
  6461. // they are passed (at least partially) in GPRs.
  6462. if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
  6463. assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
  6464. // Store value to its stack slot.
  6465. SDValue PtrOff =
  6466. DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
  6467. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  6468. SDValue Store =
  6469. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
  6470. MemOpChains.push_back(Store);
  6471. const unsigned OriginalValNo = VA.getValNo();
  6472. // Then load the GPRs from the stack
  6473. unsigned LoadOffset = 0;
  6474. auto HandleCustomVecRegLoc = [&]() {
  6475. assert(I != E && "Unexpected end of CCvalAssigns.");
  6476. assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
  6477. "Expected custom RegLoc.");
  6478. CCValAssign RegVA = ArgLocs[I++];
  6479. assert(RegVA.getValNo() == OriginalValNo &&
  6480. "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
  6481. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
  6482. DAG.getConstant(LoadOffset, dl, PtrVT));
  6483. SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
  6484. MemOpChains.push_back(Load.getValue(1));
  6485. RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
  6486. LoadOffset += PtrByteSize;
  6487. };
  6488. // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
  6489. // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
  6490. // R10.
  6491. HandleCustomVecRegLoc();
  6492. HandleCustomVecRegLoc();
  6493. if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
  6494. ArgLocs[I].getValNo() == OriginalValNo) {
  6495. assert(!IsPPC64 &&
  6496. "Only 2 custom RegLocs expected for 64-bit codegen.");
  6497. HandleCustomVecRegLoc();
  6498. HandleCustomVecRegLoc();
  6499. }
  6500. continue;
  6501. }
  6502. if (VA.isMemLoc()) {
  6503. SDValue PtrOff =
  6504. DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
  6505. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  6506. MemOpChains.push_back(
  6507. DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
  6508. continue;
  6509. }
  6510. if (!ValVT.isFloatingPoint())
  6511. report_fatal_error(
  6512. "Unexpected register handling for calling convention.");
  6513. // Custom handling is used for GPR initializations for vararg float
  6514. // arguments.
  6515. assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
  6516. LocVT.isInteger() &&
  6517. "Custom register handling only expected for VarArg.");
  6518. SDValue ArgAsInt =
  6519. DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
  6520. if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
  6521. // f32 in 32-bit GPR
  6522. // f64 in 64-bit GPR
  6523. RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
  6524. else if (Arg.getValueType().getFixedSizeInBits() <
  6525. LocVT.getFixedSizeInBits())
  6526. // f32 in 64-bit GPR.
  6527. RegsToPass.push_back(std::make_pair(
  6528. VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
  6529. else {
  6530. // f64 in two 32-bit GPRs
  6531. // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
  6532. assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
  6533. "Unexpected custom register for argument!");
  6534. CCValAssign &GPR1 = VA;
  6535. SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
  6536. DAG.getConstant(32, dl, MVT::i8));
  6537. RegsToPass.push_back(std::make_pair(
  6538. GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
  6539. if (I != E) {
  6540. // If only 1 GPR was available, there will only be one custom GPR and
  6541. // the argument will also pass in memory.
  6542. CCValAssign &PeekArg = ArgLocs[I];
  6543. if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
  6544. assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
  6545. CCValAssign &GPR2 = ArgLocs[I++];
  6546. RegsToPass.push_back(std::make_pair(
  6547. GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
  6548. }
  6549. }
  6550. }
  6551. }
  6552. if (!MemOpChains.empty())
  6553. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
  6554. // For indirect calls, we need to save the TOC base to the stack for
  6555. // restoration after the call.
  6556. if (CFlags.IsIndirect) {
  6557. assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
  6558. const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
  6559. const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
  6560. const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
  6561. const unsigned TOCSaveOffset =
  6562. Subtarget.getFrameLowering()->getTOCSaveOffset();
  6563. setUsesTOCBasePtr(DAG);
  6564. SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
  6565. SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
  6566. SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
  6567. SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
  6568. Chain = DAG.getStore(
  6569. Val.getValue(1), dl, Val, AddPtr,
  6570. MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
  6571. }
  6572. // Build a sequence of copy-to-reg nodes chained together with token chain
  6573. // and flag operands which copy the outgoing args into the appropriate regs.
  6574. SDValue InFlag;
  6575. for (auto Reg : RegsToPass) {
  6576. Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
  6577. InFlag = Chain.getValue(1);
  6578. }
  6579. const int SPDiff = 0;
  6580. return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
  6581. Callee, SPDiff, NumBytes, Ins, InVals, CB);
  6582. }
  6583. bool
  6584. PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
  6585. MachineFunction &MF, bool isVarArg,
  6586. const SmallVectorImpl<ISD::OutputArg> &Outs,
  6587. LLVMContext &Context) const {
  6588. SmallVector<CCValAssign, 16> RVLocs;
  6589. CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
  6590. return CCInfo.CheckReturn(
  6591. Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
  6592. ? RetCC_PPC_Cold
  6593. : RetCC_PPC);
  6594. }
  6595. SDValue
  6596. PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
  6597. bool isVarArg,
  6598. const SmallVectorImpl<ISD::OutputArg> &Outs,
  6599. const SmallVectorImpl<SDValue> &OutVals,
  6600. const SDLoc &dl, SelectionDAG &DAG) const {
  6601. SmallVector<CCValAssign, 16> RVLocs;
  6602. CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
  6603. *DAG.getContext());
  6604. CCInfo.AnalyzeReturn(Outs,
  6605. (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
  6606. ? RetCC_PPC_Cold
  6607. : RetCC_PPC);
  6608. SDValue Flag;
  6609. SmallVector<SDValue, 4> RetOps(1, Chain);
  6610. // Copy the result values into the output registers.
  6611. for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
  6612. CCValAssign &VA = RVLocs[i];
  6613. assert(VA.isRegLoc() && "Can only return in registers!");
  6614. SDValue Arg = OutVals[RealResIdx];
  6615. switch (VA.getLocInfo()) {
  6616. default: llvm_unreachable("Unknown loc info!");
  6617. case CCValAssign::Full: break;
  6618. case CCValAssign::AExt:
  6619. Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
  6620. break;
  6621. case CCValAssign::ZExt:
  6622. Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
  6623. break;
  6624. case CCValAssign::SExt:
  6625. Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
  6626. break;
  6627. }
  6628. if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
  6629. bool isLittleEndian = Subtarget.isLittleEndian();
  6630. // Legalize ret f64 -> ret 2 x i32.
  6631. SDValue SVal =
  6632. DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
  6633. DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
  6634. Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
  6635. RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
  6636. SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
  6637. DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
  6638. Flag = Chain.getValue(1);
  6639. VA = RVLocs[++i]; // skip ahead to next loc
  6640. Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
  6641. } else
  6642. Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
  6643. Flag = Chain.getValue(1);
  6644. RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
  6645. }
  6646. RetOps[0] = Chain; // Update chain.
  6647. // Add the flag if we have it.
  6648. if (Flag.getNode())
  6649. RetOps.push_back(Flag);
  6650. return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
  6651. }
  6652. SDValue
  6653. PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
  6654. SelectionDAG &DAG) const {
  6655. SDLoc dl(Op);
  6656. // Get the correct type for integers.
  6657. EVT IntVT = Op.getValueType();
  6658. // Get the inputs.
  6659. SDValue Chain = Op.getOperand(0);
  6660. SDValue FPSIdx = getFramePointerFrameIndex(DAG);
  6661. // Build a DYNAREAOFFSET node.
  6662. SDValue Ops[2] = {Chain, FPSIdx};
  6663. SDVTList VTs = DAG.getVTList(IntVT);
  6664. return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
  6665. }
  6666. SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
  6667. SelectionDAG &DAG) const {
  6668. // When we pop the dynamic allocation we need to restore the SP link.
  6669. SDLoc dl(Op);
  6670. // Get the correct type for pointers.
  6671. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6672. // Construct the stack pointer operand.
  6673. bool isPPC64 = Subtarget.isPPC64();
  6674. unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
  6675. SDValue StackPtr = DAG.getRegister(SP, PtrVT);
  6676. // Get the operands for the STACKRESTORE.
  6677. SDValue Chain = Op.getOperand(0);
  6678. SDValue SaveSP = Op.getOperand(1);
  6679. // Load the old link SP.
  6680. SDValue LoadLinkSP =
  6681. DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
  6682. // Restore the stack pointer.
  6683. Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
  6684. // Store the old link SP.
  6685. return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
  6686. }
  6687. SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
  6688. MachineFunction &MF = DAG.getMachineFunction();
  6689. bool isPPC64 = Subtarget.isPPC64();
  6690. EVT PtrVT = getPointerTy(MF.getDataLayout());
  6691. // Get current frame pointer save index. The users of this index will be
  6692. // primarily DYNALLOC instructions.
  6693. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  6694. int RASI = FI->getReturnAddrSaveIndex();
  6695. // If the frame pointer save index hasn't been defined yet.
  6696. if (!RASI) {
  6697. // Find out what the fix offset of the frame pointer save area.
  6698. int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
  6699. // Allocate the frame index for frame pointer save area.
  6700. RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
  6701. // Save the result.
  6702. FI->setReturnAddrSaveIndex(RASI);
  6703. }
  6704. return DAG.getFrameIndex(RASI, PtrVT);
  6705. }
  6706. SDValue
  6707. PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
  6708. MachineFunction &MF = DAG.getMachineFunction();
  6709. bool isPPC64 = Subtarget.isPPC64();
  6710. EVT PtrVT = getPointerTy(MF.getDataLayout());
  6711. // Get current frame pointer save index. The users of this index will be
  6712. // primarily DYNALLOC instructions.
  6713. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
  6714. int FPSI = FI->getFramePointerSaveIndex();
  6715. // If the frame pointer save index hasn't been defined yet.
  6716. if (!FPSI) {
  6717. // Find out what the fix offset of the frame pointer save area.
  6718. int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
  6719. // Allocate the frame index for frame pointer save area.
  6720. FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
  6721. // Save the result.
  6722. FI->setFramePointerSaveIndex(FPSI);
  6723. }
  6724. return DAG.getFrameIndex(FPSI, PtrVT);
  6725. }
  6726. SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
  6727. SelectionDAG &DAG) const {
  6728. MachineFunction &MF = DAG.getMachineFunction();
  6729. // Get the inputs.
  6730. SDValue Chain = Op.getOperand(0);
  6731. SDValue Size = Op.getOperand(1);
  6732. SDLoc dl(Op);
  6733. // Get the correct type for pointers.
  6734. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6735. // Negate the size.
  6736. SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
  6737. DAG.getConstant(0, dl, PtrVT), Size);
  6738. // Construct a node for the frame pointer save index.
  6739. SDValue FPSIdx = getFramePointerFrameIndex(DAG);
  6740. SDValue Ops[3] = { Chain, NegSize, FPSIdx };
  6741. SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
  6742. if (hasInlineStackProbe(MF))
  6743. return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
  6744. return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
  6745. }
  6746. SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
  6747. SelectionDAG &DAG) const {
  6748. MachineFunction &MF = DAG.getMachineFunction();
  6749. bool isPPC64 = Subtarget.isPPC64();
  6750. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6751. int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
  6752. return DAG.getFrameIndex(FI, PtrVT);
  6753. }
  6754. SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
  6755. SelectionDAG &DAG) const {
  6756. SDLoc DL(Op);
  6757. return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
  6758. DAG.getVTList(MVT::i32, MVT::Other),
  6759. Op.getOperand(0), Op.getOperand(1));
  6760. }
  6761. SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
  6762. SelectionDAG &DAG) const {
  6763. SDLoc DL(Op);
  6764. return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
  6765. Op.getOperand(0), Op.getOperand(1));
  6766. }
  6767. SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
  6768. if (Op.getValueType().isVector())
  6769. return LowerVectorLoad(Op, DAG);
  6770. assert(Op.getValueType() == MVT::i1 &&
  6771. "Custom lowering only for i1 loads");
  6772. // First, load 8 bits into 32 bits, then truncate to 1 bit.
  6773. SDLoc dl(Op);
  6774. LoadSDNode *LD = cast<LoadSDNode>(Op);
  6775. SDValue Chain = LD->getChain();
  6776. SDValue BasePtr = LD->getBasePtr();
  6777. MachineMemOperand *MMO = LD->getMemOperand();
  6778. SDValue NewLD =
  6779. DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
  6780. BasePtr, MVT::i8, MMO);
  6781. SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
  6782. SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
  6783. return DAG.getMergeValues(Ops, dl);
  6784. }
  6785. SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
  6786. if (Op.getOperand(1).getValueType().isVector())
  6787. return LowerVectorStore(Op, DAG);
  6788. assert(Op.getOperand(1).getValueType() == MVT::i1 &&
  6789. "Custom lowering only for i1 stores");
  6790. // First, zero extend to 32 bits, then use a truncating store to 8 bits.
  6791. SDLoc dl(Op);
  6792. StoreSDNode *ST = cast<StoreSDNode>(Op);
  6793. SDValue Chain = ST->getChain();
  6794. SDValue BasePtr = ST->getBasePtr();
  6795. SDValue Value = ST->getValue();
  6796. MachineMemOperand *MMO = ST->getMemOperand();
  6797. Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
  6798. Value);
  6799. return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
  6800. }
  6801. // FIXME: Remove this once the ANDI glue bug is fixed:
  6802. SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
  6803. assert(Op.getValueType() == MVT::i1 &&
  6804. "Custom lowering only for i1 results");
  6805. SDLoc DL(Op);
  6806. return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
  6807. }
  6808. SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
  6809. SelectionDAG &DAG) const {
  6810. // Implements a vector truncate that fits in a vector register as a shuffle.
  6811. // We want to legalize vector truncates down to where the source fits in
  6812. // a vector register (and target is therefore smaller than vector register
  6813. // size). At that point legalization will try to custom lower the sub-legal
  6814. // result and get here - where we can contain the truncate as a single target
  6815. // operation.
  6816. // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
  6817. // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
  6818. //
  6819. // We will implement it for big-endian ordering as this (where x denotes
  6820. // undefined):
  6821. // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
  6822. // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
  6823. //
  6824. // The same operation in little-endian ordering will be:
  6825. // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
  6826. // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
  6827. EVT TrgVT = Op.getValueType();
  6828. assert(TrgVT.isVector() && "Vector type expected.");
  6829. unsigned TrgNumElts = TrgVT.getVectorNumElements();
  6830. EVT EltVT = TrgVT.getVectorElementType();
  6831. if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
  6832. TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
  6833. !isPowerOf2_32(EltVT.getSizeInBits()))
  6834. return SDValue();
  6835. SDValue N1 = Op.getOperand(0);
  6836. EVT SrcVT = N1.getValueType();
  6837. unsigned SrcSize = SrcVT.getSizeInBits();
  6838. if (SrcSize > 256 ||
  6839. !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
  6840. !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
  6841. return SDValue();
  6842. if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
  6843. return SDValue();
  6844. unsigned WideNumElts = 128 / EltVT.getSizeInBits();
  6845. EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
  6846. SDLoc DL(Op);
  6847. SDValue Op1, Op2;
  6848. if (SrcSize == 256) {
  6849. EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
  6850. EVT SplitVT =
  6851. N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
  6852. unsigned SplitNumElts = SplitVT.getVectorNumElements();
  6853. Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
  6854. DAG.getConstant(0, DL, VecIdxTy));
  6855. Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
  6856. DAG.getConstant(SplitNumElts, DL, VecIdxTy));
  6857. }
  6858. else {
  6859. Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
  6860. Op2 = DAG.getUNDEF(WideVT);
  6861. }
  6862. // First list the elements we want to keep.
  6863. unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
  6864. SmallVector<int, 16> ShuffV;
  6865. if (Subtarget.isLittleEndian())
  6866. for (unsigned i = 0; i < TrgNumElts; ++i)
  6867. ShuffV.push_back(i * SizeMult);
  6868. else
  6869. for (unsigned i = 1; i <= TrgNumElts; ++i)
  6870. ShuffV.push_back(i * SizeMult - 1);
  6871. // Populate the remaining elements with undefs.
  6872. for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
  6873. // ShuffV.push_back(i + WideNumElts);
  6874. ShuffV.push_back(WideNumElts + 1);
  6875. Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
  6876. Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
  6877. return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
  6878. }
  6879. /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
  6880. /// possible.
  6881. SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
  6882. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
  6883. EVT ResVT = Op.getValueType();
  6884. EVT CmpVT = Op.getOperand(0).getValueType();
  6885. SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
  6886. SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
  6887. SDLoc dl(Op);
  6888. // Without power9-vector, we don't have native instruction for f128 comparison.
  6889. // Following transformation to libcall is needed for setcc:
  6890. // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
  6891. if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
  6892. SDValue Z = DAG.getSetCC(
  6893. dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
  6894. LHS, RHS, CC);
  6895. SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
  6896. return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
  6897. }
  6898. // Not FP, or using SPE? Not a fsel.
  6899. if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
  6900. Subtarget.hasSPE())
  6901. return Op;
  6902. SDNodeFlags Flags = Op.getNode()->getFlags();
  6903. // We have xsmaxcdp/xsmincdp which are OK to emit even in the
  6904. // presence of infinities.
  6905. if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
  6906. switch (CC) {
  6907. default:
  6908. break;
  6909. case ISD::SETOGT:
  6910. case ISD::SETGT:
  6911. return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
  6912. case ISD::SETOLT:
  6913. case ISD::SETLT:
  6914. return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
  6915. }
  6916. }
  6917. // We might be able to do better than this under some circumstances, but in
  6918. // general, fsel-based lowering of select is a finite-math-only optimization.
  6919. // For more information, see section F.3 of the 2.06 ISA specification.
  6920. // With ISA 3.0
  6921. if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
  6922. (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
  6923. return Op;
  6924. // If the RHS of the comparison is a 0.0, we don't need to do the
  6925. // subtraction at all.
  6926. SDValue Sel1;
  6927. if (isFloatingPointZero(RHS))
  6928. switch (CC) {
  6929. default: break; // SETUO etc aren't handled by fsel.
  6930. case ISD::SETNE:
  6931. std::swap(TV, FV);
  6932. LLVM_FALLTHROUGH;
  6933. case ISD::SETEQ:
  6934. if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
  6935. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
  6936. Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
  6937. if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
  6938. Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
  6939. return DAG.getNode(PPCISD::FSEL, dl, ResVT,
  6940. DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
  6941. case ISD::SETULT:
  6942. case ISD::SETLT:
  6943. std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
  6944. LLVM_FALLTHROUGH;
  6945. case ISD::SETOGE:
  6946. case ISD::SETGE:
  6947. if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
  6948. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
  6949. return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
  6950. case ISD::SETUGT:
  6951. case ISD::SETGT:
  6952. std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
  6953. LLVM_FALLTHROUGH;
  6954. case ISD::SETOLE:
  6955. case ISD::SETLE:
  6956. if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
  6957. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
  6958. return DAG.getNode(PPCISD::FSEL, dl, ResVT,
  6959. DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
  6960. }
  6961. SDValue Cmp;
  6962. switch (CC) {
  6963. default: break; // SETUO etc aren't handled by fsel.
  6964. case ISD::SETNE:
  6965. std::swap(TV, FV);
  6966. LLVM_FALLTHROUGH;
  6967. case ISD::SETEQ:
  6968. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
  6969. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  6970. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  6971. Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
  6972. if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
  6973. Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
  6974. return DAG.getNode(PPCISD::FSEL, dl, ResVT,
  6975. DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
  6976. case ISD::SETULT:
  6977. case ISD::SETLT:
  6978. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
  6979. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  6980. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  6981. return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
  6982. case ISD::SETOGE:
  6983. case ISD::SETGE:
  6984. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
  6985. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  6986. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  6987. return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
  6988. case ISD::SETUGT:
  6989. case ISD::SETGT:
  6990. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
  6991. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  6992. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  6993. return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
  6994. case ISD::SETOLE:
  6995. case ISD::SETLE:
  6996. Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
  6997. if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
  6998. Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
  6999. return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
  7000. }
  7001. return Op;
  7002. }
  7003. static unsigned getPPCStrictOpcode(unsigned Opc) {
  7004. switch (Opc) {
  7005. default:
  7006. llvm_unreachable("No strict version of this opcode!");
  7007. case PPCISD::FCTIDZ:
  7008. return PPCISD::STRICT_FCTIDZ;
  7009. case PPCISD::FCTIWZ:
  7010. return PPCISD::STRICT_FCTIWZ;
  7011. case PPCISD::FCTIDUZ:
  7012. return PPCISD::STRICT_FCTIDUZ;
  7013. case PPCISD::FCTIWUZ:
  7014. return PPCISD::STRICT_FCTIWUZ;
  7015. case PPCISD::FCFID:
  7016. return PPCISD::STRICT_FCFID;
  7017. case PPCISD::FCFIDU:
  7018. return PPCISD::STRICT_FCFIDU;
  7019. case PPCISD::FCFIDS:
  7020. return PPCISD::STRICT_FCFIDS;
  7021. case PPCISD::FCFIDUS:
  7022. return PPCISD::STRICT_FCFIDUS;
  7023. }
  7024. }
  7025. static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
  7026. const PPCSubtarget &Subtarget) {
  7027. SDLoc dl(Op);
  7028. bool IsStrict = Op->isStrictFPOpcode();
  7029. bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
  7030. Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
  7031. // TODO: Any other flags to propagate?
  7032. SDNodeFlags Flags;
  7033. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7034. // For strict nodes, source is the second operand.
  7035. SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
  7036. SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
  7037. assert(Src.getValueType().isFloatingPoint());
  7038. if (Src.getValueType() == MVT::f32) {
  7039. if (IsStrict) {
  7040. Src =
  7041. DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
  7042. DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
  7043. Chain = Src.getValue(1);
  7044. } else
  7045. Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
  7046. }
  7047. SDValue Conv;
  7048. unsigned Opc = ISD::DELETED_NODE;
  7049. switch (Op.getSimpleValueType().SimpleTy) {
  7050. default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
  7051. case MVT::i32:
  7052. Opc = IsSigned ? PPCISD::FCTIWZ
  7053. : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
  7054. break;
  7055. case MVT::i64:
  7056. assert((IsSigned || Subtarget.hasFPCVT()) &&
  7057. "i64 FP_TO_UINT is supported only with FPCVT");
  7058. Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
  7059. }
  7060. if (IsStrict) {
  7061. Opc = getPPCStrictOpcode(Opc);
  7062. Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
  7063. {Chain, Src}, Flags);
  7064. } else {
  7065. Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
  7066. }
  7067. return Conv;
  7068. }
  7069. void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
  7070. SelectionDAG &DAG,
  7071. const SDLoc &dl) const {
  7072. SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
  7073. bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
  7074. Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
  7075. bool IsStrict = Op->isStrictFPOpcode();
  7076. // Convert the FP value to an int value through memory.
  7077. bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
  7078. (IsSigned || Subtarget.hasFPCVT());
  7079. SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
  7080. int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
  7081. MachinePointerInfo MPI =
  7082. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
  7083. // Emit a store to the stack slot.
  7084. SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
  7085. Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
  7086. if (i32Stack) {
  7087. MachineFunction &MF = DAG.getMachineFunction();
  7088. Alignment = Align(4);
  7089. MachineMemOperand *MMO =
  7090. MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
  7091. SDValue Ops[] = { Chain, Tmp, FIPtr };
  7092. Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
  7093. DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
  7094. } else
  7095. Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
  7096. // Result is a load from the stack slot. If loading 4 bytes, make sure to
  7097. // add in a bias on big endian.
  7098. if (Op.getValueType() == MVT::i32 && !i32Stack) {
  7099. FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
  7100. DAG.getConstant(4, dl, FIPtr.getValueType()));
  7101. MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
  7102. }
  7103. RLI.Chain = Chain;
  7104. RLI.Ptr = FIPtr;
  7105. RLI.MPI = MPI;
  7106. RLI.Alignment = Alignment;
  7107. }
  7108. /// Custom lowers floating point to integer conversions to use
  7109. /// the direct move instructions available in ISA 2.07 to avoid the
  7110. /// need for load/store combinations.
  7111. SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
  7112. SelectionDAG &DAG,
  7113. const SDLoc &dl) const {
  7114. SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
  7115. SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
  7116. if (Op->isStrictFPOpcode())
  7117. return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
  7118. else
  7119. return Mov;
  7120. }
  7121. SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
  7122. const SDLoc &dl) const {
  7123. bool IsStrict = Op->isStrictFPOpcode();
  7124. bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
  7125. Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
  7126. SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
  7127. EVT SrcVT = Src.getValueType();
  7128. EVT DstVT = Op.getValueType();
  7129. // FP to INT conversions are legal for f128.
  7130. if (SrcVT == MVT::f128)
  7131. return Subtarget.hasP9Vector() ? Op : SDValue();
  7132. // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
  7133. // PPC (the libcall is not available).
  7134. if (SrcVT == MVT::ppcf128) {
  7135. if (DstVT == MVT::i32) {
  7136. // TODO: Conservatively pass only nofpexcept flag here. Need to check and
  7137. // set other fast-math flags to FP operations in both strict and
  7138. // non-strict cases. (FP_TO_SINT, FSUB)
  7139. SDNodeFlags Flags;
  7140. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7141. if (IsSigned) {
  7142. SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
  7143. DAG.getIntPtrConstant(0, dl));
  7144. SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
  7145. DAG.getIntPtrConstant(1, dl));
  7146. // Add the two halves of the long double in round-to-zero mode, and use
  7147. // a smaller FP_TO_SINT.
  7148. if (IsStrict) {
  7149. SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
  7150. DAG.getVTList(MVT::f64, MVT::Other),
  7151. {Op.getOperand(0), Lo, Hi}, Flags);
  7152. return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
  7153. DAG.getVTList(MVT::i32, MVT::Other),
  7154. {Res.getValue(1), Res}, Flags);
  7155. } else {
  7156. SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
  7157. return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
  7158. }
  7159. } else {
  7160. const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
  7161. APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
  7162. SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
  7163. SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
  7164. if (IsStrict) {
  7165. // Sel = Src < 0x80000000
  7166. // FltOfs = select Sel, 0.0, 0x80000000
  7167. // IntOfs = select Sel, 0, 0x80000000
  7168. // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
  7169. SDValue Chain = Op.getOperand(0);
  7170. EVT SetCCVT =
  7171. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
  7172. EVT DstSetCCVT =
  7173. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
  7174. SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
  7175. Chain, true);
  7176. Chain = Sel.getValue(1);
  7177. SDValue FltOfs = DAG.getSelect(
  7178. dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
  7179. Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
  7180. SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
  7181. DAG.getVTList(SrcVT, MVT::Other),
  7182. {Chain, Src, FltOfs}, Flags);
  7183. Chain = Val.getValue(1);
  7184. SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
  7185. DAG.getVTList(DstVT, MVT::Other),
  7186. {Chain, Val}, Flags);
  7187. Chain = SInt.getValue(1);
  7188. SDValue IntOfs = DAG.getSelect(
  7189. dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
  7190. SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
  7191. return DAG.getMergeValues({Result, Chain}, dl);
  7192. } else {
  7193. // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
  7194. // FIXME: generated code sucks.
  7195. SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
  7196. True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
  7197. True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
  7198. SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
  7199. return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
  7200. }
  7201. }
  7202. }
  7203. return SDValue();
  7204. }
  7205. if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
  7206. return LowerFP_TO_INTDirectMove(Op, DAG, dl);
  7207. ReuseLoadInfo RLI;
  7208. LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
  7209. return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
  7210. RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
  7211. }
  7212. // We're trying to insert a regular store, S, and then a load, L. If the
  7213. // incoming value, O, is a load, we might just be able to have our load use the
  7214. // address used by O. However, we don't know if anything else will store to
  7215. // that address before we can load from it. To prevent this situation, we need
  7216. // to insert our load, L, into the chain as a peer of O. To do this, we give L
  7217. // the same chain operand as O, we create a token factor from the chain results
  7218. // of O and L, and we replace all uses of O's chain result with that token
  7219. // factor (see spliceIntoChain below for this last part).
  7220. bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
  7221. ReuseLoadInfo &RLI,
  7222. SelectionDAG &DAG,
  7223. ISD::LoadExtType ET) const {
  7224. // Conservatively skip reusing for constrained FP nodes.
  7225. if (Op->isStrictFPOpcode())
  7226. return false;
  7227. SDLoc dl(Op);
  7228. bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
  7229. (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
  7230. if (ET == ISD::NON_EXTLOAD &&
  7231. (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
  7232. isOperationLegalOrCustom(Op.getOpcode(),
  7233. Op.getOperand(0).getValueType())) {
  7234. LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
  7235. return true;
  7236. }
  7237. LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
  7238. if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
  7239. LD->isNonTemporal())
  7240. return false;
  7241. if (LD->getMemoryVT() != MemVT)
  7242. return false;
  7243. // If the result of the load is an illegal type, then we can't build a
  7244. // valid chain for reuse since the legalised loads and token factor node that
  7245. // ties the legalised loads together uses a different output chain then the
  7246. // illegal load.
  7247. if (!isTypeLegal(LD->getValueType(0)))
  7248. return false;
  7249. RLI.Ptr = LD->getBasePtr();
  7250. if (LD->isIndexed() && !LD->getOffset().isUndef()) {
  7251. assert(LD->getAddressingMode() == ISD::PRE_INC &&
  7252. "Non-pre-inc AM on PPC?");
  7253. RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
  7254. LD->getOffset());
  7255. }
  7256. RLI.Chain = LD->getChain();
  7257. RLI.MPI = LD->getPointerInfo();
  7258. RLI.IsDereferenceable = LD->isDereferenceable();
  7259. RLI.IsInvariant = LD->isInvariant();
  7260. RLI.Alignment = LD->getAlign();
  7261. RLI.AAInfo = LD->getAAInfo();
  7262. RLI.Ranges = LD->getRanges();
  7263. RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
  7264. return true;
  7265. }
  7266. // Given the head of the old chain, ResChain, insert a token factor containing
  7267. // it and NewResChain, and make users of ResChain now be users of that token
  7268. // factor.
  7269. // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
  7270. void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
  7271. SDValue NewResChain,
  7272. SelectionDAG &DAG) const {
  7273. if (!ResChain)
  7274. return;
  7275. SDLoc dl(NewResChain);
  7276. SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  7277. NewResChain, DAG.getUNDEF(MVT::Other));
  7278. assert(TF.getNode() != NewResChain.getNode() &&
  7279. "A new TF really is required here");
  7280. DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
  7281. DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
  7282. }
  7283. /// Analyze profitability of direct move
  7284. /// prefer float load to int load plus direct move
  7285. /// when there is no integer use of int load
  7286. bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
  7287. SDNode *Origin = Op.getOperand(0).getNode();
  7288. if (Origin->getOpcode() != ISD::LOAD)
  7289. return true;
  7290. // If there is no LXSIBZX/LXSIHZX, like Power8,
  7291. // prefer direct move if the memory size is 1 or 2 bytes.
  7292. MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
  7293. if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
  7294. return true;
  7295. for (SDNode::use_iterator UI = Origin->use_begin(),
  7296. UE = Origin->use_end();
  7297. UI != UE; ++UI) {
  7298. // Only look at the users of the loaded value.
  7299. if (UI.getUse().get().getResNo() != 0)
  7300. continue;
  7301. if (UI->getOpcode() != ISD::SINT_TO_FP &&
  7302. UI->getOpcode() != ISD::UINT_TO_FP &&
  7303. UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
  7304. UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
  7305. return true;
  7306. }
  7307. return false;
  7308. }
  7309. static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
  7310. const PPCSubtarget &Subtarget,
  7311. SDValue Chain = SDValue()) {
  7312. bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
  7313. Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
  7314. SDLoc dl(Op);
  7315. // TODO: Any other flags to propagate?
  7316. SDNodeFlags Flags;
  7317. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7318. // If we have FCFIDS, then use it when converting to single-precision.
  7319. // Otherwise, convert to double-precision and then round.
  7320. bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
  7321. unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
  7322. : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
  7323. EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
  7324. if (Op->isStrictFPOpcode()) {
  7325. if (!Chain)
  7326. Chain = Op.getOperand(0);
  7327. return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
  7328. DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
  7329. } else
  7330. return DAG.getNode(ConvOpc, dl, ConvTy, Src);
  7331. }
  7332. /// Custom lowers integer to floating point conversions to use
  7333. /// the direct move instructions available in ISA 2.07 to avoid the
  7334. /// need for load/store combinations.
  7335. SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
  7336. SelectionDAG &DAG,
  7337. const SDLoc &dl) const {
  7338. assert((Op.getValueType() == MVT::f32 ||
  7339. Op.getValueType() == MVT::f64) &&
  7340. "Invalid floating point type as target of conversion");
  7341. assert(Subtarget.hasFPCVT() &&
  7342. "Int to FP conversions with direct moves require FPCVT");
  7343. SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
  7344. bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
  7345. bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
  7346. Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
  7347. unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
  7348. SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
  7349. return convertIntToFP(Op, Mov, DAG, Subtarget);
  7350. }
  7351. static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
  7352. EVT VecVT = Vec.getValueType();
  7353. assert(VecVT.isVector() && "Expected a vector type.");
  7354. assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
  7355. EVT EltVT = VecVT.getVectorElementType();
  7356. unsigned WideNumElts = 128 / EltVT.getSizeInBits();
  7357. EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
  7358. unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
  7359. SmallVector<SDValue, 16> Ops(NumConcat);
  7360. Ops[0] = Vec;
  7361. SDValue UndefVec = DAG.getUNDEF(VecVT);
  7362. for (unsigned i = 1; i < NumConcat; ++i)
  7363. Ops[i] = UndefVec;
  7364. return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
  7365. }
  7366. SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
  7367. const SDLoc &dl) const {
  7368. bool IsStrict = Op->isStrictFPOpcode();
  7369. unsigned Opc = Op.getOpcode();
  7370. SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
  7371. assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
  7372. Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
  7373. "Unexpected conversion type");
  7374. assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
  7375. "Supports conversions to v2f64/v4f32 only.");
  7376. // TODO: Any other flags to propagate?
  7377. SDNodeFlags Flags;
  7378. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7379. bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
  7380. bool FourEltRes = Op.getValueType() == MVT::v4f32;
  7381. SDValue Wide = widenVec(DAG, Src, dl);
  7382. EVT WideVT = Wide.getValueType();
  7383. unsigned WideNumElts = WideVT.getVectorNumElements();
  7384. MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
  7385. SmallVector<int, 16> ShuffV;
  7386. for (unsigned i = 0; i < WideNumElts; ++i)
  7387. ShuffV.push_back(i + WideNumElts);
  7388. int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
  7389. int SaveElts = FourEltRes ? 4 : 2;
  7390. if (Subtarget.isLittleEndian())
  7391. for (int i = 0; i < SaveElts; i++)
  7392. ShuffV[i * Stride] = i;
  7393. else
  7394. for (int i = 1; i <= SaveElts; i++)
  7395. ShuffV[i * Stride - 1] = i - 1;
  7396. SDValue ShuffleSrc2 =
  7397. SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
  7398. SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
  7399. SDValue Extend;
  7400. if (SignedConv) {
  7401. Arrange = DAG.getBitcast(IntermediateVT, Arrange);
  7402. EVT ExtVT = Src.getValueType();
  7403. if (Subtarget.hasP9Altivec())
  7404. ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
  7405. IntermediateVT.getVectorNumElements());
  7406. Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
  7407. DAG.getValueType(ExtVT));
  7408. } else
  7409. Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
  7410. if (IsStrict)
  7411. return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
  7412. {Op.getOperand(0), Extend}, Flags);
  7413. return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
  7414. }
  7415. SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
  7416. SelectionDAG &DAG) const {
  7417. SDLoc dl(Op);
  7418. bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
  7419. Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
  7420. bool IsStrict = Op->isStrictFPOpcode();
  7421. SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
  7422. SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
  7423. // TODO: Any other flags to propagate?
  7424. SDNodeFlags Flags;
  7425. Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
  7426. EVT InVT = Src.getValueType();
  7427. EVT OutVT = Op.getValueType();
  7428. if (OutVT.isVector() && OutVT.isFloatingPoint() &&
  7429. isOperationCustom(Op.getOpcode(), InVT))
  7430. return LowerINT_TO_FPVector(Op, DAG, dl);
  7431. // Conversions to f128 are legal.
  7432. if (Op.getValueType() == MVT::f128)
  7433. return Subtarget.hasP9Vector() ? Op : SDValue();
  7434. // Don't handle ppc_fp128 here; let it be lowered to a libcall.
  7435. if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
  7436. return SDValue();
  7437. if (Src.getValueType() == MVT::i1) {
  7438. SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
  7439. DAG.getConstantFP(1.0, dl, Op.getValueType()),
  7440. DAG.getConstantFP(0.0, dl, Op.getValueType()));
  7441. if (IsStrict)
  7442. return DAG.getMergeValues({Sel, Chain}, dl);
  7443. else
  7444. return Sel;
  7445. }
  7446. // If we have direct moves, we can do all the conversion, skip the store/load
  7447. // however, without FPCVT we can't do most conversions.
  7448. if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
  7449. Subtarget.isPPC64() && Subtarget.hasFPCVT())
  7450. return LowerINT_TO_FPDirectMove(Op, DAG, dl);
  7451. assert((IsSigned || Subtarget.hasFPCVT()) &&
  7452. "UINT_TO_FP is supported only with FPCVT");
  7453. if (Src.getValueType() == MVT::i64) {
  7454. SDValue SINT = Src;
  7455. // When converting to single-precision, we actually need to convert
  7456. // to double-precision first and then round to single-precision.
  7457. // To avoid double-rounding effects during that operation, we have
  7458. // to prepare the input operand. Bits that might be truncated when
  7459. // converting to double-precision are replaced by a bit that won't
  7460. // be lost at this stage, but is below the single-precision rounding
  7461. // position.
  7462. //
  7463. // However, if -enable-unsafe-fp-math is in effect, accept double
  7464. // rounding to avoid the extra overhead.
  7465. if (Op.getValueType() == MVT::f32 &&
  7466. !Subtarget.hasFPCVT() &&
  7467. !DAG.getTarget().Options.UnsafeFPMath) {
  7468. // Twiddle input to make sure the low 11 bits are zero. (If this
  7469. // is the case, we are guaranteed the value will fit into the 53 bit
  7470. // mantissa of an IEEE double-precision value without rounding.)
  7471. // If any of those low 11 bits were not zero originally, make sure
  7472. // bit 12 (value 2048) is set instead, so that the final rounding
  7473. // to single-precision gets the correct result.
  7474. SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
  7475. SINT, DAG.getConstant(2047, dl, MVT::i64));
  7476. Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
  7477. Round, DAG.getConstant(2047, dl, MVT::i64));
  7478. Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
  7479. Round = DAG.getNode(ISD::AND, dl, MVT::i64,
  7480. Round, DAG.getConstant(-2048, dl, MVT::i64));
  7481. // However, we cannot use that value unconditionally: if the magnitude
  7482. // of the input value is small, the bit-twiddling we did above might
  7483. // end up visibly changing the output. Fortunately, in that case, we
  7484. // don't need to twiddle bits since the original input will convert
  7485. // exactly to double-precision floating-point already. Therefore,
  7486. // construct a conditional to use the original value if the top 11
  7487. // bits are all sign-bit copies, and use the rounded value computed
  7488. // above otherwise.
  7489. SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
  7490. SINT, DAG.getConstant(53, dl, MVT::i32));
  7491. Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
  7492. Cond, DAG.getConstant(1, dl, MVT::i64));
  7493. Cond = DAG.getSetCC(
  7494. dl,
  7495. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
  7496. Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
  7497. SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
  7498. }
  7499. ReuseLoadInfo RLI;
  7500. SDValue Bits;
  7501. MachineFunction &MF = DAG.getMachineFunction();
  7502. if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
  7503. Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
  7504. RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
  7505. spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
  7506. } else if (Subtarget.hasLFIWAX() &&
  7507. canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
  7508. MachineMemOperand *MMO =
  7509. MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
  7510. RLI.Alignment, RLI.AAInfo, RLI.Ranges);
  7511. SDValue Ops[] = { RLI.Chain, RLI.Ptr };
  7512. Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
  7513. DAG.getVTList(MVT::f64, MVT::Other),
  7514. Ops, MVT::i32, MMO);
  7515. spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
  7516. } else if (Subtarget.hasFPCVT() &&
  7517. canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
  7518. MachineMemOperand *MMO =
  7519. MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
  7520. RLI.Alignment, RLI.AAInfo, RLI.Ranges);
  7521. SDValue Ops[] = { RLI.Chain, RLI.Ptr };
  7522. Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
  7523. DAG.getVTList(MVT::f64, MVT::Other),
  7524. Ops, MVT::i32, MMO);
  7525. spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
  7526. } else if (((Subtarget.hasLFIWAX() &&
  7527. SINT.getOpcode() == ISD::SIGN_EXTEND) ||
  7528. (Subtarget.hasFPCVT() &&
  7529. SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
  7530. SINT.getOperand(0).getValueType() == MVT::i32) {
  7531. MachineFrameInfo &MFI = MF.getFrameInfo();
  7532. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  7533. int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
  7534. SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
  7535. SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
  7536. MachinePointerInfo::getFixedStack(
  7537. DAG.getMachineFunction(), FrameIdx));
  7538. Chain = Store;
  7539. assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
  7540. "Expected an i32 store");
  7541. RLI.Ptr = FIdx;
  7542. RLI.Chain = Chain;
  7543. RLI.MPI =
  7544. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
  7545. RLI.Alignment = Align(4);
  7546. MachineMemOperand *MMO =
  7547. MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
  7548. RLI.Alignment, RLI.AAInfo, RLI.Ranges);
  7549. SDValue Ops[] = { RLI.Chain, RLI.Ptr };
  7550. Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
  7551. PPCISD::LFIWZX : PPCISD::LFIWAX,
  7552. dl, DAG.getVTList(MVT::f64, MVT::Other),
  7553. Ops, MVT::i32, MMO);
  7554. Chain = Bits.getValue(1);
  7555. } else
  7556. Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
  7557. SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
  7558. if (IsStrict)
  7559. Chain = FP.getValue(1);
  7560. if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
  7561. if (IsStrict)
  7562. FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
  7563. DAG.getVTList(MVT::f32, MVT::Other),
  7564. {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
  7565. else
  7566. FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
  7567. DAG.getIntPtrConstant(0, dl));
  7568. }
  7569. return FP;
  7570. }
  7571. assert(Src.getValueType() == MVT::i32 &&
  7572. "Unhandled INT_TO_FP type in custom expander!");
  7573. // Since we only generate this in 64-bit mode, we can take advantage of
  7574. // 64-bit registers. In particular, sign extend the input value into the
  7575. // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
  7576. // then lfd it and fcfid it.
  7577. MachineFunction &MF = DAG.getMachineFunction();
  7578. MachineFrameInfo &MFI = MF.getFrameInfo();
  7579. EVT PtrVT = getPointerTy(MF.getDataLayout());
  7580. SDValue Ld;
  7581. if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
  7582. ReuseLoadInfo RLI;
  7583. bool ReusingLoad;
  7584. if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
  7585. int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
  7586. SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
  7587. SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
  7588. MachinePointerInfo::getFixedStack(
  7589. DAG.getMachineFunction(), FrameIdx));
  7590. Chain = Store;
  7591. assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
  7592. "Expected an i32 store");
  7593. RLI.Ptr = FIdx;
  7594. RLI.Chain = Chain;
  7595. RLI.MPI =
  7596. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
  7597. RLI.Alignment = Align(4);
  7598. }
  7599. MachineMemOperand *MMO =
  7600. MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
  7601. RLI.Alignment, RLI.AAInfo, RLI.Ranges);
  7602. SDValue Ops[] = { RLI.Chain, RLI.Ptr };
  7603. Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
  7604. DAG.getVTList(MVT::f64, MVT::Other), Ops,
  7605. MVT::i32, MMO);
  7606. Chain = Ld.getValue(1);
  7607. if (ReusingLoad)
  7608. spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
  7609. } else {
  7610. assert(Subtarget.isPPC64() &&
  7611. "i32->FP without LFIWAX supported only on PPC64");
  7612. int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
  7613. SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
  7614. SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
  7615. // STD the extended value into the stack slot.
  7616. SDValue Store = DAG.getStore(
  7617. Chain, dl, Ext64, FIdx,
  7618. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
  7619. Chain = Store;
  7620. // Load the value as a double.
  7621. Ld = DAG.getLoad(
  7622. MVT::f64, dl, Chain, FIdx,
  7623. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
  7624. Chain = Ld.getValue(1);
  7625. }
  7626. // FCFID it and return it.
  7627. SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
  7628. if (IsStrict)
  7629. Chain = FP.getValue(1);
  7630. if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
  7631. if (IsStrict)
  7632. FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
  7633. DAG.getVTList(MVT::f32, MVT::Other),
  7634. {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
  7635. else
  7636. FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
  7637. DAG.getIntPtrConstant(0, dl));
  7638. }
  7639. return FP;
  7640. }
  7641. SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
  7642. SelectionDAG &DAG) const {
  7643. SDLoc dl(Op);
  7644. /*
  7645. The rounding mode is in bits 30:31 of FPSR, and has the following
  7646. settings:
  7647. 00 Round to nearest
  7648. 01 Round to 0
  7649. 10 Round to +inf
  7650. 11 Round to -inf
  7651. FLT_ROUNDS, on the other hand, expects the following:
  7652. -1 Undefined
  7653. 0 Round to 0
  7654. 1 Round to nearest
  7655. 2 Round to +inf
  7656. 3 Round to -inf
  7657. To perform the conversion, we do:
  7658. ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
  7659. */
  7660. MachineFunction &MF = DAG.getMachineFunction();
  7661. EVT VT = Op.getValueType();
  7662. EVT PtrVT = getPointerTy(MF.getDataLayout());
  7663. // Save FP Control Word to register
  7664. SDValue Chain = Op.getOperand(0);
  7665. SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
  7666. Chain = MFFS.getValue(1);
  7667. SDValue CWD;
  7668. if (isTypeLegal(MVT::i64)) {
  7669. CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
  7670. DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
  7671. } else {
  7672. // Save FP register to stack slot
  7673. int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
  7674. SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
  7675. Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
  7676. // Load FP Control Word from low 32 bits of stack slot.
  7677. assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
  7678. "Stack slot adjustment is valid only on big endian subtargets!");
  7679. SDValue Four = DAG.getConstant(4, dl, PtrVT);
  7680. SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
  7681. CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
  7682. Chain = CWD.getValue(1);
  7683. }
  7684. // Transform as necessary
  7685. SDValue CWD1 =
  7686. DAG.getNode(ISD::AND, dl, MVT::i32,
  7687. CWD, DAG.getConstant(3, dl, MVT::i32));
  7688. SDValue CWD2 =
  7689. DAG.getNode(ISD::SRL, dl, MVT::i32,
  7690. DAG.getNode(ISD::AND, dl, MVT::i32,
  7691. DAG.getNode(ISD::XOR, dl, MVT::i32,
  7692. CWD, DAG.getConstant(3, dl, MVT::i32)),
  7693. DAG.getConstant(3, dl, MVT::i32)),
  7694. DAG.getConstant(1, dl, MVT::i32));
  7695. SDValue RetVal =
  7696. DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
  7697. RetVal =
  7698. DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
  7699. dl, VT, RetVal);
  7700. return DAG.getMergeValues({RetVal, Chain}, dl);
  7701. }
  7702. SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
  7703. EVT VT = Op.getValueType();
  7704. unsigned BitWidth = VT.getSizeInBits();
  7705. SDLoc dl(Op);
  7706. assert(Op.getNumOperands() == 3 &&
  7707. VT == Op.getOperand(1).getValueType() &&
  7708. "Unexpected SHL!");
  7709. // Expand into a bunch of logical ops. Note that these ops
  7710. // depend on the PPC behavior for oversized shift amounts.
  7711. SDValue Lo = Op.getOperand(0);
  7712. SDValue Hi = Op.getOperand(1);
  7713. SDValue Amt = Op.getOperand(2);
  7714. EVT AmtVT = Amt.getValueType();
  7715. SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
  7716. DAG.getConstant(BitWidth, dl, AmtVT), Amt);
  7717. SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
  7718. SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
  7719. SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
  7720. SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
  7721. DAG.getConstant(-BitWidth, dl, AmtVT));
  7722. SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
  7723. SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
  7724. SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
  7725. SDValue OutOps[] = { OutLo, OutHi };
  7726. return DAG.getMergeValues(OutOps, dl);
  7727. }
  7728. SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
  7729. EVT VT = Op.getValueType();
  7730. SDLoc dl(Op);
  7731. unsigned BitWidth = VT.getSizeInBits();
  7732. assert(Op.getNumOperands() == 3 &&
  7733. VT == Op.getOperand(1).getValueType() &&
  7734. "Unexpected SRL!");
  7735. // Expand into a bunch of logical ops. Note that these ops
  7736. // depend on the PPC behavior for oversized shift amounts.
  7737. SDValue Lo = Op.getOperand(0);
  7738. SDValue Hi = Op.getOperand(1);
  7739. SDValue Amt = Op.getOperand(2);
  7740. EVT AmtVT = Amt.getValueType();
  7741. SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
  7742. DAG.getConstant(BitWidth, dl, AmtVT), Amt);
  7743. SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
  7744. SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
  7745. SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
  7746. SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
  7747. DAG.getConstant(-BitWidth, dl, AmtVT));
  7748. SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
  7749. SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
  7750. SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
  7751. SDValue OutOps[] = { OutLo, OutHi };
  7752. return DAG.getMergeValues(OutOps, dl);
  7753. }
  7754. SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
  7755. SDLoc dl(Op);
  7756. EVT VT = Op.getValueType();
  7757. unsigned BitWidth = VT.getSizeInBits();
  7758. assert(Op.getNumOperands() == 3 &&
  7759. VT == Op.getOperand(1).getValueType() &&
  7760. "Unexpected SRA!");
  7761. // Expand into a bunch of logical ops, followed by a select_cc.
  7762. SDValue Lo = Op.getOperand(0);
  7763. SDValue Hi = Op.getOperand(1);
  7764. SDValue Amt = Op.getOperand(2);
  7765. EVT AmtVT = Amt.getValueType();
  7766. SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
  7767. DAG.getConstant(BitWidth, dl, AmtVT), Amt);
  7768. SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
  7769. SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
  7770. SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
  7771. SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
  7772. DAG.getConstant(-BitWidth, dl, AmtVT));
  7773. SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
  7774. SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
  7775. SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
  7776. Tmp4, Tmp6, ISD::SETLE);
  7777. SDValue OutOps[] = { OutLo, OutHi };
  7778. return DAG.getMergeValues(OutOps, dl);
  7779. }
  7780. SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
  7781. SelectionDAG &DAG) const {
  7782. SDLoc dl(Op);
  7783. EVT VT = Op.getValueType();
  7784. unsigned BitWidth = VT.getSizeInBits();
  7785. bool IsFSHL = Op.getOpcode() == ISD::FSHL;
  7786. SDValue X = Op.getOperand(0);
  7787. SDValue Y = Op.getOperand(1);
  7788. SDValue Z = Op.getOperand(2);
  7789. EVT AmtVT = Z.getValueType();
  7790. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  7791. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  7792. // This is simpler than TargetLowering::expandFunnelShift because we can rely
  7793. // on PowerPC shift by BW being well defined.
  7794. Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
  7795. DAG.getConstant(BitWidth - 1, dl, AmtVT));
  7796. SDValue SubZ =
  7797. DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
  7798. X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
  7799. Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
  7800. return DAG.getNode(ISD::OR, dl, VT, X, Y);
  7801. }
  7802. //===----------------------------------------------------------------------===//
  7803. // Vector related lowering.
  7804. //
  7805. /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
  7806. /// element size of SplatSize. Cast the result to VT.
  7807. static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
  7808. SelectionDAG &DAG, const SDLoc &dl) {
  7809. static const MVT VTys[] = { // canonical VT to use for each size.
  7810. MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
  7811. };
  7812. EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
  7813. // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
  7814. if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
  7815. SplatSize = 1;
  7816. Val = 0xFF;
  7817. }
  7818. EVT CanonicalVT = VTys[SplatSize-1];
  7819. // Build a canonical splat for this value.
  7820. return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
  7821. }
  7822. /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
  7823. /// specified intrinsic ID.
  7824. static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
  7825. const SDLoc &dl, EVT DestVT = MVT::Other) {
  7826. if (DestVT == MVT::Other) DestVT = Op.getValueType();
  7827. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
  7828. DAG.getConstant(IID, dl, MVT::i32), Op);
  7829. }
  7830. /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
  7831. /// specified intrinsic ID.
  7832. static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
  7833. SelectionDAG &DAG, const SDLoc &dl,
  7834. EVT DestVT = MVT::Other) {
  7835. if (DestVT == MVT::Other) DestVT = LHS.getValueType();
  7836. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
  7837. DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
  7838. }
  7839. /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
  7840. /// specified intrinsic ID.
  7841. static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
  7842. SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
  7843. EVT DestVT = MVT::Other) {
  7844. if (DestVT == MVT::Other) DestVT = Op0.getValueType();
  7845. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
  7846. DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
  7847. }
  7848. /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
  7849. /// amount. The result has the specified value type.
  7850. static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
  7851. SelectionDAG &DAG, const SDLoc &dl) {
  7852. // Force LHS/RHS to be the right type.
  7853. LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
  7854. RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
  7855. int Ops[16];
  7856. for (unsigned i = 0; i != 16; ++i)
  7857. Ops[i] = i + Amt;
  7858. SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
  7859. return DAG.getNode(ISD::BITCAST, dl, VT, T);
  7860. }
  7861. /// Do we have an efficient pattern in a .td file for this node?
  7862. ///
  7863. /// \param V - pointer to the BuildVectorSDNode being matched
  7864. /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
  7865. ///
  7866. /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
  7867. /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
  7868. /// the opposite is true (expansion is beneficial) are:
  7869. /// - The node builds a vector out of integers that are not 32 or 64-bits
  7870. /// - The node builds a vector out of constants
  7871. /// - The node is a "load-and-splat"
  7872. /// In all other cases, we will choose to keep the BUILD_VECTOR.
  7873. static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
  7874. bool HasDirectMove,
  7875. bool HasP8Vector) {
  7876. EVT VecVT = V->getValueType(0);
  7877. bool RightType = VecVT == MVT::v2f64 ||
  7878. (HasP8Vector && VecVT == MVT::v4f32) ||
  7879. (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
  7880. if (!RightType)
  7881. return false;
  7882. bool IsSplat = true;
  7883. bool IsLoad = false;
  7884. SDValue Op0 = V->getOperand(0);
  7885. // This function is called in a block that confirms the node is not a constant
  7886. // splat. So a constant BUILD_VECTOR here means the vector is built out of
  7887. // different constants.
  7888. if (V->isConstant())
  7889. return false;
  7890. for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
  7891. if (V->getOperand(i).isUndef())
  7892. return false;
  7893. // We want to expand nodes that represent load-and-splat even if the
  7894. // loaded value is a floating point truncation or conversion to int.
  7895. if (V->getOperand(i).getOpcode() == ISD::LOAD ||
  7896. (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
  7897. V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
  7898. (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
  7899. V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
  7900. (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
  7901. V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
  7902. IsLoad = true;
  7903. // If the operands are different or the input is not a load and has more
  7904. // uses than just this BV node, then it isn't a splat.
  7905. if (V->getOperand(i) != Op0 ||
  7906. (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
  7907. IsSplat = false;
  7908. }
  7909. return !(IsSplat && IsLoad);
  7910. }
  7911. // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
  7912. SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
  7913. SDLoc dl(Op);
  7914. SDValue Op0 = Op->getOperand(0);
  7915. if ((Op.getValueType() != MVT::f128) ||
  7916. (Op0.getOpcode() != ISD::BUILD_PAIR) ||
  7917. (Op0.getOperand(0).getValueType() != MVT::i64) ||
  7918. (Op0.getOperand(1).getValueType() != MVT::i64))
  7919. return SDValue();
  7920. return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
  7921. Op0.getOperand(1));
  7922. }
  7923. static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
  7924. const SDValue *InputLoad = &Op;
  7925. if (InputLoad->getOpcode() == ISD::BITCAST)
  7926. InputLoad = &InputLoad->getOperand(0);
  7927. if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
  7928. InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
  7929. IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
  7930. InputLoad = &InputLoad->getOperand(0);
  7931. }
  7932. if (InputLoad->getOpcode() != ISD::LOAD)
  7933. return nullptr;
  7934. LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
  7935. return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
  7936. }
  7937. // Convert the argument APFloat to a single precision APFloat if there is no
  7938. // loss in information during the conversion to single precision APFloat and the
  7939. // resulting number is not a denormal number. Return true if successful.
  7940. bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
  7941. APFloat APFloatToConvert = ArgAPFloat;
  7942. bool LosesInfo = true;
  7943. APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  7944. &LosesInfo);
  7945. bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
  7946. if (Success)
  7947. ArgAPFloat = APFloatToConvert;
  7948. return Success;
  7949. }
  7950. // Bitcast the argument APInt to a double and convert it to a single precision
  7951. // APFloat, bitcast the APFloat to an APInt and assign it to the original
  7952. // argument if there is no loss in information during the conversion from
  7953. // double to single precision APFloat and the resulting number is not a denormal
  7954. // number. Return true if successful.
  7955. bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
  7956. double DpValue = ArgAPInt.bitsToDouble();
  7957. APFloat APFloatDp(DpValue);
  7958. bool Success = convertToNonDenormSingle(APFloatDp);
  7959. if (Success)
  7960. ArgAPInt = APFloatDp.bitcastToAPInt();
  7961. return Success;
  7962. }
  7963. // Nondestructive check for convertTonNonDenormSingle.
  7964. bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
  7965. // Only convert if it loses info, since XXSPLTIDP should
  7966. // handle the other case.
  7967. APFloat APFloatToConvert = ArgAPFloat;
  7968. bool LosesInfo = true;
  7969. APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  7970. &LosesInfo);
  7971. return (!LosesInfo && !APFloatToConvert.isDenormal());
  7972. }
  7973. static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
  7974. unsigned &Opcode) {
  7975. LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
  7976. if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
  7977. return false;
  7978. EVT Ty = Op->getValueType(0);
  7979. // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
  7980. // as we cannot handle extending loads for these types.
  7981. if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
  7982. ISD::isNON_EXTLoad(InputNode))
  7983. return true;
  7984. EVT MemVT = InputNode->getMemoryVT();
  7985. // For v8i16 and v16i8 types, extending loads can be handled as long as the
  7986. // memory VT is the same vector element VT type.
  7987. // The loads feeding into the v8i16 and v16i8 types will be extending because
  7988. // scalar i8/i16 are not legal types.
  7989. if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
  7990. (MemVT == Ty.getVectorElementType()))
  7991. return true;
  7992. if (Ty == MVT::v2i64) {
  7993. // Check the extend type, when the input type is i32, and the output vector
  7994. // type is v2i64.
  7995. if (MemVT == MVT::i32) {
  7996. if (ISD::isZEXTLoad(InputNode))
  7997. Opcode = PPCISD::ZEXT_LD_SPLAT;
  7998. if (ISD::isSEXTLoad(InputNode))
  7999. Opcode = PPCISD::SEXT_LD_SPLAT;
  8000. }
  8001. return true;
  8002. }
  8003. return false;
  8004. }
  8005. // If this is a case we can't handle, return null and let the default
  8006. // expansion code take care of it. If we CAN select this case, and if it
  8007. // selects to a single instruction, return Op. Otherwise, if we can codegen
  8008. // this case more efficiently than a constant pool load, lower it to the
  8009. // sequence of ops that should be used.
  8010. SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
  8011. SelectionDAG &DAG) const {
  8012. SDLoc dl(Op);
  8013. BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
  8014. assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
  8015. // Check if this is a splat of a constant value.
  8016. APInt APSplatBits, APSplatUndef;
  8017. unsigned SplatBitSize;
  8018. bool HasAnyUndefs;
  8019. bool BVNIsConstantSplat =
  8020. BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
  8021. HasAnyUndefs, 0, !Subtarget.isLittleEndian());
  8022. // If it is a splat of a double, check if we can shrink it to a 32 bit
  8023. // non-denormal float which when converted back to double gives us the same
  8024. // double. This is to exploit the XXSPLTIDP instruction.
  8025. // If we lose precision, we use XXSPLTI32DX.
  8026. if (BVNIsConstantSplat && (SplatBitSize == 64) &&
  8027. Subtarget.hasPrefixInstrs()) {
  8028. // Check the type first to short-circuit so we don't modify APSplatBits if
  8029. // this block isn't executed.
  8030. if ((Op->getValueType(0) == MVT::v2f64) &&
  8031. convertToNonDenormSingle(APSplatBits)) {
  8032. SDValue SplatNode = DAG.getNode(
  8033. PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
  8034. DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
  8035. return DAG.getBitcast(Op.getValueType(), SplatNode);
  8036. } else {
  8037. // We may lose precision, so we have to use XXSPLTI32DX.
  8038. uint32_t Hi =
  8039. (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
  8040. uint32_t Lo =
  8041. (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
  8042. SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
  8043. if (!Hi || !Lo)
  8044. // If either load is 0, then we should generate XXLXOR to set to 0.
  8045. SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
  8046. if (Hi)
  8047. SplatNode = DAG.getNode(
  8048. PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
  8049. DAG.getTargetConstant(0, dl, MVT::i32),
  8050. DAG.getTargetConstant(Hi, dl, MVT::i32));
  8051. if (Lo)
  8052. SplatNode =
  8053. DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
  8054. DAG.getTargetConstant(1, dl, MVT::i32),
  8055. DAG.getTargetConstant(Lo, dl, MVT::i32));
  8056. return DAG.getBitcast(Op.getValueType(), SplatNode);
  8057. }
  8058. }
  8059. if (!BVNIsConstantSplat || SplatBitSize > 32) {
  8060. unsigned NewOpcode = PPCISD::LD_SPLAT;
  8061. // Handle load-and-splat patterns as we have instructions that will do this
  8062. // in one go.
  8063. if (DAG.isSplatValue(Op, true) &&
  8064. isValidSplatLoad(Subtarget, Op, NewOpcode)) {
  8065. const SDValue *InputLoad = &Op.getOperand(0);
  8066. LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
  8067. // If the input load is an extending load, it will be an i32 -> i64
  8068. // extending load and isValidSplatLoad() will update NewOpcode.
  8069. unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
  8070. unsigned ElementSize =
  8071. MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
  8072. assert(((ElementSize == 2 * MemorySize)
  8073. ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
  8074. NewOpcode == PPCISD::SEXT_LD_SPLAT)
  8075. : (NewOpcode == PPCISD::LD_SPLAT)) &&
  8076. "Unmatched element size and opcode!\n");
  8077. // Checking for a single use of this load, we have to check for vector
  8078. // width (128 bits) / ElementSize uses (since each operand of the
  8079. // BUILD_VECTOR is a separate use of the value.
  8080. unsigned NumUsesOfInputLD = 128 / ElementSize;
  8081. for (SDValue BVInOp : Op->ops())
  8082. if (BVInOp.isUndef())
  8083. NumUsesOfInputLD--;
  8084. // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
  8085. // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
  8086. // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
  8087. // 15", but funciton IsValidSplatLoad() now will only return true when
  8088. // the data at index 0 is not nullptr. So we will not get into trouble for
  8089. // these cases.
  8090. //
  8091. // case 1 - lfiwzx/lfiwax
  8092. // 1.1: load result is i32 and is sign/zero extend to i64;
  8093. // 1.2: build a v2i64 vector type with above loaded value;
  8094. // 1.3: the vector has only one value at index 0, others are all undef;
  8095. // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
  8096. if (NumUsesOfInputLD == 1 &&
  8097. (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
  8098. !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
  8099. Subtarget.hasLFIWAX()))
  8100. return SDValue();
  8101. // case 2 - lxvr[hb]x
  8102. // 2.1: load result is at most i16;
  8103. // 2.2: build a vector with above loaded value;
  8104. // 2.3: the vector has only one value at index 0, others are all undef;
  8105. // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
  8106. if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
  8107. Subtarget.isISA3_1() && ElementSize <= 16)
  8108. return SDValue();
  8109. assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
  8110. if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
  8111. Subtarget.hasVSX()) {
  8112. SDValue Ops[] = {
  8113. LD->getChain(), // Chain
  8114. LD->getBasePtr(), // Ptr
  8115. DAG.getValueType(Op.getValueType()) // VT
  8116. };
  8117. SDValue LdSplt = DAG.getMemIntrinsicNode(
  8118. NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
  8119. LD->getMemoryVT(), LD->getMemOperand());
  8120. // Replace all uses of the output chain of the original load with the
  8121. // output chain of the new load.
  8122. DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
  8123. LdSplt.getValue(1));
  8124. return LdSplt;
  8125. }
  8126. }
  8127. // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
  8128. // 32-bits can be lowered to VSX instructions under certain conditions.
  8129. // Without VSX, there is no pattern more efficient than expanding the node.
  8130. if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
  8131. haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
  8132. Subtarget.hasP8Vector()))
  8133. return Op;
  8134. return SDValue();
  8135. }
  8136. uint64_t SplatBits = APSplatBits.getZExtValue();
  8137. uint64_t SplatUndef = APSplatUndef.getZExtValue();
  8138. unsigned SplatSize = SplatBitSize / 8;
  8139. // First, handle single instruction cases.
  8140. // All zeros?
  8141. if (SplatBits == 0) {
  8142. // Canonicalize all zero vectors to be v4i32.
  8143. if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
  8144. SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
  8145. Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
  8146. }
  8147. return Op;
  8148. }
  8149. // We have XXSPLTIW for constant splats four bytes wide.
  8150. // Given vector length is a multiple of 4, 2-byte splats can be replaced
  8151. // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
  8152. // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
  8153. // turned into a 4-byte splat of 0xABABABAB.
  8154. if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
  8155. return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
  8156. Op.getValueType(), DAG, dl);
  8157. if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
  8158. return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
  8159. dl);
  8160. // We have XXSPLTIB for constant splats one byte wide.
  8161. if (Subtarget.hasP9Vector() && SplatSize == 1)
  8162. return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
  8163. dl);
  8164. // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
  8165. int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
  8166. (32-SplatBitSize));
  8167. if (SextVal >= -16 && SextVal <= 15)
  8168. return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
  8169. dl);
  8170. // Two instruction sequences.
  8171. // If this value is in the range [-32,30] and is even, use:
  8172. // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
  8173. // If this value is in the range [17,31] and is odd, use:
  8174. // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
  8175. // If this value is in the range [-31,-17] and is odd, use:
  8176. // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
  8177. // Note the last two are three-instruction sequences.
  8178. if (SextVal >= -32 && SextVal <= 31) {
  8179. // To avoid having these optimizations undone by constant folding,
  8180. // we convert to a pseudo that will be expanded later into one of
  8181. // the above forms.
  8182. SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
  8183. EVT VT = (SplatSize == 1 ? MVT::v16i8 :
  8184. (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
  8185. SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
  8186. SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
  8187. if (VT == Op.getValueType())
  8188. return RetVal;
  8189. else
  8190. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
  8191. }
  8192. // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
  8193. // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
  8194. // for fneg/fabs.
  8195. if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
  8196. // Make -1 and vspltisw -1:
  8197. SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
  8198. // Make the VSLW intrinsic, computing 0x8000_0000.
  8199. SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
  8200. OnesV, DAG, dl);
  8201. // xor by OnesV to invert it.
  8202. Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
  8203. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
  8204. }
  8205. // Check to see if this is a wide variety of vsplti*, binop self cases.
  8206. static const signed char SplatCsts[] = {
  8207. -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
  8208. -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
  8209. };
  8210. for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
  8211. // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
  8212. // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
  8213. int i = SplatCsts[idx];
  8214. // Figure out what shift amount will be used by altivec if shifted by i in
  8215. // this splat size.
  8216. unsigned TypeShiftAmt = i & (SplatBitSize-1);
  8217. // vsplti + shl self.
  8218. if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
  8219. SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
  8220. static const unsigned IIDs[] = { // Intrinsic to use for each size.
  8221. Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
  8222. Intrinsic::ppc_altivec_vslw
  8223. };
  8224. Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
  8225. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
  8226. }
  8227. // vsplti + srl self.
  8228. if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
  8229. SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
  8230. static const unsigned IIDs[] = { // Intrinsic to use for each size.
  8231. Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
  8232. Intrinsic::ppc_altivec_vsrw
  8233. };
  8234. Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
  8235. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
  8236. }
  8237. // vsplti + rol self.
  8238. if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
  8239. ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
  8240. SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
  8241. static const unsigned IIDs[] = { // Intrinsic to use for each size.
  8242. Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
  8243. Intrinsic::ppc_altivec_vrlw
  8244. };
  8245. Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
  8246. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
  8247. }
  8248. // t = vsplti c, result = vsldoi t, t, 1
  8249. if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
  8250. SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
  8251. unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
  8252. return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
  8253. }
  8254. // t = vsplti c, result = vsldoi t, t, 2
  8255. if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
  8256. SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
  8257. unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
  8258. return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
  8259. }
  8260. // t = vsplti c, result = vsldoi t, t, 3
  8261. if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
  8262. SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
  8263. unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
  8264. return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
  8265. }
  8266. }
  8267. return SDValue();
  8268. }
  8269. /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
  8270. /// the specified operations to build the shuffle.
  8271. static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
  8272. SDValue RHS, SelectionDAG &DAG,
  8273. const SDLoc &dl) {
  8274. unsigned OpNum = (PFEntry >> 26) & 0x0F;
  8275. unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
  8276. unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
  8277. enum {
  8278. OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
  8279. OP_VMRGHW,
  8280. OP_VMRGLW,
  8281. OP_VSPLTISW0,
  8282. OP_VSPLTISW1,
  8283. OP_VSPLTISW2,
  8284. OP_VSPLTISW3,
  8285. OP_VSLDOI4,
  8286. OP_VSLDOI8,
  8287. OP_VSLDOI12
  8288. };
  8289. if (OpNum == OP_COPY) {
  8290. if (LHSID == (1*9+2)*9+3) return LHS;
  8291. assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
  8292. return RHS;
  8293. }
  8294. SDValue OpLHS, OpRHS;
  8295. OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
  8296. OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
  8297. int ShufIdxs[16];
  8298. switch (OpNum) {
  8299. default: llvm_unreachable("Unknown i32 permute!");
  8300. case OP_VMRGHW:
  8301. ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
  8302. ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
  8303. ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
  8304. ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
  8305. break;
  8306. case OP_VMRGLW:
  8307. ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
  8308. ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
  8309. ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
  8310. ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
  8311. break;
  8312. case OP_VSPLTISW0:
  8313. for (unsigned i = 0; i != 16; ++i)
  8314. ShufIdxs[i] = (i&3)+0;
  8315. break;
  8316. case OP_VSPLTISW1:
  8317. for (unsigned i = 0; i != 16; ++i)
  8318. ShufIdxs[i] = (i&3)+4;
  8319. break;
  8320. case OP_VSPLTISW2:
  8321. for (unsigned i = 0; i != 16; ++i)
  8322. ShufIdxs[i] = (i&3)+8;
  8323. break;
  8324. case OP_VSPLTISW3:
  8325. for (unsigned i = 0; i != 16; ++i)
  8326. ShufIdxs[i] = (i&3)+12;
  8327. break;
  8328. case OP_VSLDOI4:
  8329. return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
  8330. case OP_VSLDOI8:
  8331. return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
  8332. case OP_VSLDOI12:
  8333. return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
  8334. }
  8335. EVT VT = OpLHS.getValueType();
  8336. OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
  8337. OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
  8338. SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
  8339. return DAG.getNode(ISD::BITCAST, dl, VT, T);
  8340. }
  8341. /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
  8342. /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
  8343. /// SDValue.
  8344. SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
  8345. SelectionDAG &DAG) const {
  8346. const unsigned BytesInVector = 16;
  8347. bool IsLE = Subtarget.isLittleEndian();
  8348. SDLoc dl(N);
  8349. SDValue V1 = N->getOperand(0);
  8350. SDValue V2 = N->getOperand(1);
  8351. unsigned ShiftElts = 0, InsertAtByte = 0;
  8352. bool Swap = false;
  8353. // Shifts required to get the byte we want at element 7.
  8354. unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1,
  8355. 0, 15, 14, 13, 12, 11, 10, 9};
  8356. unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
  8357. 1, 2, 3, 4, 5, 6, 7, 8};
  8358. ArrayRef<int> Mask = N->getMask();
  8359. int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
  8360. // For each mask element, find out if we're just inserting something
  8361. // from V2 into V1 or vice versa.
  8362. // Possible permutations inserting an element from V2 into V1:
  8363. // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  8364. // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  8365. // ...
  8366. // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
  8367. // Inserting from V1 into V2 will be similar, except mask range will be
  8368. // [16,31].
  8369. bool FoundCandidate = false;
  8370. // If both vector operands for the shuffle are the same vector, the mask
  8371. // will contain only elements from the first one and the second one will be
  8372. // undef.
  8373. unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
  8374. // Go through the mask of half-words to find an element that's being moved
  8375. // from one vector to the other.
  8376. for (unsigned i = 0; i < BytesInVector; ++i) {
  8377. unsigned CurrentElement = Mask[i];
  8378. // If 2nd operand is undefined, we should only look for element 7 in the
  8379. // Mask.
  8380. if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
  8381. continue;
  8382. bool OtherElementsInOrder = true;
  8383. // Examine the other elements in the Mask to see if they're in original
  8384. // order.
  8385. for (unsigned j = 0; j < BytesInVector; ++j) {
  8386. if (j == i)
  8387. continue;
  8388. // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
  8389. // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined,
  8390. // in which we always assume we're always picking from the 1st operand.
  8391. int MaskOffset =
  8392. (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
  8393. if (Mask[j] != OriginalOrder[j] + MaskOffset) {
  8394. OtherElementsInOrder = false;
  8395. break;
  8396. }
  8397. }
  8398. // If other elements are in original order, we record the number of shifts
  8399. // we need to get the element we want into element 7. Also record which byte
  8400. // in the vector we should insert into.
  8401. if (OtherElementsInOrder) {
  8402. // If 2nd operand is undefined, we assume no shifts and no swapping.
  8403. if (V2.isUndef()) {
  8404. ShiftElts = 0;
  8405. Swap = false;
  8406. } else {
  8407. // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
  8408. ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
  8409. : BigEndianShifts[CurrentElement & 0xF];
  8410. Swap = CurrentElement < BytesInVector;
  8411. }
  8412. InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
  8413. FoundCandidate = true;
  8414. break;
  8415. }
  8416. }
  8417. if (!FoundCandidate)
  8418. return SDValue();
  8419. // Candidate found, construct the proper SDAG sequence with VINSERTB,
  8420. // optionally with VECSHL if shift is required.
  8421. if (Swap)
  8422. std::swap(V1, V2);
  8423. if (V2.isUndef())
  8424. V2 = V1;
  8425. if (ShiftElts) {
  8426. SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
  8427. DAG.getConstant(ShiftElts, dl, MVT::i32));
  8428. return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
  8429. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8430. }
  8431. return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
  8432. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8433. }
  8434. /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
  8435. /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
  8436. /// SDValue.
  8437. SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
  8438. SelectionDAG &DAG) const {
  8439. const unsigned NumHalfWords = 8;
  8440. const unsigned BytesInVector = NumHalfWords * 2;
  8441. // Check that the shuffle is on half-words.
  8442. if (!isNByteElemShuffleMask(N, 2, 1))
  8443. return SDValue();
  8444. bool IsLE = Subtarget.isLittleEndian();
  8445. SDLoc dl(N);
  8446. SDValue V1 = N->getOperand(0);
  8447. SDValue V2 = N->getOperand(1);
  8448. unsigned ShiftElts = 0, InsertAtByte = 0;
  8449. bool Swap = false;
  8450. // Shifts required to get the half-word we want at element 3.
  8451. unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
  8452. unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
  8453. uint32_t Mask = 0;
  8454. uint32_t OriginalOrderLow = 0x1234567;
  8455. uint32_t OriginalOrderHigh = 0x89ABCDEF;
  8456. // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a
  8457. // 32-bit space, only need 4-bit nibbles per element.
  8458. for (unsigned i = 0; i < NumHalfWords; ++i) {
  8459. unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
  8460. Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
  8461. }
  8462. // For each mask element, find out if we're just inserting something
  8463. // from V2 into V1 or vice versa. Possible permutations inserting an element
  8464. // from V2 into V1:
  8465. // X, 1, 2, 3, 4, 5, 6, 7
  8466. // 0, X, 2, 3, 4, 5, 6, 7
  8467. // 0, 1, X, 3, 4, 5, 6, 7
  8468. // 0, 1, 2, X, 4, 5, 6, 7
  8469. // 0, 1, 2, 3, X, 5, 6, 7
  8470. // 0, 1, 2, 3, 4, X, 6, 7
  8471. // 0, 1, 2, 3, 4, 5, X, 7
  8472. // 0, 1, 2, 3, 4, 5, 6, X
  8473. // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
  8474. bool FoundCandidate = false;
  8475. // Go through the mask of half-words to find an element that's being moved
  8476. // from one vector to the other.
  8477. for (unsigned i = 0; i < NumHalfWords; ++i) {
  8478. unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
  8479. uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
  8480. uint32_t MaskOtherElts = ~(0xF << MaskShift);
  8481. uint32_t TargetOrder = 0x0;
  8482. // If both vector operands for the shuffle are the same vector, the mask
  8483. // will contain only elements from the first one and the second one will be
  8484. // undef.
  8485. if (V2.isUndef()) {
  8486. ShiftElts = 0;
  8487. unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
  8488. TargetOrder = OriginalOrderLow;
  8489. Swap = false;
  8490. // Skip if not the correct element or mask of other elements don't equal
  8491. // to our expected order.
  8492. if (MaskOneElt == VINSERTHSrcElem &&
  8493. (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
  8494. InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
  8495. FoundCandidate = true;
  8496. break;
  8497. }
  8498. } else { // If both operands are defined.
  8499. // Target order is [8,15] if the current mask is between [0,7].
  8500. TargetOrder =
  8501. (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
  8502. // Skip if mask of other elements don't equal our expected order.
  8503. if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
  8504. // We only need the last 3 bits for the number of shifts.
  8505. ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
  8506. : BigEndianShifts[MaskOneElt & 0x7];
  8507. InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
  8508. Swap = MaskOneElt < NumHalfWords;
  8509. FoundCandidate = true;
  8510. break;
  8511. }
  8512. }
  8513. }
  8514. if (!FoundCandidate)
  8515. return SDValue();
  8516. // Candidate found, construct the proper SDAG sequence with VINSERTH,
  8517. // optionally with VECSHL if shift is required.
  8518. if (Swap)
  8519. std::swap(V1, V2);
  8520. if (V2.isUndef())
  8521. V2 = V1;
  8522. SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
  8523. if (ShiftElts) {
  8524. // Double ShiftElts because we're left shifting on v16i8 type.
  8525. SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
  8526. DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
  8527. SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
  8528. SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
  8529. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8530. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
  8531. }
  8532. SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
  8533. SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
  8534. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8535. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
  8536. }
  8537. /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
  8538. /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
  8539. /// return the default SDValue.
  8540. SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
  8541. SelectionDAG &DAG) const {
  8542. // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
  8543. // to v16i8. Peek through the bitcasts to get the actual operands.
  8544. SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
  8545. SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
  8546. auto ShuffleMask = SVN->getMask();
  8547. SDValue VecShuffle(SVN, 0);
  8548. SDLoc DL(SVN);
  8549. // Check that we have a four byte shuffle.
  8550. if (!isNByteElemShuffleMask(SVN, 4, 1))
  8551. return SDValue();
  8552. // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
  8553. if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
  8554. std::swap(LHS, RHS);
  8555. VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
  8556. ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
  8557. }
  8558. // Ensure that the RHS is a vector of constants.
  8559. BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
  8560. if (!BVN)
  8561. return SDValue();
  8562. // Check if RHS is a splat of 4-bytes (or smaller).
  8563. APInt APSplatValue, APSplatUndef;
  8564. unsigned SplatBitSize;
  8565. bool HasAnyUndefs;
  8566. if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
  8567. HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
  8568. SplatBitSize > 32)
  8569. return SDValue();
  8570. // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
  8571. // The instruction splats a constant C into two words of the source vector
  8572. // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
  8573. // Thus we check that the shuffle mask is the equivalent of
  8574. // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
  8575. // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
  8576. // within each word are consecutive, so we only need to check the first byte.
  8577. SDValue Index;
  8578. bool IsLE = Subtarget.isLittleEndian();
  8579. if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
  8580. (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
  8581. ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
  8582. Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
  8583. else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
  8584. (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
  8585. ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
  8586. Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
  8587. else
  8588. return SDValue();
  8589. // If the splat is narrower than 32-bits, we need to get the 32-bit value
  8590. // for XXSPLTI32DX.
  8591. unsigned SplatVal = APSplatValue.getZExtValue();
  8592. for (; SplatBitSize < 32; SplatBitSize <<= 1)
  8593. SplatVal |= (SplatVal << SplatBitSize);
  8594. SDValue SplatNode = DAG.getNode(
  8595. PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
  8596. Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
  8597. return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
  8598. }
  8599. /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
  8600. /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
  8601. /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
  8602. /// i.e (or (shl x, C1), (srl x, 128-C1)).
  8603. SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
  8604. assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
  8605. assert(Op.getValueType() == MVT::v1i128 &&
  8606. "Only set v1i128 as custom, other type shouldn't reach here!");
  8607. SDLoc dl(Op);
  8608. SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
  8609. SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
  8610. unsigned SHLAmt = N1.getConstantOperandVal(0);
  8611. if (SHLAmt % 8 == 0) {
  8612. SmallVector<int, 16> Mask(16, 0);
  8613. std::iota(Mask.begin(), Mask.end(), 0);
  8614. std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
  8615. if (SDValue Shuffle =
  8616. DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
  8617. DAG.getUNDEF(MVT::v16i8), Mask))
  8618. return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
  8619. }
  8620. SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
  8621. SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
  8622. DAG.getConstant(SHLAmt, dl, MVT::i32));
  8623. SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
  8624. DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
  8625. SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
  8626. return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
  8627. }
  8628. /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
  8629. /// is a shuffle we can handle in a single instruction, return it. Otherwise,
  8630. /// return the code it can be lowered into. Worst case, it can always be
  8631. /// lowered into a vperm.
  8632. SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
  8633. SelectionDAG &DAG) const {
  8634. SDLoc dl(Op);
  8635. SDValue V1 = Op.getOperand(0);
  8636. SDValue V2 = Op.getOperand(1);
  8637. ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
  8638. // Any nodes that were combined in the target-independent combiner prior
  8639. // to vector legalization will not be sent to the target combine. Try to
  8640. // combine it here.
  8641. if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
  8642. if (!isa<ShuffleVectorSDNode>(NewShuffle))
  8643. return NewShuffle;
  8644. Op = NewShuffle;
  8645. SVOp = cast<ShuffleVectorSDNode>(Op);
  8646. V1 = Op.getOperand(0);
  8647. V2 = Op.getOperand(1);
  8648. }
  8649. EVT VT = Op.getValueType();
  8650. bool isLittleEndian = Subtarget.isLittleEndian();
  8651. unsigned ShiftElts, InsertAtByte;
  8652. bool Swap = false;
  8653. // If this is a load-and-splat, we can do that with a single instruction
  8654. // in some cases. However if the load has multiple uses, we don't want to
  8655. // combine it because that will just produce multiple loads.
  8656. bool IsPermutedLoad = false;
  8657. const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
  8658. if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
  8659. (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
  8660. InputLoad->hasOneUse()) {
  8661. bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
  8662. int SplatIdx =
  8663. PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
  8664. // The splat index for permuted loads will be in the left half of the vector
  8665. // which is strictly wider than the loaded value by 8 bytes. So we need to
  8666. // adjust the splat index to point to the correct address in memory.
  8667. if (IsPermutedLoad) {
  8668. assert((isLittleEndian || IsFourByte) &&
  8669. "Unexpected size for permuted load on big endian target");
  8670. SplatIdx += IsFourByte ? 2 : 1;
  8671. assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
  8672. "Splat of a value outside of the loaded memory");
  8673. }
  8674. LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
  8675. // For 4-byte load-and-splat, we need Power9.
  8676. if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
  8677. uint64_t Offset = 0;
  8678. if (IsFourByte)
  8679. Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
  8680. else
  8681. Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
  8682. // If the width of the load is the same as the width of the splat,
  8683. // loading with an offset would load the wrong memory.
  8684. if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
  8685. Offset = 0;
  8686. SDValue BasePtr = LD->getBasePtr();
  8687. if (Offset != 0)
  8688. BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
  8689. BasePtr, DAG.getIntPtrConstant(Offset, dl));
  8690. SDValue Ops[] = {
  8691. LD->getChain(), // Chain
  8692. BasePtr, // BasePtr
  8693. DAG.getValueType(Op.getValueType()) // VT
  8694. };
  8695. SDVTList VTL =
  8696. DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
  8697. SDValue LdSplt =
  8698. DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
  8699. Ops, LD->getMemoryVT(), LD->getMemOperand());
  8700. DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
  8701. if (LdSplt.getValueType() != SVOp->getValueType(0))
  8702. LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
  8703. return LdSplt;
  8704. }
  8705. }
  8706. if (Subtarget.hasP9Vector() &&
  8707. PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
  8708. isLittleEndian)) {
  8709. if (Swap)
  8710. std::swap(V1, V2);
  8711. SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
  8712. SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
  8713. if (ShiftElts) {
  8714. SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
  8715. DAG.getConstant(ShiftElts, dl, MVT::i32));
  8716. SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
  8717. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8718. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
  8719. }
  8720. SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
  8721. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  8722. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
  8723. }
  8724. if (Subtarget.hasPrefixInstrs()) {
  8725. SDValue SplatInsertNode;
  8726. if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
  8727. return SplatInsertNode;
  8728. }
  8729. if (Subtarget.hasP9Altivec()) {
  8730. SDValue NewISDNode;
  8731. if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
  8732. return NewISDNode;
  8733. if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
  8734. return NewISDNode;
  8735. }
  8736. if (Subtarget.hasVSX() &&
  8737. PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
  8738. if (Swap)
  8739. std::swap(V1, V2);
  8740. SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
  8741. SDValue Conv2 =
  8742. DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
  8743. SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
  8744. DAG.getConstant(ShiftElts, dl, MVT::i32));
  8745. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
  8746. }
  8747. if (Subtarget.hasVSX() &&
  8748. PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
  8749. if (Swap)
  8750. std::swap(V1, V2);
  8751. SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
  8752. SDValue Conv2 =
  8753. DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
  8754. SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
  8755. DAG.getConstant(ShiftElts, dl, MVT::i32));
  8756. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
  8757. }
  8758. if (Subtarget.hasP9Vector()) {
  8759. if (PPC::isXXBRHShuffleMask(SVOp)) {
  8760. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
  8761. SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
  8762. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
  8763. } else if (PPC::isXXBRWShuffleMask(SVOp)) {
  8764. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
  8765. SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
  8766. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
  8767. } else if (PPC::isXXBRDShuffleMask(SVOp)) {
  8768. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
  8769. SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
  8770. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
  8771. } else if (PPC::isXXBRQShuffleMask(SVOp)) {
  8772. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
  8773. SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
  8774. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
  8775. }
  8776. }
  8777. if (Subtarget.hasVSX()) {
  8778. if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
  8779. int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
  8780. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
  8781. SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
  8782. DAG.getConstant(SplatIdx, dl, MVT::i32));
  8783. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
  8784. }
  8785. // Left shifts of 8 bytes are actually swaps. Convert accordingly.
  8786. if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
  8787. SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
  8788. SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
  8789. return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
  8790. }
  8791. }
  8792. // Cases that are handled by instructions that take permute immediates
  8793. // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
  8794. // selected by the instruction selector.
  8795. if (V2.isUndef()) {
  8796. if (PPC::isSplatShuffleMask(SVOp, 1) ||
  8797. PPC::isSplatShuffleMask(SVOp, 2) ||
  8798. PPC::isSplatShuffleMask(SVOp, 4) ||
  8799. PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
  8800. PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
  8801. PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
  8802. PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
  8803. PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
  8804. PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
  8805. PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
  8806. PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
  8807. PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
  8808. (Subtarget.hasP8Altivec() && (
  8809. PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
  8810. PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
  8811. PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
  8812. return Op;
  8813. }
  8814. }
  8815. // Altivec has a variety of "shuffle immediates" that take two vector inputs
  8816. // and produce a fixed permutation. If any of these match, do not lower to
  8817. // VPERM.
  8818. unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
  8819. if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
  8820. PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
  8821. PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
  8822. PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
  8823. PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
  8824. PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
  8825. PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
  8826. PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
  8827. PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
  8828. (Subtarget.hasP8Altivec() && (
  8829. PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
  8830. PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
  8831. PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
  8832. return Op;
  8833. // Check to see if this is a shuffle of 4-byte values. If so, we can use our
  8834. // perfect shuffle table to emit an optimal matching sequence.
  8835. ArrayRef<int> PermMask = SVOp->getMask();
  8836. unsigned PFIndexes[4];
  8837. bool isFourElementShuffle = true;
  8838. for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
  8839. unsigned EltNo = 8; // Start out undef.
  8840. for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
  8841. if (PermMask[i*4+j] < 0)
  8842. continue; // Undef, ignore it.
  8843. unsigned ByteSource = PermMask[i*4+j];
  8844. if ((ByteSource & 3) != j) {
  8845. isFourElementShuffle = false;
  8846. break;
  8847. }
  8848. if (EltNo == 8) {
  8849. EltNo = ByteSource/4;
  8850. } else if (EltNo != ByteSource/4) {
  8851. isFourElementShuffle = false;
  8852. break;
  8853. }
  8854. }
  8855. PFIndexes[i] = EltNo;
  8856. }
  8857. // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
  8858. // perfect shuffle vector to determine if it is cost effective to do this as
  8859. // discrete instructions, or whether we should use a vperm.
  8860. // For now, we skip this for little endian until such time as we have a
  8861. // little-endian perfect shuffle table.
  8862. if (isFourElementShuffle && !isLittleEndian) {
  8863. // Compute the index in the perfect shuffle table.
  8864. unsigned PFTableIndex =
  8865. PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
  8866. unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
  8867. unsigned Cost = (PFEntry >> 30);
  8868. // Determining when to avoid vperm is tricky. Many things affect the cost
  8869. // of vperm, particularly how many times the perm mask needs to be computed.
  8870. // For example, if the perm mask can be hoisted out of a loop or is already
  8871. // used (perhaps because there are multiple permutes with the same shuffle
  8872. // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
  8873. // the loop requires an extra register.
  8874. //
  8875. // As a compromise, we only emit discrete instructions if the shuffle can be
  8876. // generated in 3 or fewer operations. When we have loop information
  8877. // available, if this block is within a loop, we should avoid using vperm
  8878. // for 3-operation perms and use a constant pool load instead.
  8879. if (Cost < 3)
  8880. return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
  8881. }
  8882. // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
  8883. // vector that will get spilled to the constant pool.
  8884. if (V2.isUndef()) V2 = V1;
  8885. // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
  8886. // that it is in input element units, not in bytes. Convert now.
  8887. // For little endian, the order of the input vectors is reversed, and
  8888. // the permutation mask is complemented with respect to 31. This is
  8889. // necessary to produce proper semantics with the big-endian-biased vperm
  8890. // instruction.
  8891. EVT EltVT = V1.getValueType().getVectorElementType();
  8892. unsigned BytesPerElement = EltVT.getSizeInBits()/8;
  8893. SmallVector<SDValue, 16> ResultMask;
  8894. for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
  8895. unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
  8896. for (unsigned j = 0; j != BytesPerElement; ++j)
  8897. if (isLittleEndian)
  8898. ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
  8899. dl, MVT::i32));
  8900. else
  8901. ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
  8902. MVT::i32));
  8903. }
  8904. ShufflesHandledWithVPERM++;
  8905. SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
  8906. LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
  8907. LLVM_DEBUG(SVOp->dump());
  8908. LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
  8909. LLVM_DEBUG(VPermMask.dump());
  8910. if (isLittleEndian)
  8911. return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
  8912. V2, V1, VPermMask);
  8913. else
  8914. return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
  8915. V1, V2, VPermMask);
  8916. }
  8917. /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
  8918. /// vector comparison. If it is, return true and fill in Opc/isDot with
  8919. /// information about the intrinsic.
  8920. static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
  8921. bool &isDot, const PPCSubtarget &Subtarget) {
  8922. unsigned IntrinsicID =
  8923. cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
  8924. CompareOpc = -1;
  8925. isDot = false;
  8926. switch (IntrinsicID) {
  8927. default:
  8928. return false;
  8929. // Comparison predicates.
  8930. case Intrinsic::ppc_altivec_vcmpbfp_p:
  8931. CompareOpc = 966;
  8932. isDot = true;
  8933. break;
  8934. case Intrinsic::ppc_altivec_vcmpeqfp_p:
  8935. CompareOpc = 198;
  8936. isDot = true;
  8937. break;
  8938. case Intrinsic::ppc_altivec_vcmpequb_p:
  8939. CompareOpc = 6;
  8940. isDot = true;
  8941. break;
  8942. case Intrinsic::ppc_altivec_vcmpequh_p:
  8943. CompareOpc = 70;
  8944. isDot = true;
  8945. break;
  8946. case Intrinsic::ppc_altivec_vcmpequw_p:
  8947. CompareOpc = 134;
  8948. isDot = true;
  8949. break;
  8950. case Intrinsic::ppc_altivec_vcmpequd_p:
  8951. if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
  8952. CompareOpc = 199;
  8953. isDot = true;
  8954. } else
  8955. return false;
  8956. break;
  8957. case Intrinsic::ppc_altivec_vcmpneb_p:
  8958. case Intrinsic::ppc_altivec_vcmpneh_p:
  8959. case Intrinsic::ppc_altivec_vcmpnew_p:
  8960. case Intrinsic::ppc_altivec_vcmpnezb_p:
  8961. case Intrinsic::ppc_altivec_vcmpnezh_p:
  8962. case Intrinsic::ppc_altivec_vcmpnezw_p:
  8963. if (Subtarget.hasP9Altivec()) {
  8964. switch (IntrinsicID) {
  8965. default:
  8966. llvm_unreachable("Unknown comparison intrinsic.");
  8967. case Intrinsic::ppc_altivec_vcmpneb_p:
  8968. CompareOpc = 7;
  8969. break;
  8970. case Intrinsic::ppc_altivec_vcmpneh_p:
  8971. CompareOpc = 71;
  8972. break;
  8973. case Intrinsic::ppc_altivec_vcmpnew_p:
  8974. CompareOpc = 135;
  8975. break;
  8976. case Intrinsic::ppc_altivec_vcmpnezb_p:
  8977. CompareOpc = 263;
  8978. break;
  8979. case Intrinsic::ppc_altivec_vcmpnezh_p:
  8980. CompareOpc = 327;
  8981. break;
  8982. case Intrinsic::ppc_altivec_vcmpnezw_p:
  8983. CompareOpc = 391;
  8984. break;
  8985. }
  8986. isDot = true;
  8987. } else
  8988. return false;
  8989. break;
  8990. case Intrinsic::ppc_altivec_vcmpgefp_p:
  8991. CompareOpc = 454;
  8992. isDot = true;
  8993. break;
  8994. case Intrinsic::ppc_altivec_vcmpgtfp_p:
  8995. CompareOpc = 710;
  8996. isDot = true;
  8997. break;
  8998. case Intrinsic::ppc_altivec_vcmpgtsb_p:
  8999. CompareOpc = 774;
  9000. isDot = true;
  9001. break;
  9002. case Intrinsic::ppc_altivec_vcmpgtsh_p:
  9003. CompareOpc = 838;
  9004. isDot = true;
  9005. break;
  9006. case Intrinsic::ppc_altivec_vcmpgtsw_p:
  9007. CompareOpc = 902;
  9008. isDot = true;
  9009. break;
  9010. case Intrinsic::ppc_altivec_vcmpgtsd_p:
  9011. if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
  9012. CompareOpc = 967;
  9013. isDot = true;
  9014. } else
  9015. return false;
  9016. break;
  9017. case Intrinsic::ppc_altivec_vcmpgtub_p:
  9018. CompareOpc = 518;
  9019. isDot = true;
  9020. break;
  9021. case Intrinsic::ppc_altivec_vcmpgtuh_p:
  9022. CompareOpc = 582;
  9023. isDot = true;
  9024. break;
  9025. case Intrinsic::ppc_altivec_vcmpgtuw_p:
  9026. CompareOpc = 646;
  9027. isDot = true;
  9028. break;
  9029. case Intrinsic::ppc_altivec_vcmpgtud_p:
  9030. if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
  9031. CompareOpc = 711;
  9032. isDot = true;
  9033. } else
  9034. return false;
  9035. break;
  9036. case Intrinsic::ppc_altivec_vcmpequq:
  9037. case Intrinsic::ppc_altivec_vcmpgtsq:
  9038. case Intrinsic::ppc_altivec_vcmpgtuq:
  9039. if (!Subtarget.isISA3_1())
  9040. return false;
  9041. switch (IntrinsicID) {
  9042. default:
  9043. llvm_unreachable("Unknown comparison intrinsic.");
  9044. case Intrinsic::ppc_altivec_vcmpequq:
  9045. CompareOpc = 455;
  9046. break;
  9047. case Intrinsic::ppc_altivec_vcmpgtsq:
  9048. CompareOpc = 903;
  9049. break;
  9050. case Intrinsic::ppc_altivec_vcmpgtuq:
  9051. CompareOpc = 647;
  9052. break;
  9053. }
  9054. break;
  9055. // VSX predicate comparisons use the same infrastructure
  9056. case Intrinsic::ppc_vsx_xvcmpeqdp_p:
  9057. case Intrinsic::ppc_vsx_xvcmpgedp_p:
  9058. case Intrinsic::ppc_vsx_xvcmpgtdp_p:
  9059. case Intrinsic::ppc_vsx_xvcmpeqsp_p:
  9060. case Intrinsic::ppc_vsx_xvcmpgesp_p:
  9061. case Intrinsic::ppc_vsx_xvcmpgtsp_p:
  9062. if (Subtarget.hasVSX()) {
  9063. switch (IntrinsicID) {
  9064. case Intrinsic::ppc_vsx_xvcmpeqdp_p:
  9065. CompareOpc = 99;
  9066. break;
  9067. case Intrinsic::ppc_vsx_xvcmpgedp_p:
  9068. CompareOpc = 115;
  9069. break;
  9070. case Intrinsic::ppc_vsx_xvcmpgtdp_p:
  9071. CompareOpc = 107;
  9072. break;
  9073. case Intrinsic::ppc_vsx_xvcmpeqsp_p:
  9074. CompareOpc = 67;
  9075. break;
  9076. case Intrinsic::ppc_vsx_xvcmpgesp_p:
  9077. CompareOpc = 83;
  9078. break;
  9079. case Intrinsic::ppc_vsx_xvcmpgtsp_p:
  9080. CompareOpc = 75;
  9081. break;
  9082. }
  9083. isDot = true;
  9084. } else
  9085. return false;
  9086. break;
  9087. // Normal Comparisons.
  9088. case Intrinsic::ppc_altivec_vcmpbfp:
  9089. CompareOpc = 966;
  9090. break;
  9091. case Intrinsic::ppc_altivec_vcmpeqfp:
  9092. CompareOpc = 198;
  9093. break;
  9094. case Intrinsic::ppc_altivec_vcmpequb:
  9095. CompareOpc = 6;
  9096. break;
  9097. case Intrinsic::ppc_altivec_vcmpequh:
  9098. CompareOpc = 70;
  9099. break;
  9100. case Intrinsic::ppc_altivec_vcmpequw:
  9101. CompareOpc = 134;
  9102. break;
  9103. case Intrinsic::ppc_altivec_vcmpequd:
  9104. if (Subtarget.hasP8Altivec())
  9105. CompareOpc = 199;
  9106. else
  9107. return false;
  9108. break;
  9109. case Intrinsic::ppc_altivec_vcmpneb:
  9110. case Intrinsic::ppc_altivec_vcmpneh:
  9111. case Intrinsic::ppc_altivec_vcmpnew:
  9112. case Intrinsic::ppc_altivec_vcmpnezb:
  9113. case Intrinsic::ppc_altivec_vcmpnezh:
  9114. case Intrinsic::ppc_altivec_vcmpnezw:
  9115. if (Subtarget.hasP9Altivec())
  9116. switch (IntrinsicID) {
  9117. default:
  9118. llvm_unreachable("Unknown comparison intrinsic.");
  9119. case Intrinsic::ppc_altivec_vcmpneb:
  9120. CompareOpc = 7;
  9121. break;
  9122. case Intrinsic::ppc_altivec_vcmpneh:
  9123. CompareOpc = 71;
  9124. break;
  9125. case Intrinsic::ppc_altivec_vcmpnew:
  9126. CompareOpc = 135;
  9127. break;
  9128. case Intrinsic::ppc_altivec_vcmpnezb:
  9129. CompareOpc = 263;
  9130. break;
  9131. case Intrinsic::ppc_altivec_vcmpnezh:
  9132. CompareOpc = 327;
  9133. break;
  9134. case Intrinsic::ppc_altivec_vcmpnezw:
  9135. CompareOpc = 391;
  9136. break;
  9137. }
  9138. else
  9139. return false;
  9140. break;
  9141. case Intrinsic::ppc_altivec_vcmpgefp:
  9142. CompareOpc = 454;
  9143. break;
  9144. case Intrinsic::ppc_altivec_vcmpgtfp:
  9145. CompareOpc = 710;
  9146. break;
  9147. case Intrinsic::ppc_altivec_vcmpgtsb:
  9148. CompareOpc = 774;
  9149. break;
  9150. case Intrinsic::ppc_altivec_vcmpgtsh:
  9151. CompareOpc = 838;
  9152. break;
  9153. case Intrinsic::ppc_altivec_vcmpgtsw:
  9154. CompareOpc = 902;
  9155. break;
  9156. case Intrinsic::ppc_altivec_vcmpgtsd:
  9157. if (Subtarget.hasP8Altivec())
  9158. CompareOpc = 967;
  9159. else
  9160. return false;
  9161. break;
  9162. case Intrinsic::ppc_altivec_vcmpgtub:
  9163. CompareOpc = 518;
  9164. break;
  9165. case Intrinsic::ppc_altivec_vcmpgtuh:
  9166. CompareOpc = 582;
  9167. break;
  9168. case Intrinsic::ppc_altivec_vcmpgtuw:
  9169. CompareOpc = 646;
  9170. break;
  9171. case Intrinsic::ppc_altivec_vcmpgtud:
  9172. if (Subtarget.hasP8Altivec())
  9173. CompareOpc = 711;
  9174. else
  9175. return false;
  9176. break;
  9177. case Intrinsic::ppc_altivec_vcmpequq_p:
  9178. case Intrinsic::ppc_altivec_vcmpgtsq_p:
  9179. case Intrinsic::ppc_altivec_vcmpgtuq_p:
  9180. if (!Subtarget.isISA3_1())
  9181. return false;
  9182. switch (IntrinsicID) {
  9183. default:
  9184. llvm_unreachable("Unknown comparison intrinsic.");
  9185. case Intrinsic::ppc_altivec_vcmpequq_p:
  9186. CompareOpc = 455;
  9187. break;
  9188. case Intrinsic::ppc_altivec_vcmpgtsq_p:
  9189. CompareOpc = 903;
  9190. break;
  9191. case Intrinsic::ppc_altivec_vcmpgtuq_p:
  9192. CompareOpc = 647;
  9193. break;
  9194. }
  9195. isDot = true;
  9196. break;
  9197. }
  9198. return true;
  9199. }
  9200. /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
  9201. /// lower, do it, otherwise return null.
  9202. SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
  9203. SelectionDAG &DAG) const {
  9204. unsigned IntrinsicID =
  9205. cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  9206. SDLoc dl(Op);
  9207. switch (IntrinsicID) {
  9208. case Intrinsic::thread_pointer:
  9209. // Reads the thread pointer register, used for __builtin_thread_pointer.
  9210. if (Subtarget.isPPC64())
  9211. return DAG.getRegister(PPC::X13, MVT::i64);
  9212. return DAG.getRegister(PPC::R2, MVT::i32);
  9213. case Intrinsic::ppc_mma_disassemble_acc:
  9214. case Intrinsic::ppc_vsx_disassemble_pair: {
  9215. int NumVecs = 2;
  9216. SDValue WideVec = Op.getOperand(1);
  9217. if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
  9218. NumVecs = 4;
  9219. WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
  9220. }
  9221. SmallVector<SDValue, 4> RetOps;
  9222. for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
  9223. SDValue Extract = DAG.getNode(
  9224. PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
  9225. DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
  9226. : VecNo,
  9227. dl, getPointerTy(DAG.getDataLayout())));
  9228. RetOps.push_back(Extract);
  9229. }
  9230. return DAG.getMergeValues(RetOps, dl);
  9231. }
  9232. case Intrinsic::ppc_unpack_longdouble: {
  9233. auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  9234. assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
  9235. "Argument of long double unpack must be 0 or 1!");
  9236. return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
  9237. DAG.getConstant(!!(Idx->getSExtValue()), dl,
  9238. Idx->getValueType(0)));
  9239. }
  9240. case Intrinsic::ppc_compare_exp_lt:
  9241. case Intrinsic::ppc_compare_exp_gt:
  9242. case Intrinsic::ppc_compare_exp_eq:
  9243. case Intrinsic::ppc_compare_exp_uo: {
  9244. unsigned Pred;
  9245. switch (IntrinsicID) {
  9246. case Intrinsic::ppc_compare_exp_lt:
  9247. Pred = PPC::PRED_LT;
  9248. break;
  9249. case Intrinsic::ppc_compare_exp_gt:
  9250. Pred = PPC::PRED_GT;
  9251. break;
  9252. case Intrinsic::ppc_compare_exp_eq:
  9253. Pred = PPC::PRED_EQ;
  9254. break;
  9255. case Intrinsic::ppc_compare_exp_uo:
  9256. Pred = PPC::PRED_UN;
  9257. break;
  9258. }
  9259. return SDValue(
  9260. DAG.getMachineNode(
  9261. PPC::SELECT_CC_I4, dl, MVT::i32,
  9262. {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
  9263. Op.getOperand(1), Op.getOperand(2)),
  9264. 0),
  9265. DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
  9266. DAG.getTargetConstant(Pred, dl, MVT::i32)}),
  9267. 0);
  9268. }
  9269. case Intrinsic::ppc_test_data_class_d:
  9270. case Intrinsic::ppc_test_data_class_f: {
  9271. unsigned CmprOpc = PPC::XSTSTDCDP;
  9272. if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
  9273. CmprOpc = PPC::XSTSTDCSP;
  9274. return SDValue(
  9275. DAG.getMachineNode(
  9276. PPC::SELECT_CC_I4, dl, MVT::i32,
  9277. {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
  9278. Op.getOperand(1)),
  9279. 0),
  9280. DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
  9281. DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
  9282. 0);
  9283. }
  9284. case Intrinsic::ppc_convert_f128_to_ppcf128:
  9285. case Intrinsic::ppc_convert_ppcf128_to_f128: {
  9286. RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
  9287. ? RTLIB::CONVERT_PPCF128_F128
  9288. : RTLIB::CONVERT_F128_PPCF128;
  9289. MakeLibCallOptions CallOptions;
  9290. std::pair<SDValue, SDValue> Result =
  9291. makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
  9292. dl, SDValue());
  9293. return Result.first;
  9294. }
  9295. }
  9296. // If this is a lowered altivec predicate compare, CompareOpc is set to the
  9297. // opcode number of the comparison.
  9298. int CompareOpc;
  9299. bool isDot;
  9300. if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
  9301. return SDValue(); // Don't custom lower most intrinsics.
  9302. // If this is a non-dot comparison, make the VCMP node and we are done.
  9303. if (!isDot) {
  9304. SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
  9305. Op.getOperand(1), Op.getOperand(2),
  9306. DAG.getConstant(CompareOpc, dl, MVT::i32));
  9307. return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
  9308. }
  9309. // Create the PPCISD altivec 'dot' comparison node.
  9310. SDValue Ops[] = {
  9311. Op.getOperand(2), // LHS
  9312. Op.getOperand(3), // RHS
  9313. DAG.getConstant(CompareOpc, dl, MVT::i32)
  9314. };
  9315. EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
  9316. SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
  9317. // Now that we have the comparison, emit a copy from the CR to a GPR.
  9318. // This is flagged to the above dot comparison.
  9319. SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
  9320. DAG.getRegister(PPC::CR6, MVT::i32),
  9321. CompNode.getValue(1));
  9322. // Unpack the result based on how the target uses it.
  9323. unsigned BitNo; // Bit # of CR6.
  9324. bool InvertBit; // Invert result?
  9325. switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
  9326. default: // Can't happen, don't crash on invalid number though.
  9327. case 0: // Return the value of the EQ bit of CR6.
  9328. BitNo = 0; InvertBit = false;
  9329. break;
  9330. case 1: // Return the inverted value of the EQ bit of CR6.
  9331. BitNo = 0; InvertBit = true;
  9332. break;
  9333. case 2: // Return the value of the LT bit of CR6.
  9334. BitNo = 2; InvertBit = false;
  9335. break;
  9336. case 3: // Return the inverted value of the LT bit of CR6.
  9337. BitNo = 2; InvertBit = true;
  9338. break;
  9339. }
  9340. // Shift the bit into the low position.
  9341. Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
  9342. DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
  9343. // Isolate the bit.
  9344. Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
  9345. DAG.getConstant(1, dl, MVT::i32));
  9346. // If we are supposed to, toggle the bit.
  9347. if (InvertBit)
  9348. Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
  9349. DAG.getConstant(1, dl, MVT::i32));
  9350. return Flags;
  9351. }
  9352. SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
  9353. SelectionDAG &DAG) const {
  9354. // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
  9355. // the beginning of the argument list.
  9356. int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
  9357. SDLoc DL(Op);
  9358. switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
  9359. case Intrinsic::ppc_cfence: {
  9360. assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
  9361. assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
  9362. SDValue Val = Op.getOperand(ArgStart + 1);
  9363. EVT Ty = Val.getValueType();
  9364. if (Ty == MVT::i128) {
  9365. // FIXME: Testing one of two paired registers is sufficient to guarantee
  9366. // ordering?
  9367. Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
  9368. }
  9369. return SDValue(
  9370. DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
  9371. DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
  9372. Op.getOperand(0)),
  9373. 0);
  9374. }
  9375. default:
  9376. break;
  9377. }
  9378. return SDValue();
  9379. }
  9380. // Lower scalar BSWAP64 to xxbrd.
  9381. SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
  9382. SDLoc dl(Op);
  9383. if (!Subtarget.isPPC64())
  9384. return Op;
  9385. // MTVSRDD
  9386. Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
  9387. Op.getOperand(0));
  9388. // XXBRD
  9389. Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
  9390. // MFVSRD
  9391. int VectorIndex = 0;
  9392. if (Subtarget.isLittleEndian())
  9393. VectorIndex = 1;
  9394. Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
  9395. DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
  9396. return Op;
  9397. }
  9398. // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
  9399. // compared to a value that is atomically loaded (atomic loads zero-extend).
  9400. SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
  9401. SelectionDAG &DAG) const {
  9402. assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
  9403. "Expecting an atomic compare-and-swap here.");
  9404. SDLoc dl(Op);
  9405. auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
  9406. EVT MemVT = AtomicNode->getMemoryVT();
  9407. if (MemVT.getSizeInBits() >= 32)
  9408. return Op;
  9409. SDValue CmpOp = Op.getOperand(2);
  9410. // If this is already correctly zero-extended, leave it alone.
  9411. auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
  9412. if (DAG.MaskedValueIsZero(CmpOp, HighBits))
  9413. return Op;
  9414. // Clear the high bits of the compare operand.
  9415. unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
  9416. SDValue NewCmpOp =
  9417. DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
  9418. DAG.getConstant(MaskVal, dl, MVT::i32));
  9419. // Replace the existing compare operand with the properly zero-extended one.
  9420. SmallVector<SDValue, 4> Ops;
  9421. for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
  9422. Ops.push_back(AtomicNode->getOperand(i));
  9423. Ops[2] = NewCmpOp;
  9424. MachineMemOperand *MMO = AtomicNode->getMemOperand();
  9425. SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
  9426. auto NodeTy =
  9427. (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
  9428. return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
  9429. }
  9430. SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
  9431. SelectionDAG &DAG) const {
  9432. AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
  9433. EVT MemVT = N->getMemoryVT();
  9434. assert(MemVT.getSimpleVT() == MVT::i128 &&
  9435. "Expect quadword atomic operations");
  9436. SDLoc dl(N);
  9437. unsigned Opc = N->getOpcode();
  9438. switch (Opc) {
  9439. case ISD::ATOMIC_LOAD: {
  9440. // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
  9441. // lowered to ppc instructions by pattern matching instruction selector.
  9442. SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
  9443. SmallVector<SDValue, 4> Ops{
  9444. N->getOperand(0),
  9445. DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
  9446. for (int I = 1, E = N->getNumOperands(); I < E; ++I)
  9447. Ops.push_back(N->getOperand(I));
  9448. SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
  9449. Ops, MemVT, N->getMemOperand());
  9450. SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
  9451. SDValue ValHi =
  9452. DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
  9453. ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
  9454. DAG.getConstant(64, dl, MVT::i32));
  9455. SDValue Val =
  9456. DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
  9457. return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
  9458. {Val, LoadedVal.getValue(2)});
  9459. }
  9460. case ISD::ATOMIC_STORE: {
  9461. // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
  9462. // lowered to ppc instructions by pattern matching instruction selector.
  9463. SDVTList Tys = DAG.getVTList(MVT::Other);
  9464. SmallVector<SDValue, 4> Ops{
  9465. N->getOperand(0),
  9466. DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
  9467. SDValue Val = N->getOperand(2);
  9468. SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
  9469. SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
  9470. DAG.getConstant(64, dl, MVT::i32));
  9471. ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
  9472. Ops.push_back(ValLo);
  9473. Ops.push_back(ValHi);
  9474. Ops.push_back(N->getOperand(1));
  9475. return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
  9476. N->getMemOperand());
  9477. }
  9478. default:
  9479. llvm_unreachable("Unexpected atomic opcode");
  9480. }
  9481. }
  9482. SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
  9483. SelectionDAG &DAG) const {
  9484. SDLoc dl(Op);
  9485. // Create a stack slot that is 16-byte aligned.
  9486. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  9487. int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
  9488. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  9489. SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
  9490. // Store the input value into Value#0 of the stack slot.
  9491. SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
  9492. MachinePointerInfo());
  9493. // Load it out.
  9494. return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
  9495. }
  9496. SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
  9497. SelectionDAG &DAG) const {
  9498. assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
  9499. "Should only be called for ISD::INSERT_VECTOR_ELT");
  9500. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  9501. EVT VT = Op.getValueType();
  9502. SDLoc dl(Op);
  9503. SDValue V1 = Op.getOperand(0);
  9504. SDValue V2 = Op.getOperand(1);
  9505. if (VT == MVT::v2f64 && C)
  9506. return Op;
  9507. if (Subtarget.hasP9Vector()) {
  9508. // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
  9509. // because on P10, it allows this specific insert_vector_elt load pattern to
  9510. // utilize the refactored load and store infrastructure in order to exploit
  9511. // prefixed loads.
  9512. // On targets with inexpensive direct moves (Power9 and up), a
  9513. // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
  9514. // load since a single precision load will involve conversion to double
  9515. // precision on the load followed by another conversion to single precision.
  9516. if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
  9517. (isa<LoadSDNode>(V2))) {
  9518. SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
  9519. SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
  9520. SDValue InsVecElt =
  9521. DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
  9522. BitcastLoad, Op.getOperand(2));
  9523. return DAG.getBitcast(MVT::v4f32, InsVecElt);
  9524. }
  9525. }
  9526. if (Subtarget.isISA3_1()) {
  9527. if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
  9528. return SDValue();
  9529. // On P10, we have legal lowering for constant and variable indices for
  9530. // all vectors.
  9531. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
  9532. VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
  9533. return Op;
  9534. }
  9535. // Before P10, we have legal lowering for constant indices but not for
  9536. // variable ones.
  9537. if (!C)
  9538. return SDValue();
  9539. // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
  9540. if (VT == MVT::v8i16 || VT == MVT::v16i8) {
  9541. SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
  9542. unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
  9543. unsigned InsertAtElement = C->getZExtValue();
  9544. unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
  9545. if (Subtarget.isLittleEndian()) {
  9546. InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
  9547. }
  9548. return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
  9549. DAG.getConstant(InsertAtByte, dl, MVT::i32));
  9550. }
  9551. return Op;
  9552. }
  9553. SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
  9554. SelectionDAG &DAG) const {
  9555. SDLoc dl(Op);
  9556. LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
  9557. SDValue LoadChain = LN->getChain();
  9558. SDValue BasePtr = LN->getBasePtr();
  9559. EVT VT = Op.getValueType();
  9560. if (VT != MVT::v256i1 && VT != MVT::v512i1)
  9561. return Op;
  9562. // Type v256i1 is used for pairs and v512i1 is used for accumulators.
  9563. // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
  9564. // 2 or 4 vsx registers.
  9565. assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
  9566. "Type unsupported without MMA");
  9567. assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
  9568. "Type unsupported without paired vector support");
  9569. Align Alignment = LN->getAlign();
  9570. SmallVector<SDValue, 4> Loads;
  9571. SmallVector<SDValue, 4> LoadChains;
  9572. unsigned NumVecs = VT.getSizeInBits() / 128;
  9573. for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
  9574. SDValue Load =
  9575. DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
  9576. LN->getPointerInfo().getWithOffset(Idx * 16),
  9577. commonAlignment(Alignment, Idx * 16),
  9578. LN->getMemOperand()->getFlags(), LN->getAAInfo());
  9579. BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
  9580. DAG.getConstant(16, dl, BasePtr.getValueType()));
  9581. Loads.push_back(Load);
  9582. LoadChains.push_back(Load.getValue(1));
  9583. }
  9584. if (Subtarget.isLittleEndian()) {
  9585. std::reverse(Loads.begin(), Loads.end());
  9586. std::reverse(LoadChains.begin(), LoadChains.end());
  9587. }
  9588. SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
  9589. SDValue Value =
  9590. DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
  9591. dl, VT, Loads);
  9592. SDValue RetOps[] = {Value, TF};
  9593. return DAG.getMergeValues(RetOps, dl);
  9594. }
  9595. SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
  9596. SelectionDAG &DAG) const {
  9597. SDLoc dl(Op);
  9598. StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
  9599. SDValue StoreChain = SN->getChain();
  9600. SDValue BasePtr = SN->getBasePtr();
  9601. SDValue Value = SN->getValue();
  9602. EVT StoreVT = Value.getValueType();
  9603. if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
  9604. return Op;
  9605. // Type v256i1 is used for pairs and v512i1 is used for accumulators.
  9606. // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
  9607. // underlying registers individually.
  9608. assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
  9609. "Type unsupported without MMA");
  9610. assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
  9611. "Type unsupported without paired vector support");
  9612. Align Alignment = SN->getAlign();
  9613. SmallVector<SDValue, 4> Stores;
  9614. unsigned NumVecs = 2;
  9615. if (StoreVT == MVT::v512i1) {
  9616. Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
  9617. NumVecs = 4;
  9618. }
  9619. for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
  9620. unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
  9621. SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
  9622. DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
  9623. SDValue Store =
  9624. DAG.getStore(StoreChain, dl, Elt, BasePtr,
  9625. SN->getPointerInfo().getWithOffset(Idx * 16),
  9626. commonAlignment(Alignment, Idx * 16),
  9627. SN->getMemOperand()->getFlags(), SN->getAAInfo());
  9628. BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
  9629. DAG.getConstant(16, dl, BasePtr.getValueType()));
  9630. Stores.push_back(Store);
  9631. }
  9632. SDValue TF = DAG.getTokenFactor(dl, Stores);
  9633. return TF;
  9634. }
  9635. SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
  9636. SDLoc dl(Op);
  9637. if (Op.getValueType() == MVT::v4i32) {
  9638. SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
  9639. SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
  9640. // +16 as shift amt.
  9641. SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
  9642. SDValue RHSSwap = // = vrlw RHS, 16
  9643. BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
  9644. // Shrinkify inputs to v8i16.
  9645. LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
  9646. RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
  9647. RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
  9648. // Low parts multiplied together, generating 32-bit results (we ignore the
  9649. // top parts).
  9650. SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
  9651. LHS, RHS, DAG, dl, MVT::v4i32);
  9652. SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
  9653. LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
  9654. // Shift the high parts up 16 bits.
  9655. HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
  9656. Neg16, DAG, dl);
  9657. return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
  9658. } else if (Op.getValueType() == MVT::v16i8) {
  9659. SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
  9660. bool isLittleEndian = Subtarget.isLittleEndian();
  9661. // Multiply the even 8-bit parts, producing 16-bit sums.
  9662. SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
  9663. LHS, RHS, DAG, dl, MVT::v8i16);
  9664. EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
  9665. // Multiply the odd 8-bit parts, producing 16-bit sums.
  9666. SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
  9667. LHS, RHS, DAG, dl, MVT::v8i16);
  9668. OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
  9669. // Merge the results together. Because vmuleub and vmuloub are
  9670. // instructions with a big-endian bias, we must reverse the
  9671. // element numbering and reverse the meaning of "odd" and "even"
  9672. // when generating little endian code.
  9673. int Ops[16];
  9674. for (unsigned i = 0; i != 8; ++i) {
  9675. if (isLittleEndian) {
  9676. Ops[i*2 ] = 2*i;
  9677. Ops[i*2+1] = 2*i+16;
  9678. } else {
  9679. Ops[i*2 ] = 2*i+1;
  9680. Ops[i*2+1] = 2*i+1+16;
  9681. }
  9682. }
  9683. if (isLittleEndian)
  9684. return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
  9685. else
  9686. return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
  9687. } else {
  9688. llvm_unreachable("Unknown mul to lower!");
  9689. }
  9690. }
  9691. SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
  9692. bool IsStrict = Op->isStrictFPOpcode();
  9693. if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
  9694. !Subtarget.hasP9Vector())
  9695. return SDValue();
  9696. return Op;
  9697. }
  9698. // Custom lowering for fpext vf32 to v2f64
  9699. SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
  9700. assert(Op.getOpcode() == ISD::FP_EXTEND &&
  9701. "Should only be called for ISD::FP_EXTEND");
  9702. // FIXME: handle extends from half precision float vectors on P9.
  9703. // We only want to custom lower an extend from v2f32 to v2f64.
  9704. if (Op.getValueType() != MVT::v2f64 ||
  9705. Op.getOperand(0).getValueType() != MVT::v2f32)
  9706. return SDValue();
  9707. SDLoc dl(Op);
  9708. SDValue Op0 = Op.getOperand(0);
  9709. switch (Op0.getOpcode()) {
  9710. default:
  9711. return SDValue();
  9712. case ISD::EXTRACT_SUBVECTOR: {
  9713. assert(Op0.getNumOperands() == 2 &&
  9714. isa<ConstantSDNode>(Op0->getOperand(1)) &&
  9715. "Node should have 2 operands with second one being a constant!");
  9716. if (Op0.getOperand(0).getValueType() != MVT::v4f32)
  9717. return SDValue();
  9718. // Custom lower is only done for high or low doubleword.
  9719. int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
  9720. if (Idx % 2 != 0)
  9721. return SDValue();
  9722. // Since input is v4f32, at this point Idx is either 0 or 2.
  9723. // Shift to get the doubleword position we want.
  9724. int DWord = Idx >> 1;
  9725. // High and low word positions are different on little endian.
  9726. if (Subtarget.isLittleEndian())
  9727. DWord ^= 0x1;
  9728. return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
  9729. Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
  9730. }
  9731. case ISD::FADD:
  9732. case ISD::FMUL:
  9733. case ISD::FSUB: {
  9734. SDValue NewLoad[2];
  9735. for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
  9736. // Ensure both input are loads.
  9737. SDValue LdOp = Op0.getOperand(i);
  9738. if (LdOp.getOpcode() != ISD::LOAD)
  9739. return SDValue();
  9740. // Generate new load node.
  9741. LoadSDNode *LD = cast<LoadSDNode>(LdOp);
  9742. SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
  9743. NewLoad[i] = DAG.getMemIntrinsicNode(
  9744. PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
  9745. LD->getMemoryVT(), LD->getMemOperand());
  9746. }
  9747. SDValue NewOp =
  9748. DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
  9749. NewLoad[1], Op0.getNode()->getFlags());
  9750. return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
  9751. DAG.getConstant(0, dl, MVT::i32));
  9752. }
  9753. case ISD::LOAD: {
  9754. LoadSDNode *LD = cast<LoadSDNode>(Op0);
  9755. SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
  9756. SDValue NewLd = DAG.getMemIntrinsicNode(
  9757. PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
  9758. LD->getMemoryVT(), LD->getMemOperand());
  9759. return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
  9760. DAG.getConstant(0, dl, MVT::i32));
  9761. }
  9762. }
  9763. llvm_unreachable("ERROR:Should return for all cases within swtich.");
  9764. }
  9765. /// LowerOperation - Provide custom lowering hooks for some operations.
  9766. ///
  9767. SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  9768. switch (Op.getOpcode()) {
  9769. default: llvm_unreachable("Wasn't expecting to be able to lower this!");
  9770. case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
  9771. case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
  9772. case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
  9773. case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
  9774. case ISD::JumpTable: return LowerJumpTable(Op, DAG);
  9775. case ISD::STRICT_FSETCC:
  9776. case ISD::STRICT_FSETCCS:
  9777. case ISD::SETCC: return LowerSETCC(Op, DAG);
  9778. case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
  9779. case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
  9780. case ISD::INLINEASM:
  9781. case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG);
  9782. // Variable argument lowering.
  9783. case ISD::VASTART: return LowerVASTART(Op, DAG);
  9784. case ISD::VAARG: return LowerVAARG(Op, DAG);
  9785. case ISD::VACOPY: return LowerVACOPY(Op, DAG);
  9786. case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG);
  9787. case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
  9788. case ISD::GET_DYNAMIC_AREA_OFFSET:
  9789. return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
  9790. // Exception handling lowering.
  9791. case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG);
  9792. case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
  9793. case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
  9794. case ISD::LOAD: return LowerLOAD(Op, DAG);
  9795. case ISD::STORE: return LowerSTORE(Op, DAG);
  9796. case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
  9797. case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
  9798. case ISD::STRICT_FP_TO_UINT:
  9799. case ISD::STRICT_FP_TO_SINT:
  9800. case ISD::FP_TO_UINT:
  9801. case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
  9802. case ISD::STRICT_UINT_TO_FP:
  9803. case ISD::STRICT_SINT_TO_FP:
  9804. case ISD::UINT_TO_FP:
  9805. case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
  9806. case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
  9807. // Lower 64-bit shifts.
  9808. case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
  9809. case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
  9810. case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
  9811. case ISD::FSHL: return LowerFunnelShift(Op, DAG);
  9812. case ISD::FSHR: return LowerFunnelShift(Op, DAG);
  9813. // Vector-related lowering.
  9814. case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
  9815. case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
  9816. case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
  9817. case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
  9818. case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
  9819. case ISD::MUL: return LowerMUL(Op, DAG);
  9820. case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
  9821. case ISD::STRICT_FP_ROUND:
  9822. case ISD::FP_ROUND:
  9823. return LowerFP_ROUND(Op, DAG);
  9824. case ISD::ROTL: return LowerROTL(Op, DAG);
  9825. // For counter-based loop handling.
  9826. case ISD::INTRINSIC_W_CHAIN: return SDValue();
  9827. case ISD::BITCAST: return LowerBITCAST(Op, DAG);
  9828. // Frame & Return address.
  9829. case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
  9830. case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
  9831. case ISD::INTRINSIC_VOID:
  9832. return LowerINTRINSIC_VOID(Op, DAG);
  9833. case ISD::BSWAP:
  9834. return LowerBSWAP(Op, DAG);
  9835. case ISD::ATOMIC_CMP_SWAP:
  9836. return LowerATOMIC_CMP_SWAP(Op, DAG);
  9837. case ISD::ATOMIC_STORE:
  9838. return LowerATOMIC_LOAD_STORE(Op, DAG);
  9839. }
  9840. }
  9841. void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
  9842. SmallVectorImpl<SDValue>&Results,
  9843. SelectionDAG &DAG) const {
  9844. SDLoc dl(N);
  9845. switch (N->getOpcode()) {
  9846. default:
  9847. llvm_unreachable("Do not know how to custom type legalize this operation!");
  9848. case ISD::ATOMIC_LOAD: {
  9849. SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
  9850. Results.push_back(Res);
  9851. Results.push_back(Res.getValue(1));
  9852. break;
  9853. }
  9854. case ISD::READCYCLECOUNTER: {
  9855. SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
  9856. SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
  9857. Results.push_back(
  9858. DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
  9859. Results.push_back(RTB.getValue(2));
  9860. break;
  9861. }
  9862. case ISD::INTRINSIC_W_CHAIN: {
  9863. if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
  9864. Intrinsic::loop_decrement)
  9865. break;
  9866. assert(N->getValueType(0) == MVT::i1 &&
  9867. "Unexpected result type for CTR decrement intrinsic");
  9868. EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  9869. N->getValueType(0));
  9870. SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
  9871. SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
  9872. N->getOperand(1));
  9873. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
  9874. Results.push_back(NewInt.getValue(1));
  9875. break;
  9876. }
  9877. case ISD::INTRINSIC_WO_CHAIN: {
  9878. switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
  9879. case Intrinsic::ppc_pack_longdouble:
  9880. Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
  9881. N->getOperand(2), N->getOperand(1)));
  9882. break;
  9883. case Intrinsic::ppc_convert_f128_to_ppcf128:
  9884. Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
  9885. break;
  9886. }
  9887. break;
  9888. }
  9889. case ISD::VAARG: {
  9890. if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
  9891. return;
  9892. EVT VT = N->getValueType(0);
  9893. if (VT == MVT::i64) {
  9894. SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
  9895. Results.push_back(NewNode);
  9896. Results.push_back(NewNode.getValue(1));
  9897. }
  9898. return;
  9899. }
  9900. case ISD::STRICT_FP_TO_SINT:
  9901. case ISD::STRICT_FP_TO_UINT:
  9902. case ISD::FP_TO_SINT:
  9903. case ISD::FP_TO_UINT: {
  9904. // LowerFP_TO_INT() can only handle f32 and f64.
  9905. if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
  9906. MVT::ppcf128)
  9907. return;
  9908. SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
  9909. Results.push_back(LoweredValue);
  9910. if (N->isStrictFPOpcode())
  9911. Results.push_back(LoweredValue.getValue(1));
  9912. return;
  9913. }
  9914. case ISD::TRUNCATE: {
  9915. if (!N->getValueType(0).isVector())
  9916. return;
  9917. SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
  9918. if (Lowered)
  9919. Results.push_back(Lowered);
  9920. return;
  9921. }
  9922. case ISD::FSHL:
  9923. case ISD::FSHR:
  9924. // Don't handle funnel shifts here.
  9925. return;
  9926. case ISD::BITCAST:
  9927. // Don't handle bitcast here.
  9928. return;
  9929. case ISD::FP_EXTEND:
  9930. SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
  9931. if (Lowered)
  9932. Results.push_back(Lowered);
  9933. return;
  9934. }
  9935. }
  9936. //===----------------------------------------------------------------------===//
  9937. // Other Lowering Code
  9938. //===----------------------------------------------------------------------===//
  9939. static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
  9940. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  9941. Function *Func = Intrinsic::getDeclaration(M, Id);
  9942. return Builder.CreateCall(Func, {});
  9943. }
  9944. // The mappings for emitLeading/TrailingFence is taken from
  9945. // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
  9946. Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
  9947. Instruction *Inst,
  9948. AtomicOrdering Ord) const {
  9949. if (Ord == AtomicOrdering::SequentiallyConsistent)
  9950. return callIntrinsic(Builder, Intrinsic::ppc_sync);
  9951. if (isReleaseOrStronger(Ord))
  9952. return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
  9953. return nullptr;
  9954. }
  9955. Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
  9956. Instruction *Inst,
  9957. AtomicOrdering Ord) const {
  9958. if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
  9959. // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
  9960. // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
  9961. // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
  9962. if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
  9963. return Builder.CreateCall(
  9964. Intrinsic::getDeclaration(
  9965. Builder.GetInsertBlock()->getParent()->getParent(),
  9966. Intrinsic::ppc_cfence, {Inst->getType()}),
  9967. {Inst});
  9968. // FIXME: Can use isync for rmw operation.
  9969. return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
  9970. }
  9971. return nullptr;
  9972. }
  9973. MachineBasicBlock *
  9974. PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
  9975. unsigned AtomicSize,
  9976. unsigned BinOpcode,
  9977. unsigned CmpOpcode,
  9978. unsigned CmpPred) const {
  9979. // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
  9980. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  9981. auto LoadMnemonic = PPC::LDARX;
  9982. auto StoreMnemonic = PPC::STDCX;
  9983. switch (AtomicSize) {
  9984. default:
  9985. llvm_unreachable("Unexpected size of atomic entity");
  9986. case 1:
  9987. LoadMnemonic = PPC::LBARX;
  9988. StoreMnemonic = PPC::STBCX;
  9989. assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
  9990. break;
  9991. case 2:
  9992. LoadMnemonic = PPC::LHARX;
  9993. StoreMnemonic = PPC::STHCX;
  9994. assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
  9995. break;
  9996. case 4:
  9997. LoadMnemonic = PPC::LWARX;
  9998. StoreMnemonic = PPC::STWCX;
  9999. break;
  10000. case 8:
  10001. LoadMnemonic = PPC::LDARX;
  10002. StoreMnemonic = PPC::STDCX;
  10003. break;
  10004. }
  10005. const BasicBlock *LLVM_BB = BB->getBasicBlock();
  10006. MachineFunction *F = BB->getParent();
  10007. MachineFunction::iterator It = ++BB->getIterator();
  10008. Register dest = MI.getOperand(0).getReg();
  10009. Register ptrA = MI.getOperand(1).getReg();
  10010. Register ptrB = MI.getOperand(2).getReg();
  10011. Register incr = MI.getOperand(3).getReg();
  10012. DebugLoc dl = MI.getDebugLoc();
  10013. MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10014. MachineBasicBlock *loop2MBB =
  10015. CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
  10016. MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10017. F->insert(It, loopMBB);
  10018. if (CmpOpcode)
  10019. F->insert(It, loop2MBB);
  10020. F->insert(It, exitMBB);
  10021. exitMBB->splice(exitMBB->begin(), BB,
  10022. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  10023. exitMBB->transferSuccessorsAndUpdatePHIs(BB);
  10024. MachineRegisterInfo &RegInfo = F->getRegInfo();
  10025. Register TmpReg = (!BinOpcode) ? incr :
  10026. RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
  10027. : &PPC::GPRCRegClass);
  10028. // thisMBB:
  10029. // ...
  10030. // fallthrough --> loopMBB
  10031. BB->addSuccessor(loopMBB);
  10032. // loopMBB:
  10033. // l[wd]arx dest, ptr
  10034. // add r0, dest, incr
  10035. // st[wd]cx. r0, ptr
  10036. // bne- loopMBB
  10037. // fallthrough --> exitMBB
  10038. // For max/min...
  10039. // loopMBB:
  10040. // l[wd]arx dest, ptr
  10041. // cmpl?[wd] incr, dest
  10042. // bgt exitMBB
  10043. // loop2MBB:
  10044. // st[wd]cx. dest, ptr
  10045. // bne- loopMBB
  10046. // fallthrough --> exitMBB
  10047. BB = loopMBB;
  10048. BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
  10049. .addReg(ptrA).addReg(ptrB);
  10050. if (BinOpcode)
  10051. BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
  10052. if (CmpOpcode) {
  10053. // Signed comparisons of byte or halfword values must be sign-extended.
  10054. if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
  10055. Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
  10056. BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
  10057. ExtReg).addReg(dest);
  10058. BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
  10059. .addReg(incr).addReg(ExtReg);
  10060. } else
  10061. BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
  10062. .addReg(incr).addReg(dest);
  10063. BuildMI(BB, dl, TII->get(PPC::BCC))
  10064. .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
  10065. BB->addSuccessor(loop2MBB);
  10066. BB->addSuccessor(exitMBB);
  10067. BB = loop2MBB;
  10068. }
  10069. BuildMI(BB, dl, TII->get(StoreMnemonic))
  10070. .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
  10071. BuildMI(BB, dl, TII->get(PPC::BCC))
  10072. .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
  10073. BB->addSuccessor(loopMBB);
  10074. BB->addSuccessor(exitMBB);
  10075. // exitMBB:
  10076. // ...
  10077. BB = exitMBB;
  10078. return BB;
  10079. }
  10080. static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
  10081. switch(MI.getOpcode()) {
  10082. default:
  10083. return false;
  10084. case PPC::COPY:
  10085. return TII->isSignExtended(MI);
  10086. case PPC::LHA:
  10087. case PPC::LHA8:
  10088. case PPC::LHAU:
  10089. case PPC::LHAU8:
  10090. case PPC::LHAUX:
  10091. case PPC::LHAUX8:
  10092. case PPC::LHAX:
  10093. case PPC::LHAX8:
  10094. case PPC::LWA:
  10095. case PPC::LWAUX:
  10096. case PPC::LWAX:
  10097. case PPC::LWAX_32:
  10098. case PPC::LWA_32:
  10099. case PPC::PLHA:
  10100. case PPC::PLHA8:
  10101. case PPC::PLHA8pc:
  10102. case PPC::PLHApc:
  10103. case PPC::PLWA:
  10104. case PPC::PLWA8:
  10105. case PPC::PLWA8pc:
  10106. case PPC::PLWApc:
  10107. case PPC::EXTSB:
  10108. case PPC::EXTSB8:
  10109. case PPC::EXTSB8_32_64:
  10110. case PPC::EXTSB8_rec:
  10111. case PPC::EXTSB_rec:
  10112. case PPC::EXTSH:
  10113. case PPC::EXTSH8:
  10114. case PPC::EXTSH8_32_64:
  10115. case PPC::EXTSH8_rec:
  10116. case PPC::EXTSH_rec:
  10117. case PPC::EXTSW:
  10118. case PPC::EXTSWSLI:
  10119. case PPC::EXTSWSLI_32_64:
  10120. case PPC::EXTSWSLI_32_64_rec:
  10121. case PPC::EXTSWSLI_rec:
  10122. case PPC::EXTSW_32:
  10123. case PPC::EXTSW_32_64:
  10124. case PPC::EXTSW_32_64_rec:
  10125. case PPC::EXTSW_rec:
  10126. case PPC::SRAW:
  10127. case PPC::SRAWI:
  10128. case PPC::SRAWI_rec:
  10129. case PPC::SRAW_rec:
  10130. return true;
  10131. }
  10132. return false;
  10133. }
  10134. MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
  10135. MachineInstr &MI, MachineBasicBlock *BB,
  10136. bool is8bit, // operation
  10137. unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
  10138. // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
  10139. const PPCInstrInfo *TII = Subtarget.getInstrInfo();
  10140. // If this is a signed comparison and the value being compared is not known
  10141. // to be sign extended, sign extend it here.
  10142. DebugLoc dl = MI.getDebugLoc();
  10143. MachineFunction *F = BB->getParent();
  10144. MachineRegisterInfo &RegInfo = F->getRegInfo();
  10145. Register incr = MI.getOperand(3).getReg();
  10146. bool IsSignExtended = Register::isVirtualRegister(incr) &&
  10147. isSignExtended(*RegInfo.getVRegDef(incr), TII);
  10148. if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
  10149. Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
  10150. BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
  10151. .addReg(MI.getOperand(3).getReg());
  10152. MI.getOperand(3).setReg(ValueReg);
  10153. }
  10154. // If we support part-word atomic mnemonics, just use them
  10155. if (Subtarget.hasPartwordAtomics())
  10156. return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
  10157. CmpPred);
  10158. // In 64 bit mode we have to use 64 bits for addresses, even though the
  10159. // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
  10160. // registers without caring whether they're 32 or 64, but here we're
  10161. // doing actual arithmetic on the addresses.
  10162. bool is64bit = Subtarget.isPPC64();
  10163. bool isLittleEndian = Subtarget.isLittleEndian();
  10164. unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
  10165. const BasicBlock *LLVM_BB = BB->getBasicBlock();
  10166. MachineFunction::iterator It = ++BB->getIterator();
  10167. Register dest = MI.getOperand(0).getReg();
  10168. Register ptrA = MI.getOperand(1).getReg();
  10169. Register ptrB = MI.getOperand(2).getReg();
  10170. MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10171. MachineBasicBlock *loop2MBB =
  10172. CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
  10173. MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10174. F->insert(It, loopMBB);
  10175. if (CmpOpcode)
  10176. F->insert(It, loop2MBB);
  10177. F->insert(It, exitMBB);
  10178. exitMBB->splice(exitMBB->begin(), BB,
  10179. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  10180. exitMBB->transferSuccessorsAndUpdatePHIs(BB);
  10181. const TargetRegisterClass *RC =
  10182. is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  10183. const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
  10184. Register PtrReg = RegInfo.createVirtualRegister(RC);
  10185. Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
  10186. Register ShiftReg =
  10187. isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
  10188. Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
  10189. Register MaskReg = RegInfo.createVirtualRegister(GPRC);
  10190. Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
  10191. Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
  10192. Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
  10193. Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
  10194. Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
  10195. Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
  10196. Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
  10197. Register Ptr1Reg;
  10198. Register TmpReg =
  10199. (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
  10200. // thisMBB:
  10201. // ...
  10202. // fallthrough --> loopMBB
  10203. BB->addSuccessor(loopMBB);
  10204. // The 4-byte load must be aligned, while a char or short may be
  10205. // anywhere in the word. Hence all this nasty bookkeeping code.
  10206. // add ptr1, ptrA, ptrB [copy if ptrA==0]
  10207. // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
  10208. // xori shift, shift1, 24 [16]
  10209. // rlwinm ptr, ptr1, 0, 0, 29
  10210. // slw incr2, incr, shift
  10211. // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
  10212. // slw mask, mask2, shift
  10213. // loopMBB:
  10214. // lwarx tmpDest, ptr
  10215. // add tmp, tmpDest, incr2
  10216. // andc tmp2, tmpDest, mask
  10217. // and tmp3, tmp, mask
  10218. // or tmp4, tmp3, tmp2
  10219. // stwcx. tmp4, ptr
  10220. // bne- loopMBB
  10221. // fallthrough --> exitMBB
  10222. // srw SrwDest, tmpDest, shift
  10223. // rlwinm SrwDest, SrwDest, 0, 24 [16], 31
  10224. if (ptrA != ZeroReg) {
  10225. Ptr1Reg = RegInfo.createVirtualRegister(RC);
  10226. BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
  10227. .addReg(ptrA)
  10228. .addReg(ptrB);
  10229. } else {
  10230. Ptr1Reg = ptrB;
  10231. }
  10232. // We need use 32-bit subregister to avoid mismatch register class in 64-bit
  10233. // mode.
  10234. BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
  10235. .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
  10236. .addImm(3)
  10237. .addImm(27)
  10238. .addImm(is8bit ? 28 : 27);
  10239. if (!isLittleEndian)
  10240. BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
  10241. .addReg(Shift1Reg)
  10242. .addImm(is8bit ? 24 : 16);
  10243. if (is64bit)
  10244. BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
  10245. .addReg(Ptr1Reg)
  10246. .addImm(0)
  10247. .addImm(61);
  10248. else
  10249. BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
  10250. .addReg(Ptr1Reg)
  10251. .addImm(0)
  10252. .addImm(0)
  10253. .addImm(29);
  10254. BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
  10255. if (is8bit)
  10256. BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
  10257. else {
  10258. BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
  10259. BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
  10260. .addReg(Mask3Reg)
  10261. .addImm(65535);
  10262. }
  10263. BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
  10264. .addReg(Mask2Reg)
  10265. .addReg(ShiftReg);
  10266. BB = loopMBB;
  10267. BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
  10268. .addReg(ZeroReg)
  10269. .addReg(PtrReg);
  10270. if (BinOpcode)
  10271. BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
  10272. .addReg(Incr2Reg)
  10273. .addReg(TmpDestReg);
  10274. BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
  10275. .addReg(TmpDestReg)
  10276. .addReg(MaskReg);
  10277. BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
  10278. if (CmpOpcode) {
  10279. // For unsigned comparisons, we can directly compare the shifted values.
  10280. // For signed comparisons we shift and sign extend.
  10281. Register SReg = RegInfo.createVirtualRegister(GPRC);
  10282. BuildMI(BB, dl, TII->get(PPC::AND), SReg)
  10283. .addReg(TmpDestReg)
  10284. .addReg(MaskReg);
  10285. unsigned ValueReg = SReg;
  10286. unsigned CmpReg = Incr2Reg;
  10287. if (CmpOpcode == PPC::CMPW) {
  10288. ValueReg = RegInfo.createVirtualRegister(GPRC);
  10289. BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
  10290. .addReg(SReg)
  10291. .addReg(ShiftReg);
  10292. Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
  10293. BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
  10294. .addReg(ValueReg);
  10295. ValueReg = ValueSReg;
  10296. CmpReg = incr;
  10297. }
  10298. BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
  10299. .addReg(CmpReg)
  10300. .addReg(ValueReg);
  10301. BuildMI(BB, dl, TII->get(PPC::BCC))
  10302. .addImm(CmpPred)
  10303. .addReg(PPC::CR0)
  10304. .addMBB(exitMBB);
  10305. BB->addSuccessor(loop2MBB);
  10306. BB->addSuccessor(exitMBB);
  10307. BB = loop2MBB;
  10308. }
  10309. BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
  10310. BuildMI(BB, dl, TII->get(PPC::STWCX))
  10311. .addReg(Tmp4Reg)
  10312. .addReg(ZeroReg)
  10313. .addReg(PtrReg);
  10314. BuildMI(BB, dl, TII->get(PPC::BCC))
  10315. .addImm(PPC::PRED_NE)
  10316. .addReg(PPC::CR0)
  10317. .addMBB(loopMBB);
  10318. BB->addSuccessor(loopMBB);
  10319. BB->addSuccessor(exitMBB);
  10320. // exitMBB:
  10321. // ...
  10322. BB = exitMBB;
  10323. // Since the shift amount is not a constant, we need to clear
  10324. // the upper bits with a separate RLWINM.
  10325. BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
  10326. .addReg(SrwDestReg)
  10327. .addImm(0)
  10328. .addImm(is8bit ? 24 : 16)
  10329. .addImm(31);
  10330. BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
  10331. .addReg(TmpDestReg)
  10332. .addReg(ShiftReg);
  10333. return BB;
  10334. }
  10335. llvm::MachineBasicBlock *
  10336. PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
  10337. MachineBasicBlock *MBB) const {
  10338. DebugLoc DL = MI.getDebugLoc();
  10339. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10340. const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
  10341. MachineFunction *MF = MBB->getParent();
  10342. MachineRegisterInfo &MRI = MF->getRegInfo();
  10343. const BasicBlock *BB = MBB->getBasicBlock();
  10344. MachineFunction::iterator I = ++MBB->getIterator();
  10345. Register DstReg = MI.getOperand(0).getReg();
  10346. const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
  10347. assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
  10348. Register mainDstReg = MRI.createVirtualRegister(RC);
  10349. Register restoreDstReg = MRI.createVirtualRegister(RC);
  10350. MVT PVT = getPointerTy(MF->getDataLayout());
  10351. assert((PVT == MVT::i64 || PVT == MVT::i32) &&
  10352. "Invalid Pointer Size!");
  10353. // For v = setjmp(buf), we generate
  10354. //
  10355. // thisMBB:
  10356. // SjLjSetup mainMBB
  10357. // bl mainMBB
  10358. // v_restore = 1
  10359. // b sinkMBB
  10360. //
  10361. // mainMBB:
  10362. // buf[LabelOffset] = LR
  10363. // v_main = 0
  10364. //
  10365. // sinkMBB:
  10366. // v = phi(main, restore)
  10367. //
  10368. MachineBasicBlock *thisMBB = MBB;
  10369. MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
  10370. MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
  10371. MF->insert(I, mainMBB);
  10372. MF->insert(I, sinkMBB);
  10373. MachineInstrBuilder MIB;
  10374. // Transfer the remainder of BB and its successor edges to sinkMBB.
  10375. sinkMBB->splice(sinkMBB->begin(), MBB,
  10376. std::next(MachineBasicBlock::iterator(MI)), MBB->end());
  10377. sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
  10378. // Note that the structure of the jmp_buf used here is not compatible
  10379. // with that used by libc, and is not designed to be. Specifically, it
  10380. // stores only those 'reserved' registers that LLVM does not otherwise
  10381. // understand how to spill. Also, by convention, by the time this
  10382. // intrinsic is called, Clang has already stored the frame address in the
  10383. // first slot of the buffer and stack address in the third. Following the
  10384. // X86 target code, we'll store the jump address in the second slot. We also
  10385. // need to save the TOC pointer (R2) to handle jumps between shared
  10386. // libraries, and that will be stored in the fourth slot. The thread
  10387. // identifier (R13) is not affected.
  10388. // thisMBB:
  10389. const int64_t LabelOffset = 1 * PVT.getStoreSize();
  10390. const int64_t TOCOffset = 3 * PVT.getStoreSize();
  10391. const int64_t BPOffset = 4 * PVT.getStoreSize();
  10392. // Prepare IP either in reg.
  10393. const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
  10394. Register LabelReg = MRI.createVirtualRegister(PtrRC);
  10395. Register BufReg = MI.getOperand(1).getReg();
  10396. if (Subtarget.is64BitELFABI()) {
  10397. setUsesTOCBasePtr(*MBB->getParent());
  10398. MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
  10399. .addReg(PPC::X2)
  10400. .addImm(TOCOffset)
  10401. .addReg(BufReg)
  10402. .cloneMemRefs(MI);
  10403. }
  10404. // Naked functions never have a base pointer, and so we use r1. For all
  10405. // other functions, this decision must be delayed until during PEI.
  10406. unsigned BaseReg;
  10407. if (MF->getFunction().hasFnAttribute(Attribute::Naked))
  10408. BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
  10409. else
  10410. BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
  10411. MIB = BuildMI(*thisMBB, MI, DL,
  10412. TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
  10413. .addReg(BaseReg)
  10414. .addImm(BPOffset)
  10415. .addReg(BufReg)
  10416. .cloneMemRefs(MI);
  10417. // Setup
  10418. MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
  10419. MIB.addRegMask(TRI->getNoPreservedMask());
  10420. BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
  10421. MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
  10422. .addMBB(mainMBB);
  10423. MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
  10424. thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
  10425. thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
  10426. // mainMBB:
  10427. // mainDstReg = 0
  10428. MIB =
  10429. BuildMI(mainMBB, DL,
  10430. TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
  10431. // Store IP
  10432. if (Subtarget.isPPC64()) {
  10433. MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
  10434. .addReg(LabelReg)
  10435. .addImm(LabelOffset)
  10436. .addReg(BufReg);
  10437. } else {
  10438. MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
  10439. .addReg(LabelReg)
  10440. .addImm(LabelOffset)
  10441. .addReg(BufReg);
  10442. }
  10443. MIB.cloneMemRefs(MI);
  10444. BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
  10445. mainMBB->addSuccessor(sinkMBB);
  10446. // sinkMBB:
  10447. BuildMI(*sinkMBB, sinkMBB->begin(), DL,
  10448. TII->get(PPC::PHI), DstReg)
  10449. .addReg(mainDstReg).addMBB(mainMBB)
  10450. .addReg(restoreDstReg).addMBB(thisMBB);
  10451. MI.eraseFromParent();
  10452. return sinkMBB;
  10453. }
  10454. MachineBasicBlock *
  10455. PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
  10456. MachineBasicBlock *MBB) const {
  10457. DebugLoc DL = MI.getDebugLoc();
  10458. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10459. MachineFunction *MF = MBB->getParent();
  10460. MachineRegisterInfo &MRI = MF->getRegInfo();
  10461. MVT PVT = getPointerTy(MF->getDataLayout());
  10462. assert((PVT == MVT::i64 || PVT == MVT::i32) &&
  10463. "Invalid Pointer Size!");
  10464. const TargetRegisterClass *RC =
  10465. (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  10466. Register Tmp = MRI.createVirtualRegister(RC);
  10467. // Since FP is only updated here but NOT referenced, it's treated as GPR.
  10468. unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
  10469. unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
  10470. unsigned BP =
  10471. (PVT == MVT::i64)
  10472. ? PPC::X30
  10473. : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
  10474. : PPC::R30);
  10475. MachineInstrBuilder MIB;
  10476. const int64_t LabelOffset = 1 * PVT.getStoreSize();
  10477. const int64_t SPOffset = 2 * PVT.getStoreSize();
  10478. const int64_t TOCOffset = 3 * PVT.getStoreSize();
  10479. const int64_t BPOffset = 4 * PVT.getStoreSize();
  10480. Register BufReg = MI.getOperand(0).getReg();
  10481. // Reload FP (the jumped-to function may not have had a
  10482. // frame pointer, and if so, then its r31 will be restored
  10483. // as necessary).
  10484. if (PVT == MVT::i64) {
  10485. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
  10486. .addImm(0)
  10487. .addReg(BufReg);
  10488. } else {
  10489. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
  10490. .addImm(0)
  10491. .addReg(BufReg);
  10492. }
  10493. MIB.cloneMemRefs(MI);
  10494. // Reload IP
  10495. if (PVT == MVT::i64) {
  10496. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
  10497. .addImm(LabelOffset)
  10498. .addReg(BufReg);
  10499. } else {
  10500. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
  10501. .addImm(LabelOffset)
  10502. .addReg(BufReg);
  10503. }
  10504. MIB.cloneMemRefs(MI);
  10505. // Reload SP
  10506. if (PVT == MVT::i64) {
  10507. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
  10508. .addImm(SPOffset)
  10509. .addReg(BufReg);
  10510. } else {
  10511. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
  10512. .addImm(SPOffset)
  10513. .addReg(BufReg);
  10514. }
  10515. MIB.cloneMemRefs(MI);
  10516. // Reload BP
  10517. if (PVT == MVT::i64) {
  10518. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
  10519. .addImm(BPOffset)
  10520. .addReg(BufReg);
  10521. } else {
  10522. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
  10523. .addImm(BPOffset)
  10524. .addReg(BufReg);
  10525. }
  10526. MIB.cloneMemRefs(MI);
  10527. // Reload TOC
  10528. if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
  10529. setUsesTOCBasePtr(*MBB->getParent());
  10530. MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
  10531. .addImm(TOCOffset)
  10532. .addReg(BufReg)
  10533. .cloneMemRefs(MI);
  10534. }
  10535. // Jump
  10536. BuildMI(*MBB, MI, DL,
  10537. TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
  10538. BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
  10539. MI.eraseFromParent();
  10540. return MBB;
  10541. }
  10542. bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
  10543. // If the function specifically requests inline stack probes, emit them.
  10544. if (MF.getFunction().hasFnAttribute("probe-stack"))
  10545. return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
  10546. "inline-asm";
  10547. return false;
  10548. }
  10549. unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
  10550. const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
  10551. unsigned StackAlign = TFI->getStackAlignment();
  10552. assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
  10553. "Unexpected stack alignment");
  10554. // The default stack probe size is 4096 if the function has no
  10555. // stack-probe-size attribute.
  10556. unsigned StackProbeSize = 4096;
  10557. const Function &Fn = MF.getFunction();
  10558. if (Fn.hasFnAttribute("stack-probe-size"))
  10559. Fn.getFnAttribute("stack-probe-size")
  10560. .getValueAsString()
  10561. .getAsInteger(0, StackProbeSize);
  10562. // Round down to the stack alignment.
  10563. StackProbeSize &= ~(StackAlign - 1);
  10564. return StackProbeSize ? StackProbeSize : StackAlign;
  10565. }
  10566. // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
  10567. // into three phases. In the first phase, it uses pseudo instruction
  10568. // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
  10569. // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
  10570. // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
  10571. // MaxCallFrameSize so that it can calculate correct data area pointer.
  10572. MachineBasicBlock *
  10573. PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
  10574. MachineBasicBlock *MBB) const {
  10575. const bool isPPC64 = Subtarget.isPPC64();
  10576. MachineFunction *MF = MBB->getParent();
  10577. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10578. DebugLoc DL = MI.getDebugLoc();
  10579. const unsigned ProbeSize = getStackProbeSize(*MF);
  10580. const BasicBlock *ProbedBB = MBB->getBasicBlock();
  10581. MachineRegisterInfo &MRI = MF->getRegInfo();
  10582. // The CFG of probing stack looks as
  10583. // +-----+
  10584. // | MBB |
  10585. // +--+--+
  10586. // |
  10587. // +----v----+
  10588. // +--->+ TestMBB +---+
  10589. // | +----+----+ |
  10590. // | | |
  10591. // | +-----v----+ |
  10592. // +---+ BlockMBB | |
  10593. // +----------+ |
  10594. // |
  10595. // +---------+ |
  10596. // | TailMBB +<--+
  10597. // +---------+
  10598. // In MBB, calculate previous frame pointer and final stack pointer.
  10599. // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
  10600. // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
  10601. // TailMBB is spliced via \p MI.
  10602. MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
  10603. MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
  10604. MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
  10605. MachineFunction::iterator MBBIter = ++MBB->getIterator();
  10606. MF->insert(MBBIter, TestMBB);
  10607. MF->insert(MBBIter, BlockMBB);
  10608. MF->insert(MBBIter, TailMBB);
  10609. const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
  10610. const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
  10611. Register DstReg = MI.getOperand(0).getReg();
  10612. Register NegSizeReg = MI.getOperand(1).getReg();
  10613. Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
  10614. Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10615. Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10616. Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10617. // Since value of NegSizeReg might be realigned in prologepilog, insert a
  10618. // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
  10619. // NegSize.
  10620. unsigned ProbeOpc;
  10621. if (!MRI.hasOneNonDBGUse(NegSizeReg))
  10622. ProbeOpc =
  10623. isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
  10624. else
  10625. // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
  10626. // and NegSizeReg will be allocated in the same phyreg to avoid
  10627. // redundant copy when NegSizeReg has only one use which is current MI and
  10628. // will be replaced by PREPARE_PROBED_ALLOCA then.
  10629. ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
  10630. : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
  10631. BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
  10632. .addDef(ActualNegSizeReg)
  10633. .addReg(NegSizeReg)
  10634. .add(MI.getOperand(2))
  10635. .add(MI.getOperand(3));
  10636. // Calculate final stack pointer, which equals to SP + ActualNegSize.
  10637. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
  10638. FinalStackPtr)
  10639. .addReg(SPReg)
  10640. .addReg(ActualNegSizeReg);
  10641. // Materialize a scratch register for update.
  10642. int64_t NegProbeSize = -(int64_t)ProbeSize;
  10643. assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
  10644. Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10645. if (!isInt<16>(NegProbeSize)) {
  10646. Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10647. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
  10648. .addImm(NegProbeSize >> 16);
  10649. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
  10650. ScratchReg)
  10651. .addReg(TempReg)
  10652. .addImm(NegProbeSize & 0xFFFF);
  10653. } else
  10654. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
  10655. .addImm(NegProbeSize);
  10656. {
  10657. // Probing leading residual part.
  10658. Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10659. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
  10660. .addReg(ActualNegSizeReg)
  10661. .addReg(ScratchReg);
  10662. Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10663. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
  10664. .addReg(Div)
  10665. .addReg(ScratchReg);
  10666. Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10667. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
  10668. .addReg(Mul)
  10669. .addReg(ActualNegSizeReg);
  10670. BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
  10671. .addReg(FramePointer)
  10672. .addReg(SPReg)
  10673. .addReg(NegMod);
  10674. }
  10675. {
  10676. // Remaining part should be multiple of ProbeSize.
  10677. Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
  10678. BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
  10679. .addReg(SPReg)
  10680. .addReg(FinalStackPtr);
  10681. BuildMI(TestMBB, DL, TII->get(PPC::BCC))
  10682. .addImm(PPC::PRED_EQ)
  10683. .addReg(CmpResult)
  10684. .addMBB(TailMBB);
  10685. TestMBB->addSuccessor(BlockMBB);
  10686. TestMBB->addSuccessor(TailMBB);
  10687. }
  10688. {
  10689. // Touch the block.
  10690. // |P...|P...|P...
  10691. BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
  10692. .addReg(FramePointer)
  10693. .addReg(SPReg)
  10694. .addReg(ScratchReg);
  10695. BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
  10696. BlockMBB->addSuccessor(TestMBB);
  10697. }
  10698. // Calculation of MaxCallFrameSize is deferred to prologepilog, use
  10699. // DYNAREAOFFSET pseudo instruction to get the future result.
  10700. Register MaxCallFrameSizeReg =
  10701. MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
  10702. BuildMI(TailMBB, DL,
  10703. TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
  10704. MaxCallFrameSizeReg)
  10705. .add(MI.getOperand(2))
  10706. .add(MI.getOperand(3));
  10707. BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
  10708. .addReg(SPReg)
  10709. .addReg(MaxCallFrameSizeReg);
  10710. // Splice instructions after MI to TailMBB.
  10711. TailMBB->splice(TailMBB->end(), MBB,
  10712. std::next(MachineBasicBlock::iterator(MI)), MBB->end());
  10713. TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
  10714. MBB->addSuccessor(TestMBB);
  10715. // Delete the pseudo instruction.
  10716. MI.eraseFromParent();
  10717. ++NumDynamicAllocaProbed;
  10718. return TailMBB;
  10719. }
  10720. MachineBasicBlock *
  10721. PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
  10722. MachineBasicBlock *BB) const {
  10723. if (MI.getOpcode() == TargetOpcode::STACKMAP ||
  10724. MI.getOpcode() == TargetOpcode::PATCHPOINT) {
  10725. if (Subtarget.is64BitELFABI() &&
  10726. MI.getOpcode() == TargetOpcode::PATCHPOINT &&
  10727. !Subtarget.isUsingPCRelativeCalls()) {
  10728. // Call lowering should have added an r2 operand to indicate a dependence
  10729. // on the TOC base pointer value. It can't however, because there is no
  10730. // way to mark the dependence as implicit there, and so the stackmap code
  10731. // will confuse it with a regular operand. Instead, add the dependence
  10732. // here.
  10733. MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
  10734. }
  10735. return emitPatchPoint(MI, BB);
  10736. }
  10737. if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
  10738. MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
  10739. return emitEHSjLjSetJmp(MI, BB);
  10740. } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
  10741. MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
  10742. return emitEHSjLjLongJmp(MI, BB);
  10743. }
  10744. const TargetInstrInfo *TII = Subtarget.getInstrInfo();
  10745. // To "insert" these instructions we actually have to insert their
  10746. // control-flow patterns.
  10747. const BasicBlock *LLVM_BB = BB->getBasicBlock();
  10748. MachineFunction::iterator It = ++BB->getIterator();
  10749. MachineFunction *F = BB->getParent();
  10750. MachineRegisterInfo &MRI = F->getRegInfo();
  10751. if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
  10752. MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
  10753. MI.getOpcode() == PPC::SELECT_I8) {
  10754. SmallVector<MachineOperand, 2> Cond;
  10755. if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
  10756. MI.getOpcode() == PPC::SELECT_CC_I8)
  10757. Cond.push_back(MI.getOperand(4));
  10758. else
  10759. Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
  10760. Cond.push_back(MI.getOperand(1));
  10761. DebugLoc dl = MI.getDebugLoc();
  10762. TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
  10763. MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
  10764. } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
  10765. MI.getOpcode() == PPC::SELECT_CC_F8 ||
  10766. MI.getOpcode() == PPC::SELECT_CC_F16 ||
  10767. MI.getOpcode() == PPC::SELECT_CC_VRRC ||
  10768. MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
  10769. MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
  10770. MI.getOpcode() == PPC::SELECT_CC_VSRC ||
  10771. MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
  10772. MI.getOpcode() == PPC::SELECT_CC_SPE ||
  10773. MI.getOpcode() == PPC::SELECT_F4 ||
  10774. MI.getOpcode() == PPC::SELECT_F8 ||
  10775. MI.getOpcode() == PPC::SELECT_F16 ||
  10776. MI.getOpcode() == PPC::SELECT_SPE ||
  10777. MI.getOpcode() == PPC::SELECT_SPE4 ||
  10778. MI.getOpcode() == PPC::SELECT_VRRC ||
  10779. MI.getOpcode() == PPC::SELECT_VSFRC ||
  10780. MI.getOpcode() == PPC::SELECT_VSSRC ||
  10781. MI.getOpcode() == PPC::SELECT_VSRC) {
  10782. // The incoming instruction knows the destination vreg to set, the
  10783. // condition code register to branch on, the true/false values to
  10784. // select between, and a branch opcode to use.
  10785. // thisMBB:
  10786. // ...
  10787. // TrueVal = ...
  10788. // cmpTY ccX, r1, r2
  10789. // bCC copy1MBB
  10790. // fallthrough --> copy0MBB
  10791. MachineBasicBlock *thisMBB = BB;
  10792. MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
  10793. MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10794. DebugLoc dl = MI.getDebugLoc();
  10795. F->insert(It, copy0MBB);
  10796. F->insert(It, sinkMBB);
  10797. // Transfer the remainder of BB and its successor edges to sinkMBB.
  10798. sinkMBB->splice(sinkMBB->begin(), BB,
  10799. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  10800. sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
  10801. // Next, add the true and fallthrough blocks as its successors.
  10802. BB->addSuccessor(copy0MBB);
  10803. BB->addSuccessor(sinkMBB);
  10804. if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
  10805. MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
  10806. MI.getOpcode() == PPC::SELECT_F16 ||
  10807. MI.getOpcode() == PPC::SELECT_SPE4 ||
  10808. MI.getOpcode() == PPC::SELECT_SPE ||
  10809. MI.getOpcode() == PPC::SELECT_VRRC ||
  10810. MI.getOpcode() == PPC::SELECT_VSFRC ||
  10811. MI.getOpcode() == PPC::SELECT_VSSRC ||
  10812. MI.getOpcode() == PPC::SELECT_VSRC) {
  10813. BuildMI(BB, dl, TII->get(PPC::BC))
  10814. .addReg(MI.getOperand(1).getReg())
  10815. .addMBB(sinkMBB);
  10816. } else {
  10817. unsigned SelectPred = MI.getOperand(4).getImm();
  10818. BuildMI(BB, dl, TII->get(PPC::BCC))
  10819. .addImm(SelectPred)
  10820. .addReg(MI.getOperand(1).getReg())
  10821. .addMBB(sinkMBB);
  10822. }
  10823. // copy0MBB:
  10824. // %FalseValue = ...
  10825. // # fallthrough to sinkMBB
  10826. BB = copy0MBB;
  10827. // Update machine-CFG edges
  10828. BB->addSuccessor(sinkMBB);
  10829. // sinkMBB:
  10830. // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
  10831. // ...
  10832. BB = sinkMBB;
  10833. BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
  10834. .addReg(MI.getOperand(3).getReg())
  10835. .addMBB(copy0MBB)
  10836. .addReg(MI.getOperand(2).getReg())
  10837. .addMBB(thisMBB);
  10838. } else if (MI.getOpcode() == PPC::ReadTB) {
  10839. // To read the 64-bit time-base register on a 32-bit target, we read the
  10840. // two halves. Should the counter have wrapped while it was being read, we
  10841. // need to try again.
  10842. // ...
  10843. // readLoop:
  10844. // mfspr Rx,TBU # load from TBU
  10845. // mfspr Ry,TB # load from TB
  10846. // mfspr Rz,TBU # load from TBU
  10847. // cmpw crX,Rx,Rz # check if 'old'='new'
  10848. // bne readLoop # branch if they're not equal
  10849. // ...
  10850. MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10851. MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10852. DebugLoc dl = MI.getDebugLoc();
  10853. F->insert(It, readMBB);
  10854. F->insert(It, sinkMBB);
  10855. // Transfer the remainder of BB and its successor edges to sinkMBB.
  10856. sinkMBB->splice(sinkMBB->begin(), BB,
  10857. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  10858. sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
  10859. BB->addSuccessor(readMBB);
  10860. BB = readMBB;
  10861. MachineRegisterInfo &RegInfo = F->getRegInfo();
  10862. Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
  10863. Register LoReg = MI.getOperand(0).getReg();
  10864. Register HiReg = MI.getOperand(1).getReg();
  10865. BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
  10866. BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
  10867. BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
  10868. Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
  10869. BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
  10870. .addReg(HiReg)
  10871. .addReg(ReadAgainReg);
  10872. BuildMI(BB, dl, TII->get(PPC::BCC))
  10873. .addImm(PPC::PRED_NE)
  10874. .addReg(CmpReg)
  10875. .addMBB(readMBB);
  10876. BB->addSuccessor(readMBB);
  10877. BB->addSuccessor(sinkMBB);
  10878. } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
  10879. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
  10880. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
  10881. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
  10882. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
  10883. BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
  10884. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
  10885. BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
  10886. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
  10887. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
  10888. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
  10889. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
  10890. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
  10891. BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
  10892. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
  10893. BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
  10894. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
  10895. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
  10896. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
  10897. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
  10898. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
  10899. BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
  10900. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
  10901. BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
  10902. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
  10903. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
  10904. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
  10905. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
  10906. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
  10907. BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
  10908. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
  10909. BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
  10910. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
  10911. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
  10912. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
  10913. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
  10914. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
  10915. BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
  10916. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
  10917. BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
  10918. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
  10919. BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
  10920. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
  10921. BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
  10922. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
  10923. BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
  10924. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
  10925. BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
  10926. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
  10927. BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
  10928. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
  10929. BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
  10930. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
  10931. BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
  10932. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
  10933. BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
  10934. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
  10935. BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
  10936. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
  10937. BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
  10938. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
  10939. BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
  10940. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
  10941. BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
  10942. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
  10943. BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
  10944. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
  10945. BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
  10946. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
  10947. BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
  10948. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
  10949. BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
  10950. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
  10951. BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
  10952. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
  10953. BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
  10954. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
  10955. BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
  10956. else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
  10957. BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
  10958. else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
  10959. BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
  10960. else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
  10961. BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
  10962. else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
  10963. BB = EmitAtomicBinary(MI, BB, 4, 0);
  10964. else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
  10965. BB = EmitAtomicBinary(MI, BB, 8, 0);
  10966. else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
  10967. MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
  10968. (Subtarget.hasPartwordAtomics() &&
  10969. MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
  10970. (Subtarget.hasPartwordAtomics() &&
  10971. MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
  10972. bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
  10973. auto LoadMnemonic = PPC::LDARX;
  10974. auto StoreMnemonic = PPC::STDCX;
  10975. switch (MI.getOpcode()) {
  10976. default:
  10977. llvm_unreachable("Compare and swap of unknown size");
  10978. case PPC::ATOMIC_CMP_SWAP_I8:
  10979. LoadMnemonic = PPC::LBARX;
  10980. StoreMnemonic = PPC::STBCX;
  10981. assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
  10982. break;
  10983. case PPC::ATOMIC_CMP_SWAP_I16:
  10984. LoadMnemonic = PPC::LHARX;
  10985. StoreMnemonic = PPC::STHCX;
  10986. assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
  10987. break;
  10988. case PPC::ATOMIC_CMP_SWAP_I32:
  10989. LoadMnemonic = PPC::LWARX;
  10990. StoreMnemonic = PPC::STWCX;
  10991. break;
  10992. case PPC::ATOMIC_CMP_SWAP_I64:
  10993. LoadMnemonic = PPC::LDARX;
  10994. StoreMnemonic = PPC::STDCX;
  10995. break;
  10996. }
  10997. Register dest = MI.getOperand(0).getReg();
  10998. Register ptrA = MI.getOperand(1).getReg();
  10999. Register ptrB = MI.getOperand(2).getReg();
  11000. Register oldval = MI.getOperand(3).getReg();
  11001. Register newval = MI.getOperand(4).getReg();
  11002. DebugLoc dl = MI.getDebugLoc();
  11003. MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11004. MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11005. MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11006. MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11007. F->insert(It, loop1MBB);
  11008. F->insert(It, loop2MBB);
  11009. F->insert(It, midMBB);
  11010. F->insert(It, exitMBB);
  11011. exitMBB->splice(exitMBB->begin(), BB,
  11012. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  11013. exitMBB->transferSuccessorsAndUpdatePHIs(BB);
  11014. // thisMBB:
  11015. // ...
  11016. // fallthrough --> loopMBB
  11017. BB->addSuccessor(loop1MBB);
  11018. // loop1MBB:
  11019. // l[bhwd]arx dest, ptr
  11020. // cmp[wd] dest, oldval
  11021. // bne- midMBB
  11022. // loop2MBB:
  11023. // st[bhwd]cx. newval, ptr
  11024. // bne- loopMBB
  11025. // b exitBB
  11026. // midMBB:
  11027. // st[bhwd]cx. dest, ptr
  11028. // exitBB:
  11029. BB = loop1MBB;
  11030. BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
  11031. BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
  11032. .addReg(oldval)
  11033. .addReg(dest);
  11034. BuildMI(BB, dl, TII->get(PPC::BCC))
  11035. .addImm(PPC::PRED_NE)
  11036. .addReg(PPC::CR0)
  11037. .addMBB(midMBB);
  11038. BB->addSuccessor(loop2MBB);
  11039. BB->addSuccessor(midMBB);
  11040. BB = loop2MBB;
  11041. BuildMI(BB, dl, TII->get(StoreMnemonic))
  11042. .addReg(newval)
  11043. .addReg(ptrA)
  11044. .addReg(ptrB);
  11045. BuildMI(BB, dl, TII->get(PPC::BCC))
  11046. .addImm(PPC::PRED_NE)
  11047. .addReg(PPC::CR0)
  11048. .addMBB(loop1MBB);
  11049. BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
  11050. BB->addSuccessor(loop1MBB);
  11051. BB->addSuccessor(exitMBB);
  11052. BB = midMBB;
  11053. BuildMI(BB, dl, TII->get(StoreMnemonic))
  11054. .addReg(dest)
  11055. .addReg(ptrA)
  11056. .addReg(ptrB);
  11057. BB->addSuccessor(exitMBB);
  11058. // exitMBB:
  11059. // ...
  11060. BB = exitMBB;
  11061. } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
  11062. MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
  11063. // We must use 64-bit registers for addresses when targeting 64-bit,
  11064. // since we're actually doing arithmetic on them. Other registers
  11065. // can be 32-bit.
  11066. bool is64bit = Subtarget.isPPC64();
  11067. bool isLittleEndian = Subtarget.isLittleEndian();
  11068. bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
  11069. Register dest = MI.getOperand(0).getReg();
  11070. Register ptrA = MI.getOperand(1).getReg();
  11071. Register ptrB = MI.getOperand(2).getReg();
  11072. Register oldval = MI.getOperand(3).getReg();
  11073. Register newval = MI.getOperand(4).getReg();
  11074. DebugLoc dl = MI.getDebugLoc();
  11075. MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11076. MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
  11077. MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11078. MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
  11079. F->insert(It, loop1MBB);
  11080. F->insert(It, loop2MBB);
  11081. F->insert(It, midMBB);
  11082. F->insert(It, exitMBB);
  11083. exitMBB->splice(exitMBB->begin(), BB,
  11084. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  11085. exitMBB->transferSuccessorsAndUpdatePHIs(BB);
  11086. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11087. const TargetRegisterClass *RC =
  11088. is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
  11089. const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
  11090. Register PtrReg = RegInfo.createVirtualRegister(RC);
  11091. Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
  11092. Register ShiftReg =
  11093. isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
  11094. Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
  11095. Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
  11096. Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
  11097. Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
  11098. Register MaskReg = RegInfo.createVirtualRegister(GPRC);
  11099. Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
  11100. Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
  11101. Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
  11102. Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
  11103. Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
  11104. Register Ptr1Reg;
  11105. Register TmpReg = RegInfo.createVirtualRegister(GPRC);
  11106. Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
  11107. // thisMBB:
  11108. // ...
  11109. // fallthrough --> loopMBB
  11110. BB->addSuccessor(loop1MBB);
  11111. // The 4-byte load must be aligned, while a char or short may be
  11112. // anywhere in the word. Hence all this nasty bookkeeping code.
  11113. // add ptr1, ptrA, ptrB [copy if ptrA==0]
  11114. // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
  11115. // xori shift, shift1, 24 [16]
  11116. // rlwinm ptr, ptr1, 0, 0, 29
  11117. // slw newval2, newval, shift
  11118. // slw oldval2, oldval,shift
  11119. // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
  11120. // slw mask, mask2, shift
  11121. // and newval3, newval2, mask
  11122. // and oldval3, oldval2, mask
  11123. // loop1MBB:
  11124. // lwarx tmpDest, ptr
  11125. // and tmp, tmpDest, mask
  11126. // cmpw tmp, oldval3
  11127. // bne- midMBB
  11128. // loop2MBB:
  11129. // andc tmp2, tmpDest, mask
  11130. // or tmp4, tmp2, newval3
  11131. // stwcx. tmp4, ptr
  11132. // bne- loop1MBB
  11133. // b exitBB
  11134. // midMBB:
  11135. // stwcx. tmpDest, ptr
  11136. // exitBB:
  11137. // srw dest, tmpDest, shift
  11138. if (ptrA != ZeroReg) {
  11139. Ptr1Reg = RegInfo.createVirtualRegister(RC);
  11140. BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
  11141. .addReg(ptrA)
  11142. .addReg(ptrB);
  11143. } else {
  11144. Ptr1Reg = ptrB;
  11145. }
  11146. // We need use 32-bit subregister to avoid mismatch register class in 64-bit
  11147. // mode.
  11148. BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
  11149. .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
  11150. .addImm(3)
  11151. .addImm(27)
  11152. .addImm(is8bit ? 28 : 27);
  11153. if (!isLittleEndian)
  11154. BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
  11155. .addReg(Shift1Reg)
  11156. .addImm(is8bit ? 24 : 16);
  11157. if (is64bit)
  11158. BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
  11159. .addReg(Ptr1Reg)
  11160. .addImm(0)
  11161. .addImm(61);
  11162. else
  11163. BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
  11164. .addReg(Ptr1Reg)
  11165. .addImm(0)
  11166. .addImm(0)
  11167. .addImm(29);
  11168. BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
  11169. .addReg(newval)
  11170. .addReg(ShiftReg);
  11171. BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
  11172. .addReg(oldval)
  11173. .addReg(ShiftReg);
  11174. if (is8bit)
  11175. BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
  11176. else {
  11177. BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
  11178. BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
  11179. .addReg(Mask3Reg)
  11180. .addImm(65535);
  11181. }
  11182. BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
  11183. .addReg(Mask2Reg)
  11184. .addReg(ShiftReg);
  11185. BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
  11186. .addReg(NewVal2Reg)
  11187. .addReg(MaskReg);
  11188. BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
  11189. .addReg(OldVal2Reg)
  11190. .addReg(MaskReg);
  11191. BB = loop1MBB;
  11192. BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
  11193. .addReg(ZeroReg)
  11194. .addReg(PtrReg);
  11195. BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
  11196. .addReg(TmpDestReg)
  11197. .addReg(MaskReg);
  11198. BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
  11199. .addReg(TmpReg)
  11200. .addReg(OldVal3Reg);
  11201. BuildMI(BB, dl, TII->get(PPC::BCC))
  11202. .addImm(PPC::PRED_NE)
  11203. .addReg(PPC::CR0)
  11204. .addMBB(midMBB);
  11205. BB->addSuccessor(loop2MBB);
  11206. BB->addSuccessor(midMBB);
  11207. BB = loop2MBB;
  11208. BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
  11209. .addReg(TmpDestReg)
  11210. .addReg(MaskReg);
  11211. BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
  11212. .addReg(Tmp2Reg)
  11213. .addReg(NewVal3Reg);
  11214. BuildMI(BB, dl, TII->get(PPC::STWCX))
  11215. .addReg(Tmp4Reg)
  11216. .addReg(ZeroReg)
  11217. .addReg(PtrReg);
  11218. BuildMI(BB, dl, TII->get(PPC::BCC))
  11219. .addImm(PPC::PRED_NE)
  11220. .addReg(PPC::CR0)
  11221. .addMBB(loop1MBB);
  11222. BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
  11223. BB->addSuccessor(loop1MBB);
  11224. BB->addSuccessor(exitMBB);
  11225. BB = midMBB;
  11226. BuildMI(BB, dl, TII->get(PPC::STWCX))
  11227. .addReg(TmpDestReg)
  11228. .addReg(ZeroReg)
  11229. .addReg(PtrReg);
  11230. BB->addSuccessor(exitMBB);
  11231. // exitMBB:
  11232. // ...
  11233. BB = exitMBB;
  11234. BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
  11235. .addReg(TmpReg)
  11236. .addReg(ShiftReg);
  11237. } else if (MI.getOpcode() == PPC::FADDrtz) {
  11238. // This pseudo performs an FADD with rounding mode temporarily forced
  11239. // to round-to-zero. We emit this via custom inserter since the FPSCR
  11240. // is not modeled at the SelectionDAG level.
  11241. Register Dest = MI.getOperand(0).getReg();
  11242. Register Src1 = MI.getOperand(1).getReg();
  11243. Register Src2 = MI.getOperand(2).getReg();
  11244. DebugLoc dl = MI.getDebugLoc();
  11245. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11246. Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
  11247. // Save FPSCR value.
  11248. BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
  11249. // Set rounding mode to round-to-zero.
  11250. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
  11251. .addImm(31)
  11252. .addReg(PPC::RM, RegState::ImplicitDefine);
  11253. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
  11254. .addImm(30)
  11255. .addReg(PPC::RM, RegState::ImplicitDefine);
  11256. // Perform addition.
  11257. auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
  11258. .addReg(Src1)
  11259. .addReg(Src2);
  11260. if (MI.getFlag(MachineInstr::NoFPExcept))
  11261. MIB.setMIFlag(MachineInstr::NoFPExcept);
  11262. // Restore FPSCR value.
  11263. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
  11264. } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
  11265. MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
  11266. MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
  11267. MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
  11268. unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
  11269. MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
  11270. ? PPC::ANDI8_rec
  11271. : PPC::ANDI_rec;
  11272. bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
  11273. MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
  11274. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11275. Register Dest = RegInfo.createVirtualRegister(
  11276. Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
  11277. DebugLoc Dl = MI.getDebugLoc();
  11278. BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
  11279. .addReg(MI.getOperand(1).getReg())
  11280. .addImm(1);
  11281. BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
  11282. MI.getOperand(0).getReg())
  11283. .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
  11284. } else if (MI.getOpcode() == PPC::TCHECK_RET) {
  11285. DebugLoc Dl = MI.getDebugLoc();
  11286. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11287. Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
  11288. BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
  11289. BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
  11290. MI.getOperand(0).getReg())
  11291. .addReg(CRReg);
  11292. } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
  11293. DebugLoc Dl = MI.getDebugLoc();
  11294. unsigned Imm = MI.getOperand(1).getImm();
  11295. BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
  11296. BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
  11297. MI.getOperand(0).getReg())
  11298. .addReg(PPC::CR0EQ);
  11299. } else if (MI.getOpcode() == PPC::SETRNDi) {
  11300. DebugLoc dl = MI.getDebugLoc();
  11301. Register OldFPSCRReg = MI.getOperand(0).getReg();
  11302. // Save FPSCR value.
  11303. if (MRI.use_empty(OldFPSCRReg))
  11304. BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
  11305. else
  11306. BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
  11307. // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
  11308. // the following settings:
  11309. // 00 Round to nearest
  11310. // 01 Round to 0
  11311. // 10 Round to +inf
  11312. // 11 Round to -inf
  11313. // When the operand is immediate, using the two least significant bits of
  11314. // the immediate to set the bits 62:63 of FPSCR.
  11315. unsigned Mode = MI.getOperand(1).getImm();
  11316. BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
  11317. .addImm(31)
  11318. .addReg(PPC::RM, RegState::ImplicitDefine);
  11319. BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
  11320. .addImm(30)
  11321. .addReg(PPC::RM, RegState::ImplicitDefine);
  11322. } else if (MI.getOpcode() == PPC::SETRND) {
  11323. DebugLoc dl = MI.getDebugLoc();
  11324. // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
  11325. // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
  11326. // If the target doesn't have DirectMove, we should use stack to do the
  11327. // conversion, because the target doesn't have the instructions like mtvsrd
  11328. // or mfvsrd to do this conversion directly.
  11329. auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
  11330. if (Subtarget.hasDirectMove()) {
  11331. BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
  11332. .addReg(SrcReg);
  11333. } else {
  11334. // Use stack to do the register copy.
  11335. unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
  11336. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11337. const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
  11338. if (RC == &PPC::F8RCRegClass) {
  11339. // Copy register from F8RCRegClass to G8RCRegclass.
  11340. assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
  11341. "Unsupported RegClass.");
  11342. StoreOp = PPC::STFD;
  11343. LoadOp = PPC::LD;
  11344. } else {
  11345. // Copy register from G8RCRegClass to F8RCRegclass.
  11346. assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
  11347. (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
  11348. "Unsupported RegClass.");
  11349. }
  11350. MachineFrameInfo &MFI = F->getFrameInfo();
  11351. int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
  11352. MachineMemOperand *MMOStore = F->getMachineMemOperand(
  11353. MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
  11354. MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
  11355. MFI.getObjectAlign(FrameIdx));
  11356. // Store the SrcReg into the stack.
  11357. BuildMI(*BB, MI, dl, TII->get(StoreOp))
  11358. .addReg(SrcReg)
  11359. .addImm(0)
  11360. .addFrameIndex(FrameIdx)
  11361. .addMemOperand(MMOStore);
  11362. MachineMemOperand *MMOLoad = F->getMachineMemOperand(
  11363. MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
  11364. MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
  11365. MFI.getObjectAlign(FrameIdx));
  11366. // Load from the stack where SrcReg is stored, and save to DestReg,
  11367. // so we have done the RegClass conversion from RegClass::SrcReg to
  11368. // RegClass::DestReg.
  11369. BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
  11370. .addImm(0)
  11371. .addFrameIndex(FrameIdx)
  11372. .addMemOperand(MMOLoad);
  11373. }
  11374. };
  11375. Register OldFPSCRReg = MI.getOperand(0).getReg();
  11376. // Save FPSCR value.
  11377. BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
  11378. // When the operand is gprc register, use two least significant bits of the
  11379. // register and mtfsf instruction to set the bits 62:63 of FPSCR.
  11380. //
  11381. // copy OldFPSCRTmpReg, OldFPSCRReg
  11382. // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
  11383. // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
  11384. // copy NewFPSCRReg, NewFPSCRTmpReg
  11385. // mtfsf 255, NewFPSCRReg
  11386. MachineOperand SrcOp = MI.getOperand(1);
  11387. MachineRegisterInfo &RegInfo = F->getRegInfo();
  11388. Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
  11389. copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
  11390. Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
  11391. Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
  11392. // The first operand of INSERT_SUBREG should be a register which has
  11393. // subregisters, we only care about its RegClass, so we should use an
  11394. // IMPLICIT_DEF register.
  11395. BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
  11396. BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
  11397. .addReg(ImDefReg)
  11398. .add(SrcOp)
  11399. .addImm(1);
  11400. Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
  11401. BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
  11402. .addReg(OldFPSCRTmpReg)
  11403. .addReg(ExtSrcReg)
  11404. .addImm(0)
  11405. .addImm(62);
  11406. Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
  11407. copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
  11408. // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
  11409. // bits of FPSCR.
  11410. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
  11411. .addImm(255)
  11412. .addReg(NewFPSCRReg)
  11413. .addImm(0)
  11414. .addImm(0);
  11415. } else if (MI.getOpcode() == PPC::SETFLM) {
  11416. DebugLoc Dl = MI.getDebugLoc();
  11417. // Result of setflm is previous FPSCR content, so we need to save it first.
  11418. Register OldFPSCRReg = MI.getOperand(0).getReg();
  11419. if (MRI.use_empty(OldFPSCRReg))
  11420. BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
  11421. else
  11422. BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
  11423. // Put bits in 32:63 to FPSCR.
  11424. Register NewFPSCRReg = MI.getOperand(1).getReg();
  11425. BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
  11426. .addImm(255)
  11427. .addReg(NewFPSCRReg)
  11428. .addImm(0)
  11429. .addImm(0);
  11430. } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
  11431. MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
  11432. return emitProbedAlloca(MI, BB);
  11433. } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
  11434. DebugLoc DL = MI.getDebugLoc();
  11435. Register Src = MI.getOperand(2).getReg();
  11436. Register Lo = MI.getOperand(0).getReg();
  11437. Register Hi = MI.getOperand(1).getReg();
  11438. BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
  11439. .addDef(Lo)
  11440. .addUse(Src, 0, PPC::sub_gp8_x1);
  11441. BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
  11442. .addDef(Hi)
  11443. .addUse(Src, 0, PPC::sub_gp8_x0);
  11444. } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
  11445. MI.getOpcode() == PPC::STQX_PSEUDO) {
  11446. DebugLoc DL = MI.getDebugLoc();
  11447. // Ptr is used as the ptr_rc_no_r0 part
  11448. // of LQ/STQ's memory operand and adding result of RA and RB,
  11449. // so it has to be g8rc_and_g8rc_nox0.
  11450. Register Ptr =
  11451. F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
  11452. Register Val = MI.getOperand(0).getReg();
  11453. Register RA = MI.getOperand(1).getReg();
  11454. Register RB = MI.getOperand(2).getReg();
  11455. BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
  11456. BuildMI(*BB, MI, DL,
  11457. MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
  11458. : TII->get(PPC::STQ))
  11459. .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
  11460. .addImm(0)
  11461. .addReg(Ptr);
  11462. } else {
  11463. llvm_unreachable("Unexpected instr type to insert");
  11464. }
  11465. MI.eraseFromParent(); // The pseudo instruction is gone now.
  11466. return BB;
  11467. }
  11468. //===----------------------------------------------------------------------===//
  11469. // Target Optimization Hooks
  11470. //===----------------------------------------------------------------------===//
  11471. static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
  11472. // For the estimates, convergence is quadratic, so we essentially double the
  11473. // number of digits correct after every iteration. For both FRE and FRSQRTE,
  11474. // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
  11475. // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
  11476. int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
  11477. if (VT.getScalarType() == MVT::f64)
  11478. RefinementSteps++;
  11479. return RefinementSteps;
  11480. }
  11481. SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
  11482. const DenormalMode &Mode) const {
  11483. // We only have VSX Vector Test for software Square Root.
  11484. EVT VT = Op.getValueType();
  11485. if (!isTypeLegal(MVT::i1) ||
  11486. (VT != MVT::f64 &&
  11487. ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
  11488. return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
  11489. SDLoc DL(Op);
  11490. // The output register of FTSQRT is CR field.
  11491. SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
  11492. // ftsqrt BF,FRB
  11493. // Let e_b be the unbiased exponent of the double-precision
  11494. // floating-point operand in register FRB.
  11495. // fe_flag is set to 1 if either of the following conditions occurs.
  11496. // - The double-precision floating-point operand in register FRB is a zero,
  11497. // a NaN, or an infinity, or a negative value.
  11498. // - e_b is less than or equal to -970.
  11499. // Otherwise fe_flag is set to 0.
  11500. // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
  11501. // not eligible for iteration. (zero/negative/infinity/nan or unbiased
  11502. // exponent is less than -970)
  11503. SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
  11504. return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
  11505. FTSQRT, SRIdxVal),
  11506. 0);
  11507. }
  11508. SDValue
  11509. PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
  11510. SelectionDAG &DAG) const {
  11511. // We only have VSX Vector Square Root.
  11512. EVT VT = Op.getValueType();
  11513. if (VT != MVT::f64 &&
  11514. ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
  11515. return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
  11516. return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
  11517. }
  11518. SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
  11519. int Enabled, int &RefinementSteps,
  11520. bool &UseOneConstNR,
  11521. bool Reciprocal) const {
  11522. EVT VT = Operand.getValueType();
  11523. if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
  11524. (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
  11525. (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
  11526. (VT == MVT::v2f64 && Subtarget.hasVSX())) {
  11527. if (RefinementSteps == ReciprocalEstimate::Unspecified)
  11528. RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
  11529. // The Newton-Raphson computation with a single constant does not provide
  11530. // enough accuracy on some CPUs.
  11531. UseOneConstNR = !Subtarget.needsTwoConstNR();
  11532. return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
  11533. }
  11534. return SDValue();
  11535. }
  11536. SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
  11537. int Enabled,
  11538. int &RefinementSteps) const {
  11539. EVT VT = Operand.getValueType();
  11540. if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
  11541. (VT == MVT::f64 && Subtarget.hasFRE()) ||
  11542. (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
  11543. (VT == MVT::v2f64 && Subtarget.hasVSX())) {
  11544. if (RefinementSteps == ReciprocalEstimate::Unspecified)
  11545. RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
  11546. return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
  11547. }
  11548. return SDValue();
  11549. }
  11550. unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
  11551. // Note: This functionality is used only when unsafe-fp-math is enabled, and
  11552. // on cores with reciprocal estimates (which are used when unsafe-fp-math is
  11553. // enabled for division), this functionality is redundant with the default
  11554. // combiner logic (once the division -> reciprocal/multiply transformation
  11555. // has taken place). As a result, this matters more for older cores than for
  11556. // newer ones.
  11557. // Combine multiple FDIVs with the same divisor into multiple FMULs by the
  11558. // reciprocal if there are two or more FDIVs (for embedded cores with only
  11559. // one FP pipeline) for three or more FDIVs (for generic OOO cores).
  11560. switch (Subtarget.getCPUDirective()) {
  11561. default:
  11562. return 3;
  11563. case PPC::DIR_440:
  11564. case PPC::DIR_A2:
  11565. case PPC::DIR_E500:
  11566. case PPC::DIR_E500mc:
  11567. case PPC::DIR_E5500:
  11568. return 2;
  11569. }
  11570. }
  11571. // isConsecutiveLSLoc needs to work even if all adds have not yet been
  11572. // collapsed, and so we need to look through chains of them.
  11573. static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
  11574. int64_t& Offset, SelectionDAG &DAG) {
  11575. if (DAG.isBaseWithConstantOffset(Loc)) {
  11576. Base = Loc.getOperand(0);
  11577. Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
  11578. // The base might itself be a base plus an offset, and if so, accumulate
  11579. // that as well.
  11580. getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
  11581. }
  11582. }
  11583. static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
  11584. unsigned Bytes, int Dist,
  11585. SelectionDAG &DAG) {
  11586. if (VT.getSizeInBits() / 8 != Bytes)
  11587. return false;
  11588. SDValue BaseLoc = Base->getBasePtr();
  11589. if (Loc.getOpcode() == ISD::FrameIndex) {
  11590. if (BaseLoc.getOpcode() != ISD::FrameIndex)
  11591. return false;
  11592. const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  11593. int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
  11594. int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
  11595. int FS = MFI.getObjectSize(FI);
  11596. int BFS = MFI.getObjectSize(BFI);
  11597. if (FS != BFS || FS != (int)Bytes) return false;
  11598. return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
  11599. }
  11600. SDValue Base1 = Loc, Base2 = BaseLoc;
  11601. int64_t Offset1 = 0, Offset2 = 0;
  11602. getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
  11603. getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
  11604. if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
  11605. return true;
  11606. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  11607. const GlobalValue *GV1 = nullptr;
  11608. const GlobalValue *GV2 = nullptr;
  11609. Offset1 = 0;
  11610. Offset2 = 0;
  11611. bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
  11612. bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
  11613. if (isGA1 && isGA2 && GV1 == GV2)
  11614. return Offset1 == (Offset2 + Dist*Bytes);
  11615. return false;
  11616. }
  11617. // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
  11618. // not enforce equality of the chain operands.
  11619. static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
  11620. unsigned Bytes, int Dist,
  11621. SelectionDAG &DAG) {
  11622. if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
  11623. EVT VT = LS->getMemoryVT();
  11624. SDValue Loc = LS->getBasePtr();
  11625. return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
  11626. }
  11627. if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
  11628. EVT VT;
  11629. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  11630. default: return false;
  11631. case Intrinsic::ppc_altivec_lvx:
  11632. case Intrinsic::ppc_altivec_lvxl:
  11633. case Intrinsic::ppc_vsx_lxvw4x:
  11634. case Intrinsic::ppc_vsx_lxvw4x_be:
  11635. VT = MVT::v4i32;
  11636. break;
  11637. case Intrinsic::ppc_vsx_lxvd2x:
  11638. case Intrinsic::ppc_vsx_lxvd2x_be:
  11639. VT = MVT::v2f64;
  11640. break;
  11641. case Intrinsic::ppc_altivec_lvebx:
  11642. VT = MVT::i8;
  11643. break;
  11644. case Intrinsic::ppc_altivec_lvehx:
  11645. VT = MVT::i16;
  11646. break;
  11647. case Intrinsic::ppc_altivec_lvewx:
  11648. VT = MVT::i32;
  11649. break;
  11650. }
  11651. return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
  11652. }
  11653. if (N->getOpcode() == ISD::INTRINSIC_VOID) {
  11654. EVT VT;
  11655. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  11656. default: return false;
  11657. case Intrinsic::ppc_altivec_stvx:
  11658. case Intrinsic::ppc_altivec_stvxl:
  11659. case Intrinsic::ppc_vsx_stxvw4x:
  11660. VT = MVT::v4i32;
  11661. break;
  11662. case Intrinsic::ppc_vsx_stxvd2x:
  11663. VT = MVT::v2f64;
  11664. break;
  11665. case Intrinsic::ppc_vsx_stxvw4x_be:
  11666. VT = MVT::v4i32;
  11667. break;
  11668. case Intrinsic::ppc_vsx_stxvd2x_be:
  11669. VT = MVT::v2f64;
  11670. break;
  11671. case Intrinsic::ppc_altivec_stvebx:
  11672. VT = MVT::i8;
  11673. break;
  11674. case Intrinsic::ppc_altivec_stvehx:
  11675. VT = MVT::i16;
  11676. break;
  11677. case Intrinsic::ppc_altivec_stvewx:
  11678. VT = MVT::i32;
  11679. break;
  11680. }
  11681. return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
  11682. }
  11683. return false;
  11684. }
  11685. // Return true is there is a nearyby consecutive load to the one provided
  11686. // (regardless of alignment). We search up and down the chain, looking though
  11687. // token factors and other loads (but nothing else). As a result, a true result
  11688. // indicates that it is safe to create a new consecutive load adjacent to the
  11689. // load provided.
  11690. static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
  11691. SDValue Chain = LD->getChain();
  11692. EVT VT = LD->getMemoryVT();
  11693. SmallSet<SDNode *, 16> LoadRoots;
  11694. SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
  11695. SmallSet<SDNode *, 16> Visited;
  11696. // First, search up the chain, branching to follow all token-factor operands.
  11697. // If we find a consecutive load, then we're done, otherwise, record all
  11698. // nodes just above the top-level loads and token factors.
  11699. while (!Queue.empty()) {
  11700. SDNode *ChainNext = Queue.pop_back_val();
  11701. if (!Visited.insert(ChainNext).second)
  11702. continue;
  11703. if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
  11704. if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
  11705. return true;
  11706. if (!Visited.count(ChainLD->getChain().getNode()))
  11707. Queue.push_back(ChainLD->getChain().getNode());
  11708. } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
  11709. for (const SDUse &O : ChainNext->ops())
  11710. if (!Visited.count(O.getNode()))
  11711. Queue.push_back(O.getNode());
  11712. } else
  11713. LoadRoots.insert(ChainNext);
  11714. }
  11715. // Second, search down the chain, starting from the top-level nodes recorded
  11716. // in the first phase. These top-level nodes are the nodes just above all
  11717. // loads and token factors. Starting with their uses, recursively look though
  11718. // all loads (just the chain uses) and token factors to find a consecutive
  11719. // load.
  11720. Visited.clear();
  11721. Queue.clear();
  11722. for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
  11723. IE = LoadRoots.end(); I != IE; ++I) {
  11724. Queue.push_back(*I);
  11725. while (!Queue.empty()) {
  11726. SDNode *LoadRoot = Queue.pop_back_val();
  11727. if (!Visited.insert(LoadRoot).second)
  11728. continue;
  11729. if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
  11730. if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
  11731. return true;
  11732. for (SDNode *U : LoadRoot->uses())
  11733. if (((isa<MemSDNode>(U) &&
  11734. cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
  11735. U->getOpcode() == ISD::TokenFactor) &&
  11736. !Visited.count(U))
  11737. Queue.push_back(U);
  11738. }
  11739. }
  11740. return false;
  11741. }
  11742. /// This function is called when we have proved that a SETCC node can be replaced
  11743. /// by subtraction (and other supporting instructions) so that the result of
  11744. /// comparison is kept in a GPR instead of CR. This function is purely for
  11745. /// codegen purposes and has some flags to guide the codegen process.
  11746. static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
  11747. bool Swap, SDLoc &DL, SelectionDAG &DAG) {
  11748. assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
  11749. // Zero extend the operands to the largest legal integer. Originally, they
  11750. // must be of a strictly smaller size.
  11751. auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
  11752. DAG.getConstant(Size, DL, MVT::i32));
  11753. auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
  11754. DAG.getConstant(Size, DL, MVT::i32));
  11755. // Swap if needed. Depends on the condition code.
  11756. if (Swap)
  11757. std::swap(Op0, Op1);
  11758. // Subtract extended integers.
  11759. auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
  11760. // Move the sign bit to the least significant position and zero out the rest.
  11761. // Now the least significant bit carries the result of original comparison.
  11762. auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
  11763. DAG.getConstant(Size - 1, DL, MVT::i32));
  11764. auto Final = Shifted;
  11765. // Complement the result if needed. Based on the condition code.
  11766. if (Complement)
  11767. Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
  11768. DAG.getConstant(1, DL, MVT::i64));
  11769. return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
  11770. }
  11771. SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
  11772. DAGCombinerInfo &DCI) const {
  11773. assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
  11774. SelectionDAG &DAG = DCI.DAG;
  11775. SDLoc DL(N);
  11776. // Size of integers being compared has a critical role in the following
  11777. // analysis, so we prefer to do this when all types are legal.
  11778. if (!DCI.isAfterLegalizeDAG())
  11779. return SDValue();
  11780. // If all users of SETCC extend its value to a legal integer type
  11781. // then we replace SETCC with a subtraction
  11782. for (const SDNode *U : N->uses())
  11783. if (U->getOpcode() != ISD::ZERO_EXTEND)
  11784. return SDValue();
  11785. ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
  11786. auto OpSize = N->getOperand(0).getValueSizeInBits();
  11787. unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
  11788. if (OpSize < Size) {
  11789. switch (CC) {
  11790. default: break;
  11791. case ISD::SETULT:
  11792. return generateEquivalentSub(N, Size, false, false, DL, DAG);
  11793. case ISD::SETULE:
  11794. return generateEquivalentSub(N, Size, true, true, DL, DAG);
  11795. case ISD::SETUGT:
  11796. return generateEquivalentSub(N, Size, false, true, DL, DAG);
  11797. case ISD::SETUGE:
  11798. return generateEquivalentSub(N, Size, true, false, DL, DAG);
  11799. }
  11800. }
  11801. return SDValue();
  11802. }
  11803. SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
  11804. DAGCombinerInfo &DCI) const {
  11805. SelectionDAG &DAG = DCI.DAG;
  11806. SDLoc dl(N);
  11807. assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
  11808. // If we're tracking CR bits, we need to be careful that we don't have:
  11809. // trunc(binary-ops(zext(x), zext(y)))
  11810. // or
  11811. // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
  11812. // such that we're unnecessarily moving things into GPRs when it would be
  11813. // better to keep them in CR bits.
  11814. // Note that trunc here can be an actual i1 trunc, or can be the effective
  11815. // truncation that comes from a setcc or select_cc.
  11816. if (N->getOpcode() == ISD::TRUNCATE &&
  11817. N->getValueType(0) != MVT::i1)
  11818. return SDValue();
  11819. if (N->getOperand(0).getValueType() != MVT::i32 &&
  11820. N->getOperand(0).getValueType() != MVT::i64)
  11821. return SDValue();
  11822. if (N->getOpcode() == ISD::SETCC ||
  11823. N->getOpcode() == ISD::SELECT_CC) {
  11824. // If we're looking at a comparison, then we need to make sure that the
  11825. // high bits (all except for the first) don't matter the result.
  11826. ISD::CondCode CC =
  11827. cast<CondCodeSDNode>(N->getOperand(
  11828. N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
  11829. unsigned OpBits = N->getOperand(0).getValueSizeInBits();
  11830. if (ISD::isSignedIntSetCC(CC)) {
  11831. if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
  11832. DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
  11833. return SDValue();
  11834. } else if (ISD::isUnsignedIntSetCC(CC)) {
  11835. if (!DAG.MaskedValueIsZero(N->getOperand(0),
  11836. APInt::getHighBitsSet(OpBits, OpBits-1)) ||
  11837. !DAG.MaskedValueIsZero(N->getOperand(1),
  11838. APInt::getHighBitsSet(OpBits, OpBits-1)))
  11839. return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
  11840. : SDValue());
  11841. } else {
  11842. // This is neither a signed nor an unsigned comparison, just make sure
  11843. // that the high bits are equal.
  11844. KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
  11845. KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
  11846. // We don't really care about what is known about the first bit (if
  11847. // anything), so pretend that it is known zero for both to ensure they can
  11848. // be compared as constants.
  11849. Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
  11850. Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
  11851. if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
  11852. Op1Known.getConstant() != Op2Known.getConstant())
  11853. return SDValue();
  11854. }
  11855. }
  11856. // We now know that the higher-order bits are irrelevant, we just need to
  11857. // make sure that all of the intermediate operations are bit operations, and
  11858. // all inputs are extensions.
  11859. if (N->getOperand(0).getOpcode() != ISD::AND &&
  11860. N->getOperand(0).getOpcode() != ISD::OR &&
  11861. N->getOperand(0).getOpcode() != ISD::XOR &&
  11862. N->getOperand(0).getOpcode() != ISD::SELECT &&
  11863. N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
  11864. N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
  11865. N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
  11866. N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
  11867. N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
  11868. return SDValue();
  11869. if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
  11870. N->getOperand(1).getOpcode() != ISD::AND &&
  11871. N->getOperand(1).getOpcode() != ISD::OR &&
  11872. N->getOperand(1).getOpcode() != ISD::XOR &&
  11873. N->getOperand(1).getOpcode() != ISD::SELECT &&
  11874. N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
  11875. N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
  11876. N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
  11877. N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
  11878. N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
  11879. return SDValue();
  11880. SmallVector<SDValue, 4> Inputs;
  11881. SmallVector<SDValue, 8> BinOps, PromOps;
  11882. SmallPtrSet<SDNode *, 16> Visited;
  11883. for (unsigned i = 0; i < 2; ++i) {
  11884. if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
  11885. N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
  11886. N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
  11887. N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
  11888. isa<ConstantSDNode>(N->getOperand(i)))
  11889. Inputs.push_back(N->getOperand(i));
  11890. else
  11891. BinOps.push_back(N->getOperand(i));
  11892. if (N->getOpcode() == ISD::TRUNCATE)
  11893. break;
  11894. }
  11895. // Visit all inputs, collect all binary operations (and, or, xor and
  11896. // select) that are all fed by extensions.
  11897. while (!BinOps.empty()) {
  11898. SDValue BinOp = BinOps.pop_back_val();
  11899. if (!Visited.insert(BinOp.getNode()).second)
  11900. continue;
  11901. PromOps.push_back(BinOp);
  11902. for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
  11903. // The condition of the select is not promoted.
  11904. if (BinOp.getOpcode() == ISD::SELECT && i == 0)
  11905. continue;
  11906. if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
  11907. continue;
  11908. if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
  11909. BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
  11910. BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
  11911. BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
  11912. isa<ConstantSDNode>(BinOp.getOperand(i))) {
  11913. Inputs.push_back(BinOp.getOperand(i));
  11914. } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
  11915. BinOp.getOperand(i).getOpcode() == ISD::OR ||
  11916. BinOp.getOperand(i).getOpcode() == ISD::XOR ||
  11917. BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
  11918. BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
  11919. BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
  11920. BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
  11921. BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
  11922. BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
  11923. BinOps.push_back(BinOp.getOperand(i));
  11924. } else {
  11925. // We have an input that is not an extension or another binary
  11926. // operation; we'll abort this transformation.
  11927. return SDValue();
  11928. }
  11929. }
  11930. }
  11931. // Make sure that this is a self-contained cluster of operations (which
  11932. // is not quite the same thing as saying that everything has only one
  11933. // use).
  11934. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  11935. if (isa<ConstantSDNode>(Inputs[i]))
  11936. continue;
  11937. for (const SDNode *User : Inputs[i].getNode()->uses()) {
  11938. if (User != N && !Visited.count(User))
  11939. return SDValue();
  11940. // Make sure that we're not going to promote the non-output-value
  11941. // operand(s) or SELECT or SELECT_CC.
  11942. // FIXME: Although we could sometimes handle this, and it does occur in
  11943. // practice that one of the condition inputs to the select is also one of
  11944. // the outputs, we currently can't deal with this.
  11945. if (User->getOpcode() == ISD::SELECT) {
  11946. if (User->getOperand(0) == Inputs[i])
  11947. return SDValue();
  11948. } else if (User->getOpcode() == ISD::SELECT_CC) {
  11949. if (User->getOperand(0) == Inputs[i] ||
  11950. User->getOperand(1) == Inputs[i])
  11951. return SDValue();
  11952. }
  11953. }
  11954. }
  11955. for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
  11956. for (const SDNode *User : PromOps[i].getNode()->uses()) {
  11957. if (User != N && !Visited.count(User))
  11958. return SDValue();
  11959. // Make sure that we're not going to promote the non-output-value
  11960. // operand(s) or SELECT or SELECT_CC.
  11961. // FIXME: Although we could sometimes handle this, and it does occur in
  11962. // practice that one of the condition inputs to the select is also one of
  11963. // the outputs, we currently can't deal with this.
  11964. if (User->getOpcode() == ISD::SELECT) {
  11965. if (User->getOperand(0) == PromOps[i])
  11966. return SDValue();
  11967. } else if (User->getOpcode() == ISD::SELECT_CC) {
  11968. if (User->getOperand(0) == PromOps[i] ||
  11969. User->getOperand(1) == PromOps[i])
  11970. return SDValue();
  11971. }
  11972. }
  11973. }
  11974. // Replace all inputs with the extension operand.
  11975. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  11976. // Constants may have users outside the cluster of to-be-promoted nodes,
  11977. // and so we need to replace those as we do the promotions.
  11978. if (isa<ConstantSDNode>(Inputs[i]))
  11979. continue;
  11980. else
  11981. DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
  11982. }
  11983. std::list<HandleSDNode> PromOpHandles;
  11984. for (auto &PromOp : PromOps)
  11985. PromOpHandles.emplace_back(PromOp);
  11986. // Replace all operations (these are all the same, but have a different
  11987. // (i1) return type). DAG.getNode will validate that the types of
  11988. // a binary operator match, so go through the list in reverse so that
  11989. // we've likely promoted both operands first. Any intermediate truncations or
  11990. // extensions disappear.
  11991. while (!PromOpHandles.empty()) {
  11992. SDValue PromOp = PromOpHandles.back().getValue();
  11993. PromOpHandles.pop_back();
  11994. if (PromOp.getOpcode() == ISD::TRUNCATE ||
  11995. PromOp.getOpcode() == ISD::SIGN_EXTEND ||
  11996. PromOp.getOpcode() == ISD::ZERO_EXTEND ||
  11997. PromOp.getOpcode() == ISD::ANY_EXTEND) {
  11998. if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
  11999. PromOp.getOperand(0).getValueType() != MVT::i1) {
  12000. // The operand is not yet ready (see comment below).
  12001. PromOpHandles.emplace_front(PromOp);
  12002. continue;
  12003. }
  12004. SDValue RepValue = PromOp.getOperand(0);
  12005. if (isa<ConstantSDNode>(RepValue))
  12006. RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
  12007. DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
  12008. continue;
  12009. }
  12010. unsigned C;
  12011. switch (PromOp.getOpcode()) {
  12012. default: C = 0; break;
  12013. case ISD::SELECT: C = 1; break;
  12014. case ISD::SELECT_CC: C = 2; break;
  12015. }
  12016. if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
  12017. PromOp.getOperand(C).getValueType() != MVT::i1) ||
  12018. (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
  12019. PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
  12020. // The to-be-promoted operands of this node have not yet been
  12021. // promoted (this should be rare because we're going through the
  12022. // list backward, but if one of the operands has several users in
  12023. // this cluster of to-be-promoted nodes, it is possible).
  12024. PromOpHandles.emplace_front(PromOp);
  12025. continue;
  12026. }
  12027. SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
  12028. PromOp.getNode()->op_end());
  12029. // If there are any constant inputs, make sure they're replaced now.
  12030. for (unsigned i = 0; i < 2; ++i)
  12031. if (isa<ConstantSDNode>(Ops[C+i]))
  12032. Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
  12033. DAG.ReplaceAllUsesOfValueWith(PromOp,
  12034. DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
  12035. }
  12036. // Now we're left with the initial truncation itself.
  12037. if (N->getOpcode() == ISD::TRUNCATE)
  12038. return N->getOperand(0);
  12039. // Otherwise, this is a comparison. The operands to be compared have just
  12040. // changed type (to i1), but everything else is the same.
  12041. return SDValue(N, 0);
  12042. }
  12043. SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
  12044. DAGCombinerInfo &DCI) const {
  12045. SelectionDAG &DAG = DCI.DAG;
  12046. SDLoc dl(N);
  12047. // If we're tracking CR bits, we need to be careful that we don't have:
  12048. // zext(binary-ops(trunc(x), trunc(y)))
  12049. // or
  12050. // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
  12051. // such that we're unnecessarily moving things into CR bits that can more
  12052. // efficiently stay in GPRs. Note that if we're not certain that the high
  12053. // bits are set as required by the final extension, we still may need to do
  12054. // some masking to get the proper behavior.
  12055. // This same functionality is important on PPC64 when dealing with
  12056. // 32-to-64-bit extensions; these occur often when 32-bit values are used as
  12057. // the return values of functions. Because it is so similar, it is handled
  12058. // here as well.
  12059. if (N->getValueType(0) != MVT::i32 &&
  12060. N->getValueType(0) != MVT::i64)
  12061. return SDValue();
  12062. if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
  12063. (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
  12064. return SDValue();
  12065. if (N->getOperand(0).getOpcode() != ISD::AND &&
  12066. N->getOperand(0).getOpcode() != ISD::OR &&
  12067. N->getOperand(0).getOpcode() != ISD::XOR &&
  12068. N->getOperand(0).getOpcode() != ISD::SELECT &&
  12069. N->getOperand(0).getOpcode() != ISD::SELECT_CC)
  12070. return SDValue();
  12071. SmallVector<SDValue, 4> Inputs;
  12072. SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
  12073. SmallPtrSet<SDNode *, 16> Visited;
  12074. // Visit all inputs, collect all binary operations (and, or, xor and
  12075. // select) that are all fed by truncations.
  12076. while (!BinOps.empty()) {
  12077. SDValue BinOp = BinOps.pop_back_val();
  12078. if (!Visited.insert(BinOp.getNode()).second)
  12079. continue;
  12080. PromOps.push_back(BinOp);
  12081. for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
  12082. // The condition of the select is not promoted.
  12083. if (BinOp.getOpcode() == ISD::SELECT && i == 0)
  12084. continue;
  12085. if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
  12086. continue;
  12087. if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
  12088. isa<ConstantSDNode>(BinOp.getOperand(i))) {
  12089. Inputs.push_back(BinOp.getOperand(i));
  12090. } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
  12091. BinOp.getOperand(i).getOpcode() == ISD::OR ||
  12092. BinOp.getOperand(i).getOpcode() == ISD::XOR ||
  12093. BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
  12094. BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
  12095. BinOps.push_back(BinOp.getOperand(i));
  12096. } else {
  12097. // We have an input that is not a truncation or another binary
  12098. // operation; we'll abort this transformation.
  12099. return SDValue();
  12100. }
  12101. }
  12102. }
  12103. // The operands of a select that must be truncated when the select is
  12104. // promoted because the operand is actually part of the to-be-promoted set.
  12105. DenseMap<SDNode *, EVT> SelectTruncOp[2];
  12106. // Make sure that this is a self-contained cluster of operations (which
  12107. // is not quite the same thing as saying that everything has only one
  12108. // use).
  12109. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  12110. if (isa<ConstantSDNode>(Inputs[i]))
  12111. continue;
  12112. for (SDNode *User : Inputs[i].getNode()->uses()) {
  12113. if (User != N && !Visited.count(User))
  12114. return SDValue();
  12115. // If we're going to promote the non-output-value operand(s) or SELECT or
  12116. // SELECT_CC, record them for truncation.
  12117. if (User->getOpcode() == ISD::SELECT) {
  12118. if (User->getOperand(0) == Inputs[i])
  12119. SelectTruncOp[0].insert(std::make_pair(User,
  12120. User->getOperand(0).getValueType()));
  12121. } else if (User->getOpcode() == ISD::SELECT_CC) {
  12122. if (User->getOperand(0) == Inputs[i])
  12123. SelectTruncOp[0].insert(std::make_pair(User,
  12124. User->getOperand(0).getValueType()));
  12125. if (User->getOperand(1) == Inputs[i])
  12126. SelectTruncOp[1].insert(std::make_pair(User,
  12127. User->getOperand(1).getValueType()));
  12128. }
  12129. }
  12130. }
  12131. for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
  12132. for (SDNode *User : PromOps[i].getNode()->uses()) {
  12133. if (User != N && !Visited.count(User))
  12134. return SDValue();
  12135. // If we're going to promote the non-output-value operand(s) or SELECT or
  12136. // SELECT_CC, record them for truncation.
  12137. if (User->getOpcode() == ISD::SELECT) {
  12138. if (User->getOperand(0) == PromOps[i])
  12139. SelectTruncOp[0].insert(std::make_pair(User,
  12140. User->getOperand(0).getValueType()));
  12141. } else if (User->getOpcode() == ISD::SELECT_CC) {
  12142. if (User->getOperand(0) == PromOps[i])
  12143. SelectTruncOp[0].insert(std::make_pair(User,
  12144. User->getOperand(0).getValueType()));
  12145. if (User->getOperand(1) == PromOps[i])
  12146. SelectTruncOp[1].insert(std::make_pair(User,
  12147. User->getOperand(1).getValueType()));
  12148. }
  12149. }
  12150. }
  12151. unsigned PromBits = N->getOperand(0).getValueSizeInBits();
  12152. bool ReallyNeedsExt = false;
  12153. if (N->getOpcode() != ISD::ANY_EXTEND) {
  12154. // If all of the inputs are not already sign/zero extended, then
  12155. // we'll still need to do that at the end.
  12156. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  12157. if (isa<ConstantSDNode>(Inputs[i]))
  12158. continue;
  12159. unsigned OpBits =
  12160. Inputs[i].getOperand(0).getValueSizeInBits();
  12161. assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
  12162. if ((N->getOpcode() == ISD::ZERO_EXTEND &&
  12163. !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
  12164. APInt::getHighBitsSet(OpBits,
  12165. OpBits-PromBits))) ||
  12166. (N->getOpcode() == ISD::SIGN_EXTEND &&
  12167. DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
  12168. (OpBits-(PromBits-1)))) {
  12169. ReallyNeedsExt = true;
  12170. break;
  12171. }
  12172. }
  12173. }
  12174. // Replace all inputs, either with the truncation operand, or a
  12175. // truncation or extension to the final output type.
  12176. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
  12177. // Constant inputs need to be replaced with the to-be-promoted nodes that
  12178. // use them because they might have users outside of the cluster of
  12179. // promoted nodes.
  12180. if (isa<ConstantSDNode>(Inputs[i]))
  12181. continue;
  12182. SDValue InSrc = Inputs[i].getOperand(0);
  12183. if (Inputs[i].getValueType() == N->getValueType(0))
  12184. DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
  12185. else if (N->getOpcode() == ISD::SIGN_EXTEND)
  12186. DAG.ReplaceAllUsesOfValueWith(Inputs[i],
  12187. DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
  12188. else if (N->getOpcode() == ISD::ZERO_EXTEND)
  12189. DAG.ReplaceAllUsesOfValueWith(Inputs[i],
  12190. DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
  12191. else
  12192. DAG.ReplaceAllUsesOfValueWith(Inputs[i],
  12193. DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
  12194. }
  12195. std::list<HandleSDNode> PromOpHandles;
  12196. for (auto &PromOp : PromOps)
  12197. PromOpHandles.emplace_back(PromOp);
  12198. // Replace all operations (these are all the same, but have a different
  12199. // (promoted) return type). DAG.getNode will validate that the types of
  12200. // a binary operator match, so go through the list in reverse so that
  12201. // we've likely promoted both operands first.
  12202. while (!PromOpHandles.empty()) {
  12203. SDValue PromOp = PromOpHandles.back().getValue();
  12204. PromOpHandles.pop_back();
  12205. unsigned C;
  12206. switch (PromOp.getOpcode()) {
  12207. default: C = 0; break;
  12208. case ISD::SELECT: C = 1; break;
  12209. case ISD::SELECT_CC: C = 2; break;
  12210. }
  12211. if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
  12212. PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
  12213. (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
  12214. PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
  12215. // The to-be-promoted operands of this node have not yet been
  12216. // promoted (this should be rare because we're going through the
  12217. // list backward, but if one of the operands has several users in
  12218. // this cluster of to-be-promoted nodes, it is possible).
  12219. PromOpHandles.emplace_front(PromOp);
  12220. continue;
  12221. }
  12222. // For SELECT and SELECT_CC nodes, we do a similar check for any
  12223. // to-be-promoted comparison inputs.
  12224. if (PromOp.getOpcode() == ISD::SELECT ||
  12225. PromOp.getOpcode() == ISD::SELECT_CC) {
  12226. if ((SelectTruncOp[0].count(PromOp.getNode()) &&
  12227. PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
  12228. (SelectTruncOp[1].count(PromOp.getNode()) &&
  12229. PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
  12230. PromOpHandles.emplace_front(PromOp);
  12231. continue;
  12232. }
  12233. }
  12234. SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
  12235. PromOp.getNode()->op_end());
  12236. // If this node has constant inputs, then they'll need to be promoted here.
  12237. for (unsigned i = 0; i < 2; ++i) {
  12238. if (!isa<ConstantSDNode>(Ops[C+i]))
  12239. continue;
  12240. if (Ops[C+i].getValueType() == N->getValueType(0))
  12241. continue;
  12242. if (N->getOpcode() == ISD::SIGN_EXTEND)
  12243. Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
  12244. else if (N->getOpcode() == ISD::ZERO_EXTEND)
  12245. Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
  12246. else
  12247. Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
  12248. }
  12249. // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
  12250. // truncate them again to the original value type.
  12251. if (PromOp.getOpcode() == ISD::SELECT ||
  12252. PromOp.getOpcode() == ISD::SELECT_CC) {
  12253. auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
  12254. if (SI0 != SelectTruncOp[0].end())
  12255. Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
  12256. auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
  12257. if (SI1 != SelectTruncOp[1].end())
  12258. Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
  12259. }
  12260. DAG.ReplaceAllUsesOfValueWith(PromOp,
  12261. DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
  12262. }
  12263. // Now we're left with the initial extension itself.
  12264. if (!ReallyNeedsExt)
  12265. return N->getOperand(0);
  12266. // To zero extend, just mask off everything except for the first bit (in the
  12267. // i1 case).
  12268. if (N->getOpcode() == ISD::ZERO_EXTEND)
  12269. return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
  12270. DAG.getConstant(APInt::getLowBitsSet(
  12271. N->getValueSizeInBits(0), PromBits),
  12272. dl, N->getValueType(0)));
  12273. assert(N->getOpcode() == ISD::SIGN_EXTEND &&
  12274. "Invalid extension type");
  12275. EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
  12276. SDValue ShiftCst =
  12277. DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
  12278. return DAG.getNode(
  12279. ISD::SRA, dl, N->getValueType(0),
  12280. DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
  12281. ShiftCst);
  12282. }
  12283. SDValue PPCTargetLowering::combineSetCC(SDNode *N,
  12284. DAGCombinerInfo &DCI) const {
  12285. assert(N->getOpcode() == ISD::SETCC &&
  12286. "Should be called with a SETCC node");
  12287. ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
  12288. if (CC == ISD::SETNE || CC == ISD::SETEQ) {
  12289. SDValue LHS = N->getOperand(0);
  12290. SDValue RHS = N->getOperand(1);
  12291. // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
  12292. if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
  12293. LHS.hasOneUse())
  12294. std::swap(LHS, RHS);
  12295. // x == 0-y --> x+y == 0
  12296. // x != 0-y --> x+y != 0
  12297. if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
  12298. RHS.hasOneUse()) {
  12299. SDLoc DL(N);
  12300. SelectionDAG &DAG = DCI.DAG;
  12301. EVT VT = N->getValueType(0);
  12302. EVT OpVT = LHS.getValueType();
  12303. SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
  12304. return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
  12305. }
  12306. }
  12307. return DAGCombineTruncBoolExt(N, DCI);
  12308. }
  12309. // Is this an extending load from an f32 to an f64?
  12310. static bool isFPExtLoad(SDValue Op) {
  12311. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
  12312. return LD->getExtensionType() == ISD::EXTLOAD &&
  12313. Op.getValueType() == MVT::f64;
  12314. return false;
  12315. }
  12316. /// Reduces the number of fp-to-int conversion when building a vector.
  12317. ///
  12318. /// If this vector is built out of floating to integer conversions,
  12319. /// transform it to a vector built out of floating point values followed by a
  12320. /// single floating to integer conversion of the vector.
  12321. /// Namely (build_vector (fptosi $A), (fptosi $B), ...)
  12322. /// becomes (fptosi (build_vector ($A, $B, ...)))
  12323. SDValue PPCTargetLowering::
  12324. combineElementTruncationToVectorTruncation(SDNode *N,
  12325. DAGCombinerInfo &DCI) const {
  12326. assert(N->getOpcode() == ISD::BUILD_VECTOR &&
  12327. "Should be called with a BUILD_VECTOR node");
  12328. SelectionDAG &DAG = DCI.DAG;
  12329. SDLoc dl(N);
  12330. SDValue FirstInput = N->getOperand(0);
  12331. assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
  12332. "The input operand must be an fp-to-int conversion.");
  12333. // This combine happens after legalization so the fp_to_[su]i nodes are
  12334. // already converted to PPCSISD nodes.
  12335. unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
  12336. if (FirstConversion == PPCISD::FCTIDZ ||
  12337. FirstConversion == PPCISD::FCTIDUZ ||
  12338. FirstConversion == PPCISD::FCTIWZ ||
  12339. FirstConversion == PPCISD::FCTIWUZ) {
  12340. bool IsSplat = true;
  12341. bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
  12342. FirstConversion == PPCISD::FCTIWUZ;
  12343. EVT SrcVT = FirstInput.getOperand(0).getValueType();
  12344. SmallVector<SDValue, 4> Ops;
  12345. EVT TargetVT = N->getValueType(0);
  12346. for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
  12347. SDValue NextOp = N->getOperand(i);
  12348. if (NextOp.getOpcode() != PPCISD::MFVSR)
  12349. return SDValue();
  12350. unsigned NextConversion = NextOp.getOperand(0).getOpcode();
  12351. if (NextConversion != FirstConversion)
  12352. return SDValue();
  12353. // If we are converting to 32-bit integers, we need to add an FP_ROUND.
  12354. // This is not valid if the input was originally double precision. It is
  12355. // also not profitable to do unless this is an extending load in which
  12356. // case doing this combine will allow us to combine consecutive loads.
  12357. if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
  12358. return SDValue();
  12359. if (N->getOperand(i) != FirstInput)
  12360. IsSplat = false;
  12361. }
  12362. // If this is a splat, we leave it as-is since there will be only a single
  12363. // fp-to-int conversion followed by a splat of the integer. This is better
  12364. // for 32-bit and smaller ints and neutral for 64-bit ints.
  12365. if (IsSplat)
  12366. return SDValue();
  12367. // Now that we know we have the right type of node, get its operands
  12368. for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
  12369. SDValue In = N->getOperand(i).getOperand(0);
  12370. if (Is32Bit) {
  12371. // For 32-bit values, we need to add an FP_ROUND node (if we made it
  12372. // here, we know that all inputs are extending loads so this is safe).
  12373. if (In.isUndef())
  12374. Ops.push_back(DAG.getUNDEF(SrcVT));
  12375. else {
  12376. SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
  12377. MVT::f32, In.getOperand(0),
  12378. DAG.getIntPtrConstant(1, dl));
  12379. Ops.push_back(Trunc);
  12380. }
  12381. } else
  12382. Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
  12383. }
  12384. unsigned Opcode;
  12385. if (FirstConversion == PPCISD::FCTIDZ ||
  12386. FirstConversion == PPCISD::FCTIWZ)
  12387. Opcode = ISD::FP_TO_SINT;
  12388. else
  12389. Opcode = ISD::FP_TO_UINT;
  12390. EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
  12391. SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
  12392. return DAG.getNode(Opcode, dl, TargetVT, BV);
  12393. }
  12394. return SDValue();
  12395. }
  12396. /// Reduce the number of loads when building a vector.
  12397. ///
  12398. /// Building a vector out of multiple loads can be converted to a load
  12399. /// of the vector type if the loads are consecutive. If the loads are
  12400. /// consecutive but in descending order, a shuffle is added at the end
  12401. /// to reorder the vector.
  12402. static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
  12403. assert(N->getOpcode() == ISD::BUILD_VECTOR &&
  12404. "Should be called with a BUILD_VECTOR node");
  12405. SDLoc dl(N);
  12406. // Return early for non byte-sized type, as they can't be consecutive.
  12407. if (!N->getValueType(0).getVectorElementType().isByteSized())
  12408. return SDValue();
  12409. bool InputsAreConsecutiveLoads = true;
  12410. bool InputsAreReverseConsecutive = true;
  12411. unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
  12412. SDValue FirstInput = N->getOperand(0);
  12413. bool IsRoundOfExtLoad = false;
  12414. if (FirstInput.getOpcode() == ISD::FP_ROUND &&
  12415. FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
  12416. LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
  12417. IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
  12418. }
  12419. // Not a build vector of (possibly fp_rounded) loads.
  12420. if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
  12421. N->getNumOperands() == 1)
  12422. return SDValue();
  12423. for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
  12424. // If any inputs are fp_round(extload), they all must be.
  12425. if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
  12426. return SDValue();
  12427. SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
  12428. N->getOperand(i);
  12429. if (NextInput.getOpcode() != ISD::LOAD)
  12430. return SDValue();
  12431. SDValue PreviousInput =
  12432. IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
  12433. LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
  12434. LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
  12435. // If any inputs are fp_round(extload), they all must be.
  12436. if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
  12437. return SDValue();
  12438. if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
  12439. InputsAreConsecutiveLoads = false;
  12440. if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
  12441. InputsAreReverseConsecutive = false;
  12442. // Exit early if the loads are neither consecutive nor reverse consecutive.
  12443. if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
  12444. return SDValue();
  12445. }
  12446. assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
  12447. "The loads cannot be both consecutive and reverse consecutive.");
  12448. SDValue FirstLoadOp =
  12449. IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
  12450. SDValue LastLoadOp =
  12451. IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
  12452. N->getOperand(N->getNumOperands()-1);
  12453. LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
  12454. LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
  12455. if (InputsAreConsecutiveLoads) {
  12456. assert(LD1 && "Input needs to be a LoadSDNode.");
  12457. return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
  12458. LD1->getBasePtr(), LD1->getPointerInfo(),
  12459. LD1->getAlignment());
  12460. }
  12461. if (InputsAreReverseConsecutive) {
  12462. assert(LDL && "Input needs to be a LoadSDNode.");
  12463. SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
  12464. LDL->getBasePtr(), LDL->getPointerInfo(),
  12465. LDL->getAlignment());
  12466. SmallVector<int, 16> Ops;
  12467. for (int i = N->getNumOperands() - 1; i >= 0; i--)
  12468. Ops.push_back(i);
  12469. return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
  12470. DAG.getUNDEF(N->getValueType(0)), Ops);
  12471. }
  12472. return SDValue();
  12473. }
  12474. // This function adds the required vector_shuffle needed to get
  12475. // the elements of the vector extract in the correct position
  12476. // as specified by the CorrectElems encoding.
  12477. static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
  12478. SDValue Input, uint64_t Elems,
  12479. uint64_t CorrectElems) {
  12480. SDLoc dl(N);
  12481. unsigned NumElems = Input.getValueType().getVectorNumElements();
  12482. SmallVector<int, 16> ShuffleMask(NumElems, -1);
  12483. // Knowing the element indices being extracted from the original
  12484. // vector and the order in which they're being inserted, just put
  12485. // them at element indices required for the instruction.
  12486. for (unsigned i = 0; i < N->getNumOperands(); i++) {
  12487. if (DAG.getDataLayout().isLittleEndian())
  12488. ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
  12489. else
  12490. ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
  12491. CorrectElems = CorrectElems >> 8;
  12492. Elems = Elems >> 8;
  12493. }
  12494. SDValue Shuffle =
  12495. DAG.getVectorShuffle(Input.getValueType(), dl, Input,
  12496. DAG.getUNDEF(Input.getValueType()), ShuffleMask);
  12497. EVT VT = N->getValueType(0);
  12498. SDValue Conv = DAG.getBitcast(VT, Shuffle);
  12499. EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
  12500. Input.getValueType().getVectorElementType(),
  12501. VT.getVectorNumElements());
  12502. return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
  12503. DAG.getValueType(ExtVT));
  12504. }
  12505. // Look for build vector patterns where input operands come from sign
  12506. // extended vector_extract elements of specific indices. If the correct indices
  12507. // aren't used, add a vector shuffle to fix up the indices and create
  12508. // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
  12509. // during instruction selection.
  12510. static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
  12511. // This array encodes the indices that the vector sign extend instructions
  12512. // extract from when extending from one type to another for both BE and LE.
  12513. // The right nibble of each byte corresponds to the LE incides.
  12514. // and the left nibble of each byte corresponds to the BE incides.
  12515. // For example: 0x3074B8FC byte->word
  12516. // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
  12517. // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
  12518. // For example: 0x000070F8 byte->double word
  12519. // For LE: the allowed indices are: 0x0,0x8
  12520. // For BE: the allowed indices are: 0x7,0xF
  12521. uint64_t TargetElems[] = {
  12522. 0x3074B8FC, // b->w
  12523. 0x000070F8, // b->d
  12524. 0x10325476, // h->w
  12525. 0x00003074, // h->d
  12526. 0x00001032, // w->d
  12527. };
  12528. uint64_t Elems = 0;
  12529. int Index;
  12530. SDValue Input;
  12531. auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
  12532. if (!Op)
  12533. return false;
  12534. if (Op.getOpcode() != ISD::SIGN_EXTEND &&
  12535. Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
  12536. return false;
  12537. // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
  12538. // of the right width.
  12539. SDValue Extract = Op.getOperand(0);
  12540. if (Extract.getOpcode() == ISD::ANY_EXTEND)
  12541. Extract = Extract.getOperand(0);
  12542. if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
  12543. return false;
  12544. ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
  12545. if (!ExtOp)
  12546. return false;
  12547. Index = ExtOp->getZExtValue();
  12548. if (Input && Input != Extract.getOperand(0))
  12549. return false;
  12550. if (!Input)
  12551. Input = Extract.getOperand(0);
  12552. Elems = Elems << 8;
  12553. Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
  12554. Elems |= Index;
  12555. return true;
  12556. };
  12557. // If the build vector operands aren't sign extended vector extracts,
  12558. // of the same input vector, then return.
  12559. for (unsigned i = 0; i < N->getNumOperands(); i++) {
  12560. if (!isSExtOfVecExtract(N->getOperand(i))) {
  12561. return SDValue();
  12562. }
  12563. }
  12564. // If the vector extract indicies are not correct, add the appropriate
  12565. // vector_shuffle.
  12566. int TgtElemArrayIdx;
  12567. int InputSize = Input.getValueType().getScalarSizeInBits();
  12568. int OutputSize = N->getValueType(0).getScalarSizeInBits();
  12569. if (InputSize + OutputSize == 40)
  12570. TgtElemArrayIdx = 0;
  12571. else if (InputSize + OutputSize == 72)
  12572. TgtElemArrayIdx = 1;
  12573. else if (InputSize + OutputSize == 48)
  12574. TgtElemArrayIdx = 2;
  12575. else if (InputSize + OutputSize == 80)
  12576. TgtElemArrayIdx = 3;
  12577. else if (InputSize + OutputSize == 96)
  12578. TgtElemArrayIdx = 4;
  12579. else
  12580. return SDValue();
  12581. uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
  12582. CorrectElems = DAG.getDataLayout().isLittleEndian()
  12583. ? CorrectElems & 0x0F0F0F0F0F0F0F0F
  12584. : CorrectElems & 0xF0F0F0F0F0F0F0F0;
  12585. if (Elems != CorrectElems) {
  12586. return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
  12587. }
  12588. // Regular lowering will catch cases where a shuffle is not needed.
  12589. return SDValue();
  12590. }
  12591. // Look for the pattern of a load from a narrow width to i128, feeding
  12592. // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
  12593. // (LXVRZX). This node represents a zero extending load that will be matched
  12594. // to the Load VSX Vector Rightmost instructions.
  12595. static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
  12596. SDLoc DL(N);
  12597. // This combine is only eligible for a BUILD_VECTOR of v1i128.
  12598. if (N->getValueType(0) != MVT::v1i128)
  12599. return SDValue();
  12600. SDValue Operand = N->getOperand(0);
  12601. // Proceed with the transformation if the operand to the BUILD_VECTOR
  12602. // is a load instruction.
  12603. if (Operand.getOpcode() != ISD::LOAD)
  12604. return SDValue();
  12605. auto *LD = cast<LoadSDNode>(Operand);
  12606. EVT MemoryType = LD->getMemoryVT();
  12607. // This transformation is only valid if the we are loading either a byte,
  12608. // halfword, word, or doubleword.
  12609. bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
  12610. MemoryType == MVT::i32 || MemoryType == MVT::i64;
  12611. // Ensure that the load from the narrow width is being zero extended to i128.
  12612. if (!ValidLDType ||
  12613. (LD->getExtensionType() != ISD::ZEXTLOAD &&
  12614. LD->getExtensionType() != ISD::EXTLOAD))
  12615. return SDValue();
  12616. SDValue LoadOps[] = {
  12617. LD->getChain(), LD->getBasePtr(),
  12618. DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
  12619. return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
  12620. DAG.getVTList(MVT::v1i128, MVT::Other),
  12621. LoadOps, MemoryType, LD->getMemOperand());
  12622. }
  12623. SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
  12624. DAGCombinerInfo &DCI) const {
  12625. assert(N->getOpcode() == ISD::BUILD_VECTOR &&
  12626. "Should be called with a BUILD_VECTOR node");
  12627. SelectionDAG &DAG = DCI.DAG;
  12628. SDLoc dl(N);
  12629. if (!Subtarget.hasVSX())
  12630. return SDValue();
  12631. // The target independent DAG combiner will leave a build_vector of
  12632. // float-to-int conversions intact. We can generate MUCH better code for
  12633. // a float-to-int conversion of a vector of floats.
  12634. SDValue FirstInput = N->getOperand(0);
  12635. if (FirstInput.getOpcode() == PPCISD::MFVSR) {
  12636. SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
  12637. if (Reduced)
  12638. return Reduced;
  12639. }
  12640. // If we're building a vector out of consecutive loads, just load that
  12641. // vector type.
  12642. SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
  12643. if (Reduced)
  12644. return Reduced;
  12645. // If we're building a vector out of extended elements from another vector
  12646. // we have P9 vector integer extend instructions. The code assumes legal
  12647. // input types (i.e. it can't handle things like v4i16) so do not run before
  12648. // legalization.
  12649. if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
  12650. Reduced = combineBVOfVecSExt(N, DAG);
  12651. if (Reduced)
  12652. return Reduced;
  12653. }
  12654. // On Power10, the Load VSX Vector Rightmost instructions can be utilized
  12655. // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
  12656. // is a load from <valid narrow width> to i128.
  12657. if (Subtarget.isISA3_1()) {
  12658. SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
  12659. if (BVOfZLoad)
  12660. return BVOfZLoad;
  12661. }
  12662. if (N->getValueType(0) != MVT::v2f64)
  12663. return SDValue();
  12664. // Looking for:
  12665. // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
  12666. if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
  12667. FirstInput.getOpcode() != ISD::UINT_TO_FP)
  12668. return SDValue();
  12669. if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
  12670. N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
  12671. return SDValue();
  12672. if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
  12673. return SDValue();
  12674. SDValue Ext1 = FirstInput.getOperand(0);
  12675. SDValue Ext2 = N->getOperand(1).getOperand(0);
  12676. if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  12677. Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
  12678. return SDValue();
  12679. ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
  12680. ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
  12681. if (!Ext1Op || !Ext2Op)
  12682. return SDValue();
  12683. if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
  12684. Ext1.getOperand(0) != Ext2.getOperand(0))
  12685. return SDValue();
  12686. int FirstElem = Ext1Op->getZExtValue();
  12687. int SecondElem = Ext2Op->getZExtValue();
  12688. int SubvecIdx;
  12689. if (FirstElem == 0 && SecondElem == 1)
  12690. SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
  12691. else if (FirstElem == 2 && SecondElem == 3)
  12692. SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
  12693. else
  12694. return SDValue();
  12695. SDValue SrcVec = Ext1.getOperand(0);
  12696. auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
  12697. PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
  12698. return DAG.getNode(NodeType, dl, MVT::v2f64,
  12699. SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
  12700. }
  12701. SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
  12702. DAGCombinerInfo &DCI) const {
  12703. assert((N->getOpcode() == ISD::SINT_TO_FP ||
  12704. N->getOpcode() == ISD::UINT_TO_FP) &&
  12705. "Need an int -> FP conversion node here");
  12706. if (useSoftFloat() || !Subtarget.has64BitSupport())
  12707. return SDValue();
  12708. SelectionDAG &DAG = DCI.DAG;
  12709. SDLoc dl(N);
  12710. SDValue Op(N, 0);
  12711. // Don't handle ppc_fp128 here or conversions that are out-of-range capable
  12712. // from the hardware.
  12713. if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
  12714. return SDValue();
  12715. if (!Op.getOperand(0).getValueType().isSimple())
  12716. return SDValue();
  12717. if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
  12718. Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
  12719. return SDValue();
  12720. SDValue FirstOperand(Op.getOperand(0));
  12721. bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
  12722. (FirstOperand.getValueType() == MVT::i8 ||
  12723. FirstOperand.getValueType() == MVT::i16);
  12724. if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
  12725. bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
  12726. bool DstDouble = Op.getValueType() == MVT::f64;
  12727. unsigned ConvOp = Signed ?
  12728. (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
  12729. (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
  12730. SDValue WidthConst =
  12731. DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
  12732. dl, false);
  12733. LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
  12734. SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
  12735. SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
  12736. DAG.getVTList(MVT::f64, MVT::Other),
  12737. Ops, MVT::i8, LDN->getMemOperand());
  12738. // For signed conversion, we need to sign-extend the value in the VSR
  12739. if (Signed) {
  12740. SDValue ExtOps[] = { Ld, WidthConst };
  12741. SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
  12742. return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
  12743. } else
  12744. return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
  12745. }
  12746. // For i32 intermediate values, unfortunately, the conversion functions
  12747. // leave the upper 32 bits of the value are undefined. Within the set of
  12748. // scalar instructions, we have no method for zero- or sign-extending the
  12749. // value. Thus, we cannot handle i32 intermediate values here.
  12750. if (Op.getOperand(0).getValueType() == MVT::i32)
  12751. return SDValue();
  12752. assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
  12753. "UINT_TO_FP is supported only with FPCVT");
  12754. // If we have FCFIDS, then use it when converting to single-precision.
  12755. // Otherwise, convert to double-precision and then round.
  12756. unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
  12757. ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
  12758. : PPCISD::FCFIDS)
  12759. : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
  12760. : PPCISD::FCFID);
  12761. MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
  12762. ? MVT::f32
  12763. : MVT::f64;
  12764. // If we're converting from a float, to an int, and back to a float again,
  12765. // then we don't need the store/load pair at all.
  12766. if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
  12767. Subtarget.hasFPCVT()) ||
  12768. (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
  12769. SDValue Src = Op.getOperand(0).getOperand(0);
  12770. if (Src.getValueType() == MVT::f32) {
  12771. Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
  12772. DCI.AddToWorklist(Src.getNode());
  12773. } else if (Src.getValueType() != MVT::f64) {
  12774. // Make sure that we don't pick up a ppc_fp128 source value.
  12775. return SDValue();
  12776. }
  12777. unsigned FCTOp =
  12778. Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
  12779. PPCISD::FCTIDUZ;
  12780. SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
  12781. SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
  12782. if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
  12783. FP = DAG.getNode(ISD::FP_ROUND, dl,
  12784. MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
  12785. DCI.AddToWorklist(FP.getNode());
  12786. }
  12787. return FP;
  12788. }
  12789. return SDValue();
  12790. }
  12791. // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
  12792. // builtins) into loads with swaps.
  12793. SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
  12794. DAGCombinerInfo &DCI) const {
  12795. SelectionDAG &DAG = DCI.DAG;
  12796. SDLoc dl(N);
  12797. SDValue Chain;
  12798. SDValue Base;
  12799. MachineMemOperand *MMO;
  12800. switch (N->getOpcode()) {
  12801. default:
  12802. llvm_unreachable("Unexpected opcode for little endian VSX load");
  12803. case ISD::LOAD: {
  12804. LoadSDNode *LD = cast<LoadSDNode>(N);
  12805. Chain = LD->getChain();
  12806. Base = LD->getBasePtr();
  12807. MMO = LD->getMemOperand();
  12808. // If the MMO suggests this isn't a load of a full vector, leave
  12809. // things alone. For a built-in, we have to make the change for
  12810. // correctness, so if there is a size problem that will be a bug.
  12811. if (MMO->getSize() < 16)
  12812. return SDValue();
  12813. break;
  12814. }
  12815. case ISD::INTRINSIC_W_CHAIN: {
  12816. MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
  12817. Chain = Intrin->getChain();
  12818. // Similarly to the store case below, Intrin->getBasePtr() doesn't get
  12819. // us what we want. Get operand 2 instead.
  12820. Base = Intrin->getOperand(2);
  12821. MMO = Intrin->getMemOperand();
  12822. break;
  12823. }
  12824. }
  12825. MVT VecTy = N->getValueType(0).getSimpleVT();
  12826. // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
  12827. // aligned and the type is a vector with elements up to 4 bytes
  12828. if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
  12829. VecTy.getScalarSizeInBits() <= 32) {
  12830. return SDValue();
  12831. }
  12832. SDValue LoadOps[] = { Chain, Base };
  12833. SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
  12834. DAG.getVTList(MVT::v2f64, MVT::Other),
  12835. LoadOps, MVT::v2f64, MMO);
  12836. DCI.AddToWorklist(Load.getNode());
  12837. Chain = Load.getValue(1);
  12838. SDValue Swap = DAG.getNode(
  12839. PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
  12840. DCI.AddToWorklist(Swap.getNode());
  12841. // Add a bitcast if the resulting load type doesn't match v2f64.
  12842. if (VecTy != MVT::v2f64) {
  12843. SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
  12844. DCI.AddToWorklist(N.getNode());
  12845. // Package {bitcast value, swap's chain} to match Load's shape.
  12846. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
  12847. N, Swap.getValue(1));
  12848. }
  12849. return Swap;
  12850. }
  12851. // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
  12852. // builtins) into stores with swaps.
  12853. SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
  12854. DAGCombinerInfo &DCI) const {
  12855. SelectionDAG &DAG = DCI.DAG;
  12856. SDLoc dl(N);
  12857. SDValue Chain;
  12858. SDValue Base;
  12859. unsigned SrcOpnd;
  12860. MachineMemOperand *MMO;
  12861. switch (N->getOpcode()) {
  12862. default:
  12863. llvm_unreachable("Unexpected opcode for little endian VSX store");
  12864. case ISD::STORE: {
  12865. StoreSDNode *ST = cast<StoreSDNode>(N);
  12866. Chain = ST->getChain();
  12867. Base = ST->getBasePtr();
  12868. MMO = ST->getMemOperand();
  12869. SrcOpnd = 1;
  12870. // If the MMO suggests this isn't a store of a full vector, leave
  12871. // things alone. For a built-in, we have to make the change for
  12872. // correctness, so if there is a size problem that will be a bug.
  12873. if (MMO->getSize() < 16)
  12874. return SDValue();
  12875. break;
  12876. }
  12877. case ISD::INTRINSIC_VOID: {
  12878. MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
  12879. Chain = Intrin->getChain();
  12880. // Intrin->getBasePtr() oddly does not get what we want.
  12881. Base = Intrin->getOperand(3);
  12882. MMO = Intrin->getMemOperand();
  12883. SrcOpnd = 2;
  12884. break;
  12885. }
  12886. }
  12887. SDValue Src = N->getOperand(SrcOpnd);
  12888. MVT VecTy = Src.getValueType().getSimpleVT();
  12889. // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
  12890. // aligned and the type is a vector with elements up to 4 bytes
  12891. if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
  12892. VecTy.getScalarSizeInBits() <= 32) {
  12893. return SDValue();
  12894. }
  12895. // All stores are done as v2f64 and possible bit cast.
  12896. if (VecTy != MVT::v2f64) {
  12897. Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
  12898. DCI.AddToWorklist(Src.getNode());
  12899. }
  12900. SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
  12901. DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
  12902. DCI.AddToWorklist(Swap.getNode());
  12903. Chain = Swap.getValue(1);
  12904. SDValue StoreOps[] = { Chain, Swap, Base };
  12905. SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
  12906. DAG.getVTList(MVT::Other),
  12907. StoreOps, VecTy, MMO);
  12908. DCI.AddToWorklist(Store.getNode());
  12909. return Store;
  12910. }
  12911. // Handle DAG combine for STORE (FP_TO_INT F).
  12912. SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
  12913. DAGCombinerInfo &DCI) const {
  12914. SelectionDAG &DAG = DCI.DAG;
  12915. SDLoc dl(N);
  12916. unsigned Opcode = N->getOperand(1).getOpcode();
  12917. assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
  12918. && "Not a FP_TO_INT Instruction!");
  12919. SDValue Val = N->getOperand(1).getOperand(0);
  12920. EVT Op1VT = N->getOperand(1).getValueType();
  12921. EVT ResVT = Val.getValueType();
  12922. if (!isTypeLegal(ResVT))
  12923. return SDValue();
  12924. // Only perform combine for conversion to i64/i32 or power9 i16/i8.
  12925. bool ValidTypeForStoreFltAsInt =
  12926. (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
  12927. (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
  12928. if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
  12929. return SDValue();
  12930. if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
  12931. cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
  12932. return SDValue();
  12933. // Extend f32 values to f64
  12934. if (ResVT.getScalarSizeInBits() == 32) {
  12935. Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
  12936. DCI.AddToWorklist(Val.getNode());
  12937. }
  12938. // Set signed or unsigned conversion opcode.
  12939. unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
  12940. PPCISD::FP_TO_SINT_IN_VSR :
  12941. PPCISD::FP_TO_UINT_IN_VSR;
  12942. Val = DAG.getNode(ConvOpcode,
  12943. dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
  12944. DCI.AddToWorklist(Val.getNode());
  12945. // Set number of bytes being converted.
  12946. unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
  12947. SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
  12948. DAG.getIntPtrConstant(ByteSize, dl, false),
  12949. DAG.getValueType(Op1VT) };
  12950. Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
  12951. DAG.getVTList(MVT::Other), Ops,
  12952. cast<StoreSDNode>(N)->getMemoryVT(),
  12953. cast<StoreSDNode>(N)->getMemOperand());
  12954. DCI.AddToWorklist(Val.getNode());
  12955. return Val;
  12956. }
  12957. static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
  12958. // Check that the source of the element keeps flipping
  12959. // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
  12960. bool PrevElemFromFirstVec = Mask[0] < NumElts;
  12961. for (int i = 1, e = Mask.size(); i < e; i++) {
  12962. if (PrevElemFromFirstVec && Mask[i] < NumElts)
  12963. return false;
  12964. if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
  12965. return false;
  12966. PrevElemFromFirstVec = !PrevElemFromFirstVec;
  12967. }
  12968. return true;
  12969. }
  12970. static bool isSplatBV(SDValue Op) {
  12971. if (Op.getOpcode() != ISD::BUILD_VECTOR)
  12972. return false;
  12973. SDValue FirstOp;
  12974. // Find first non-undef input.
  12975. for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
  12976. FirstOp = Op.getOperand(i);
  12977. if (!FirstOp.isUndef())
  12978. break;
  12979. }
  12980. // All inputs are undef or the same as the first non-undef input.
  12981. for (int i = 1, e = Op.getNumOperands(); i < e; i++)
  12982. if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
  12983. return false;
  12984. return true;
  12985. }
  12986. static SDValue isScalarToVec(SDValue Op) {
  12987. if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
  12988. return Op;
  12989. if (Op.getOpcode() != ISD::BITCAST)
  12990. return SDValue();
  12991. Op = Op.getOperand(0);
  12992. if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
  12993. return Op;
  12994. return SDValue();
  12995. }
  12996. // Fix up the shuffle mask to account for the fact that the result of
  12997. // scalar_to_vector is not in lane zero. This just takes all values in
  12998. // the ranges specified by the min/max indices and adds the number of
  12999. // elements required to ensure each element comes from the respective
  13000. // position in the valid lane.
  13001. // On little endian, that's just the corresponding element in the other
  13002. // half of the vector. On big endian, it is in the same half but right
  13003. // justified rather than left justified in that half.
  13004. static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
  13005. int LHSMaxIdx, int RHSMinIdx,
  13006. int RHSMaxIdx, int HalfVec,
  13007. unsigned ValidLaneWidth,
  13008. const PPCSubtarget &Subtarget) {
  13009. for (int i = 0, e = ShuffV.size(); i < e; i++) {
  13010. int Idx = ShuffV[i];
  13011. if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
  13012. ShuffV[i] +=
  13013. Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
  13014. }
  13015. }
  13016. // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
  13017. // the original is:
  13018. // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
  13019. // In such a case, just change the shuffle mask to extract the element
  13020. // from the permuted index.
  13021. static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
  13022. const PPCSubtarget &Subtarget) {
  13023. SDLoc dl(OrigSToV);
  13024. EVT VT = OrigSToV.getValueType();
  13025. assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
  13026. "Expecting a SCALAR_TO_VECTOR here");
  13027. SDValue Input = OrigSToV.getOperand(0);
  13028. if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
  13029. ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
  13030. SDValue OrigVector = Input.getOperand(0);
  13031. // Can't handle non-const element indices or different vector types
  13032. // for the input to the extract and the output of the scalar_to_vector.
  13033. if (Idx && VT == OrigVector.getValueType()) {
  13034. unsigned NumElts = VT.getVectorNumElements();
  13035. assert(
  13036. NumElts > 1 &&
  13037. "Cannot produce a permuted scalar_to_vector for one element vector");
  13038. SmallVector<int, 16> NewMask(NumElts, -1);
  13039. unsigned ResultInElt = NumElts / 2;
  13040. ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
  13041. NewMask[ResultInElt] = Idx->getZExtValue();
  13042. return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
  13043. }
  13044. }
  13045. return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
  13046. OrigSToV.getOperand(0));
  13047. }
  13048. // On little endian subtargets, combine shuffles such as:
  13049. // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
  13050. // into:
  13051. // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
  13052. // because the latter can be matched to a single instruction merge.
  13053. // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
  13054. // to put the value into element zero. Adjust the shuffle mask so that the
  13055. // vector can remain in permuted form (to prevent a swap prior to a shuffle).
  13056. // On big endian targets, this is still useful for SCALAR_TO_VECTOR
  13057. // nodes with elements smaller than doubleword because all the ways
  13058. // of getting scalar data into a vector register put the value in the
  13059. // rightmost element of the left half of the vector.
  13060. SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
  13061. SelectionDAG &DAG) const {
  13062. SDValue LHS = SVN->getOperand(0);
  13063. SDValue RHS = SVN->getOperand(1);
  13064. auto Mask = SVN->getMask();
  13065. int NumElts = LHS.getValueType().getVectorNumElements();
  13066. SDValue Res(SVN, 0);
  13067. SDLoc dl(SVN);
  13068. bool IsLittleEndian = Subtarget.isLittleEndian();
  13069. // On big endian targets this is only useful for subtargets with direct moves.
  13070. // On little endian targets it would be useful for all subtargets with VSX.
  13071. // However adding special handling for LE subtargets without direct moves
  13072. // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
  13073. // which includes direct moves.
  13074. if (!Subtarget.hasDirectMove())
  13075. return Res;
  13076. // If this is not a shuffle of a shuffle and the first element comes from
  13077. // the second vector, canonicalize to the commuted form. This will make it
  13078. // more likely to match one of the single instruction patterns.
  13079. if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
  13080. RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
  13081. std::swap(LHS, RHS);
  13082. Res = DAG.getCommutedVectorShuffle(*SVN);
  13083. Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
  13084. }
  13085. // Adjust the shuffle mask if either input vector comes from a
  13086. // SCALAR_TO_VECTOR and keep the respective input vector in permuted
  13087. // form (to prevent the need for a swap).
  13088. SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
  13089. SDValue SToVLHS = isScalarToVec(LHS);
  13090. SDValue SToVRHS = isScalarToVec(RHS);
  13091. if (SToVLHS || SToVRHS) {
  13092. int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
  13093. : SToVRHS.getValueType().getVectorNumElements();
  13094. int NumEltsOut = ShuffV.size();
  13095. // The width of the "valid lane" (i.e. the lane that contains the value that
  13096. // is vectorized) needs to be expressed in terms of the number of elements
  13097. // of the shuffle. It is thereby the ratio of the values before and after
  13098. // any bitcast.
  13099. unsigned ValidLaneWidth =
  13100. SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
  13101. LHS.getValueType().getScalarSizeInBits()
  13102. : SToVRHS.getValueType().getScalarSizeInBits() /
  13103. RHS.getValueType().getScalarSizeInBits();
  13104. // Initially assume that neither input is permuted. These will be adjusted
  13105. // accordingly if either input is.
  13106. int LHSMaxIdx = -1;
  13107. int RHSMinIdx = -1;
  13108. int RHSMaxIdx = -1;
  13109. int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
  13110. // Get the permuted scalar to vector nodes for the source(s) that come from
  13111. // ISD::SCALAR_TO_VECTOR.
  13112. // On big endian systems, this only makes sense for element sizes smaller
  13113. // than 64 bits since for 64-bit elements, all instructions already put
  13114. // the value into element zero. Since scalar size of LHS and RHS may differ
  13115. // after isScalarToVec, this should be checked using their own sizes.
  13116. if (SToVLHS) {
  13117. if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
  13118. return Res;
  13119. // Set up the values for the shuffle vector fixup.
  13120. LHSMaxIdx = NumEltsOut / NumEltsIn;
  13121. SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
  13122. if (SToVLHS.getValueType() != LHS.getValueType())
  13123. SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
  13124. LHS = SToVLHS;
  13125. }
  13126. if (SToVRHS) {
  13127. if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
  13128. return Res;
  13129. RHSMinIdx = NumEltsOut;
  13130. RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
  13131. SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
  13132. if (SToVRHS.getValueType() != RHS.getValueType())
  13133. SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
  13134. RHS = SToVRHS;
  13135. }
  13136. // Fix up the shuffle mask to reflect where the desired element actually is.
  13137. // The minimum and maximum indices that correspond to element zero for both
  13138. // the LHS and RHS are computed and will control which shuffle mask entries
  13139. // are to be changed. For example, if the RHS is permuted, any shuffle mask
  13140. // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
  13141. fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
  13142. HalfVec, ValidLaneWidth, Subtarget);
  13143. Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
  13144. // We may have simplified away the shuffle. We won't be able to do anything
  13145. // further with it here.
  13146. if (!isa<ShuffleVectorSDNode>(Res))
  13147. return Res;
  13148. Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
  13149. }
  13150. SDValue TheSplat = IsLittleEndian ? RHS : LHS;
  13151. // The common case after we commuted the shuffle is that the RHS is a splat
  13152. // and we have elements coming in from the splat at indices that are not
  13153. // conducive to using a merge.
  13154. // Example:
  13155. // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
  13156. if (!isSplatBV(TheSplat))
  13157. return Res;
  13158. // We are looking for a mask such that all even elements are from
  13159. // one vector and all odd elements from the other.
  13160. if (!isAlternatingShuffMask(Mask, NumElts))
  13161. return Res;
  13162. // Adjust the mask so we are pulling in the same index from the splat
  13163. // as the index from the interesting vector in consecutive elements.
  13164. if (IsLittleEndian) {
  13165. // Example (even elements from first vector):
  13166. // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
  13167. if (Mask[0] < NumElts)
  13168. for (int i = 1, e = Mask.size(); i < e; i += 2)
  13169. ShuffV[i] = (ShuffV[i - 1] + NumElts);
  13170. // Example (odd elements from first vector):
  13171. // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
  13172. else
  13173. for (int i = 0, e = Mask.size(); i < e; i += 2)
  13174. ShuffV[i] = (ShuffV[i + 1] + NumElts);
  13175. } else {
  13176. // Example (even elements from first vector):
  13177. // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
  13178. if (Mask[0] < NumElts)
  13179. for (int i = 0, e = Mask.size(); i < e; i += 2)
  13180. ShuffV[i] = ShuffV[i + 1] - NumElts;
  13181. // Example (odd elements from first vector):
  13182. // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
  13183. else
  13184. for (int i = 1, e = Mask.size(); i < e; i += 2)
  13185. ShuffV[i] = ShuffV[i - 1] - NumElts;
  13186. }
  13187. // If the RHS has undefs, we need to remove them since we may have created
  13188. // a shuffle that adds those instead of the splat value.
  13189. SDValue SplatVal =
  13190. cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
  13191. TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
  13192. if (IsLittleEndian)
  13193. RHS = TheSplat;
  13194. else
  13195. LHS = TheSplat;
  13196. return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
  13197. }
  13198. SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
  13199. LSBaseSDNode *LSBase,
  13200. DAGCombinerInfo &DCI) const {
  13201. assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
  13202. "Not a reverse memop pattern!");
  13203. auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
  13204. auto Mask = SVN->getMask();
  13205. int i = 0;
  13206. auto I = Mask.rbegin();
  13207. auto E = Mask.rend();
  13208. for (; I != E; ++I) {
  13209. if (*I != i)
  13210. return false;
  13211. i++;
  13212. }
  13213. return true;
  13214. };
  13215. SelectionDAG &DAG = DCI.DAG;
  13216. EVT VT = SVN->getValueType(0);
  13217. if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
  13218. return SDValue();
  13219. // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
  13220. // See comment in PPCVSXSwapRemoval.cpp.
  13221. // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
  13222. if (!Subtarget.hasP9Vector())
  13223. return SDValue();
  13224. if(!IsElementReverse(SVN))
  13225. return SDValue();
  13226. if (LSBase->getOpcode() == ISD::LOAD) {
  13227. // If the load return value 0 has more than one user except the
  13228. // shufflevector instruction, it is not profitable to replace the
  13229. // shufflevector with a reverse load.
  13230. for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
  13231. UI != UE; ++UI)
  13232. if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
  13233. return SDValue();
  13234. SDLoc dl(LSBase);
  13235. SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
  13236. return DAG.getMemIntrinsicNode(
  13237. PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
  13238. LSBase->getMemoryVT(), LSBase->getMemOperand());
  13239. }
  13240. if (LSBase->getOpcode() == ISD::STORE) {
  13241. // If there are other uses of the shuffle, the swap cannot be avoided.
  13242. // Forcing the use of an X-Form (since swapped stores only have
  13243. // X-Forms) without removing the swap is unprofitable.
  13244. if (!SVN->hasOneUse())
  13245. return SDValue();
  13246. SDLoc dl(LSBase);
  13247. SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
  13248. LSBase->getBasePtr()};
  13249. return DAG.getMemIntrinsicNode(
  13250. PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
  13251. LSBase->getMemoryVT(), LSBase->getMemOperand());
  13252. }
  13253. llvm_unreachable("Expected a load or store node here");
  13254. }
  13255. SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
  13256. DAGCombinerInfo &DCI) const {
  13257. SelectionDAG &DAG = DCI.DAG;
  13258. SDLoc dl(N);
  13259. switch (N->getOpcode()) {
  13260. default: break;
  13261. case ISD::ADD:
  13262. return combineADD(N, DCI);
  13263. case ISD::SHL:
  13264. return combineSHL(N, DCI);
  13265. case ISD::SRA:
  13266. return combineSRA(N, DCI);
  13267. case ISD::SRL:
  13268. return combineSRL(N, DCI);
  13269. case ISD::MUL:
  13270. return combineMUL(N, DCI);
  13271. case ISD::FMA:
  13272. case PPCISD::FNMSUB:
  13273. return combineFMALike(N, DCI);
  13274. case PPCISD::SHL:
  13275. if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
  13276. return N->getOperand(0);
  13277. break;
  13278. case PPCISD::SRL:
  13279. if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
  13280. return N->getOperand(0);
  13281. break;
  13282. case PPCISD::SRA:
  13283. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
  13284. if (C->isZero() || // 0 >>s V -> 0.
  13285. C->isAllOnes()) // -1 >>s V -> -1.
  13286. return N->getOperand(0);
  13287. }
  13288. break;
  13289. case ISD::SIGN_EXTEND:
  13290. case ISD::ZERO_EXTEND:
  13291. case ISD::ANY_EXTEND:
  13292. return DAGCombineExtBoolTrunc(N, DCI);
  13293. case ISD::TRUNCATE:
  13294. return combineTRUNCATE(N, DCI);
  13295. case ISD::SETCC:
  13296. if (SDValue CSCC = combineSetCC(N, DCI))
  13297. return CSCC;
  13298. LLVM_FALLTHROUGH;
  13299. case ISD::SELECT_CC:
  13300. return DAGCombineTruncBoolExt(N, DCI);
  13301. case ISD::SINT_TO_FP:
  13302. case ISD::UINT_TO_FP:
  13303. return combineFPToIntToFP(N, DCI);
  13304. case ISD::VECTOR_SHUFFLE:
  13305. if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
  13306. LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
  13307. return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
  13308. }
  13309. return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
  13310. case ISD::STORE: {
  13311. EVT Op1VT = N->getOperand(1).getValueType();
  13312. unsigned Opcode = N->getOperand(1).getOpcode();
  13313. if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
  13314. SDValue Val= combineStoreFPToInt(N, DCI);
  13315. if (Val)
  13316. return Val;
  13317. }
  13318. if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
  13319. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
  13320. SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
  13321. if (Val)
  13322. return Val;
  13323. }
  13324. // Turn STORE (BSWAP) -> sthbrx/stwbrx.
  13325. if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
  13326. N->getOperand(1).getNode()->hasOneUse() &&
  13327. (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
  13328. (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
  13329. // STBRX can only handle simple types and it makes no sense to store less
  13330. // two bytes in byte-reversed order.
  13331. EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
  13332. if (mVT.isExtended() || mVT.getSizeInBits() < 16)
  13333. break;
  13334. SDValue BSwapOp = N->getOperand(1).getOperand(0);
  13335. // Do an any-extend to 32-bits if this is a half-word input.
  13336. if (BSwapOp.getValueType() == MVT::i16)
  13337. BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
  13338. // If the type of BSWAP operand is wider than stored memory width
  13339. // it need to be shifted to the right side before STBRX.
  13340. if (Op1VT.bitsGT(mVT)) {
  13341. int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
  13342. BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
  13343. DAG.getConstant(Shift, dl, MVT::i32));
  13344. // Need to truncate if this is a bswap of i64 stored as i32/i16.
  13345. if (Op1VT == MVT::i64)
  13346. BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
  13347. }
  13348. SDValue Ops[] = {
  13349. N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
  13350. };
  13351. return
  13352. DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
  13353. Ops, cast<StoreSDNode>(N)->getMemoryVT(),
  13354. cast<StoreSDNode>(N)->getMemOperand());
  13355. }
  13356. // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0>
  13357. // So it can increase the chance of CSE constant construction.
  13358. if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
  13359. isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
  13360. // Need to sign-extended to 64-bits to handle negative values.
  13361. EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
  13362. uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
  13363. MemVT.getSizeInBits());
  13364. SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
  13365. // DAG.getTruncStore() can't be used here because it doesn't accept
  13366. // the general (base + offset) addressing mode.
  13367. // So we use UpdateNodeOperands and setTruncatingStore instead.
  13368. DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
  13369. N->getOperand(3));
  13370. cast<StoreSDNode>(N)->setTruncatingStore(true);
  13371. return SDValue(N, 0);
  13372. }
  13373. // For little endian, VSX stores require generating xxswapd/lxvd2x.
  13374. // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
  13375. if (Op1VT.isSimple()) {
  13376. MVT StoreVT = Op1VT.getSimpleVT();
  13377. if (Subtarget.needsSwapsForVSXMemOps() &&
  13378. (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
  13379. StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
  13380. return expandVSXStoreForLE(N, DCI);
  13381. }
  13382. break;
  13383. }
  13384. case ISD::LOAD: {
  13385. LoadSDNode *LD = cast<LoadSDNode>(N);
  13386. EVT VT = LD->getValueType(0);
  13387. // For little endian, VSX loads require generating lxvd2x/xxswapd.
  13388. // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
  13389. if (VT.isSimple()) {
  13390. MVT LoadVT = VT.getSimpleVT();
  13391. if (Subtarget.needsSwapsForVSXMemOps() &&
  13392. (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
  13393. LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
  13394. return expandVSXLoadForLE(N, DCI);
  13395. }
  13396. // We sometimes end up with a 64-bit integer load, from which we extract
  13397. // two single-precision floating-point numbers. This happens with
  13398. // std::complex<float>, and other similar structures, because of the way we
  13399. // canonicalize structure copies. However, if we lack direct moves,
  13400. // then the final bitcasts from the extracted integer values to the
  13401. // floating-point numbers turn into store/load pairs. Even with direct moves,
  13402. // just loading the two floating-point numbers is likely better.
  13403. auto ReplaceTwoFloatLoad = [&]() {
  13404. if (VT != MVT::i64)
  13405. return false;
  13406. if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
  13407. LD->isVolatile())
  13408. return false;
  13409. // We're looking for a sequence like this:
  13410. // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
  13411. // t16: i64 = srl t13, Constant:i32<32>
  13412. // t17: i32 = truncate t16
  13413. // t18: f32 = bitcast t17
  13414. // t19: i32 = truncate t13
  13415. // t20: f32 = bitcast t19
  13416. if (!LD->hasNUsesOfValue(2, 0))
  13417. return false;
  13418. auto UI = LD->use_begin();
  13419. while (UI.getUse().getResNo() != 0) ++UI;
  13420. SDNode *Trunc = *UI++;
  13421. while (UI.getUse().getResNo() != 0) ++UI;
  13422. SDNode *RightShift = *UI;
  13423. if (Trunc->getOpcode() != ISD::TRUNCATE)
  13424. std::swap(Trunc, RightShift);
  13425. if (Trunc->getOpcode() != ISD::TRUNCATE ||
  13426. Trunc->getValueType(0) != MVT::i32 ||
  13427. !Trunc->hasOneUse())
  13428. return false;
  13429. if (RightShift->getOpcode() != ISD::SRL ||
  13430. !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
  13431. RightShift->getConstantOperandVal(1) != 32 ||
  13432. !RightShift->hasOneUse())
  13433. return false;
  13434. SDNode *Trunc2 = *RightShift->use_begin();
  13435. if (Trunc2->getOpcode() != ISD::TRUNCATE ||
  13436. Trunc2->getValueType(0) != MVT::i32 ||
  13437. !Trunc2->hasOneUse())
  13438. return false;
  13439. SDNode *Bitcast = *Trunc->use_begin();
  13440. SDNode *Bitcast2 = *Trunc2->use_begin();
  13441. if (Bitcast->getOpcode() != ISD::BITCAST ||
  13442. Bitcast->getValueType(0) != MVT::f32)
  13443. return false;
  13444. if (Bitcast2->getOpcode() != ISD::BITCAST ||
  13445. Bitcast2->getValueType(0) != MVT::f32)
  13446. return false;
  13447. if (Subtarget.isLittleEndian())
  13448. std::swap(Bitcast, Bitcast2);
  13449. // Bitcast has the second float (in memory-layout order) and Bitcast2
  13450. // has the first one.
  13451. SDValue BasePtr = LD->getBasePtr();
  13452. if (LD->isIndexed()) {
  13453. assert(LD->getAddressingMode() == ISD::PRE_INC &&
  13454. "Non-pre-inc AM on PPC?");
  13455. BasePtr =
  13456. DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
  13457. LD->getOffset());
  13458. }
  13459. auto MMOFlags =
  13460. LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
  13461. SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
  13462. LD->getPointerInfo(), LD->getAlignment(),
  13463. MMOFlags, LD->getAAInfo());
  13464. SDValue AddPtr =
  13465. DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
  13466. BasePtr, DAG.getIntPtrConstant(4, dl));
  13467. SDValue FloatLoad2 = DAG.getLoad(
  13468. MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
  13469. LD->getPointerInfo().getWithOffset(4),
  13470. MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
  13471. if (LD->isIndexed()) {
  13472. // Note that DAGCombine should re-form any pre-increment load(s) from
  13473. // what is produced here if that makes sense.
  13474. DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
  13475. }
  13476. DCI.CombineTo(Bitcast2, FloatLoad);
  13477. DCI.CombineTo(Bitcast, FloatLoad2);
  13478. DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
  13479. SDValue(FloatLoad2.getNode(), 1));
  13480. return true;
  13481. };
  13482. if (ReplaceTwoFloatLoad())
  13483. return SDValue(N, 0);
  13484. EVT MemVT = LD->getMemoryVT();
  13485. Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
  13486. Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
  13487. if (LD->isUnindexed() && VT.isVector() &&
  13488. ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
  13489. // P8 and later hardware should just use LOAD.
  13490. !Subtarget.hasP8Vector() &&
  13491. (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
  13492. VT == MVT::v4f32))) &&
  13493. LD->getAlign() < ABIAlignment) {
  13494. // This is a type-legal unaligned Altivec load.
  13495. SDValue Chain = LD->getChain();
  13496. SDValue Ptr = LD->getBasePtr();
  13497. bool isLittleEndian = Subtarget.isLittleEndian();
  13498. // This implements the loading of unaligned vectors as described in
  13499. // the venerable Apple Velocity Engine overview. Specifically:
  13500. // https://developer.apple.com/hardwaredrivers/ve/alignment.html
  13501. // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
  13502. //
  13503. // The general idea is to expand a sequence of one or more unaligned
  13504. // loads into an alignment-based permutation-control instruction (lvsl
  13505. // or lvsr), a series of regular vector loads (which always truncate
  13506. // their input address to an aligned address), and a series of
  13507. // permutations. The results of these permutations are the requested
  13508. // loaded values. The trick is that the last "extra" load is not taken
  13509. // from the address you might suspect (sizeof(vector) bytes after the
  13510. // last requested load), but rather sizeof(vector) - 1 bytes after the
  13511. // last requested vector. The point of this is to avoid a page fault if
  13512. // the base address happened to be aligned. This works because if the
  13513. // base address is aligned, then adding less than a full vector length
  13514. // will cause the last vector in the sequence to be (re)loaded.
  13515. // Otherwise, the next vector will be fetched as you might suspect was
  13516. // necessary.
  13517. // We might be able to reuse the permutation generation from
  13518. // a different base address offset from this one by an aligned amount.
  13519. // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
  13520. // optimization later.
  13521. Intrinsic::ID Intr, IntrLD, IntrPerm;
  13522. MVT PermCntlTy, PermTy, LDTy;
  13523. Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
  13524. : Intrinsic::ppc_altivec_lvsl;
  13525. IntrLD = Intrinsic::ppc_altivec_lvx;
  13526. IntrPerm = Intrinsic::ppc_altivec_vperm;
  13527. PermCntlTy = MVT::v16i8;
  13528. PermTy = MVT::v4i32;
  13529. LDTy = MVT::v4i32;
  13530. SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
  13531. // Create the new MMO for the new base load. It is like the original MMO,
  13532. // but represents an area in memory almost twice the vector size centered
  13533. // on the original address. If the address is unaligned, we might start
  13534. // reading up to (sizeof(vector)-1) bytes below the address of the
  13535. // original unaligned load.
  13536. MachineFunction &MF = DAG.getMachineFunction();
  13537. MachineMemOperand *BaseMMO =
  13538. MF.getMachineMemOperand(LD->getMemOperand(),
  13539. -(long)MemVT.getStoreSize()+1,
  13540. 2*MemVT.getStoreSize()-1);
  13541. // Create the new base load.
  13542. SDValue LDXIntID =
  13543. DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
  13544. SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
  13545. SDValue BaseLoad =
  13546. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
  13547. DAG.getVTList(PermTy, MVT::Other),
  13548. BaseLoadOps, LDTy, BaseMMO);
  13549. // Note that the value of IncOffset (which is provided to the next
  13550. // load's pointer info offset value, and thus used to calculate the
  13551. // alignment), and the value of IncValue (which is actually used to
  13552. // increment the pointer value) are different! This is because we
  13553. // require the next load to appear to be aligned, even though it
  13554. // is actually offset from the base pointer by a lesser amount.
  13555. int IncOffset = VT.getSizeInBits() / 8;
  13556. int IncValue = IncOffset;
  13557. // Walk (both up and down) the chain looking for another load at the real
  13558. // (aligned) offset (the alignment of the other load does not matter in
  13559. // this case). If found, then do not use the offset reduction trick, as
  13560. // that will prevent the loads from being later combined (as they would
  13561. // otherwise be duplicates).
  13562. if (!findConsecutiveLoad(LD, DAG))
  13563. --IncValue;
  13564. SDValue Increment =
  13565. DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
  13566. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
  13567. MachineMemOperand *ExtraMMO =
  13568. MF.getMachineMemOperand(LD->getMemOperand(),
  13569. 1, 2*MemVT.getStoreSize()-1);
  13570. SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
  13571. SDValue ExtraLoad =
  13572. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
  13573. DAG.getVTList(PermTy, MVT::Other),
  13574. ExtraLoadOps, LDTy, ExtraMMO);
  13575. SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  13576. BaseLoad.getValue(1), ExtraLoad.getValue(1));
  13577. // Because vperm has a big-endian bias, we must reverse the order
  13578. // of the input vectors and complement the permute control vector
  13579. // when generating little endian code. We have already handled the
  13580. // latter by using lvsr instead of lvsl, so just reverse BaseLoad
  13581. // and ExtraLoad here.
  13582. SDValue Perm;
  13583. if (isLittleEndian)
  13584. Perm = BuildIntrinsicOp(IntrPerm,
  13585. ExtraLoad, BaseLoad, PermCntl, DAG, dl);
  13586. else
  13587. Perm = BuildIntrinsicOp(IntrPerm,
  13588. BaseLoad, ExtraLoad, PermCntl, DAG, dl);
  13589. if (VT != PermTy)
  13590. Perm = Subtarget.hasAltivec()
  13591. ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
  13592. : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
  13593. DAG.getTargetConstant(1, dl, MVT::i64));
  13594. // second argument is 1 because this rounding
  13595. // is always exact.
  13596. // The output of the permutation is our loaded result, the TokenFactor is
  13597. // our new chain.
  13598. DCI.CombineTo(N, Perm, TF);
  13599. return SDValue(N, 0);
  13600. }
  13601. }
  13602. break;
  13603. case ISD::INTRINSIC_WO_CHAIN: {
  13604. bool isLittleEndian = Subtarget.isLittleEndian();
  13605. unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
  13606. Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
  13607. : Intrinsic::ppc_altivec_lvsl);
  13608. if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
  13609. SDValue Add = N->getOperand(1);
  13610. int Bits = 4 /* 16 byte alignment */;
  13611. if (DAG.MaskedValueIsZero(Add->getOperand(1),
  13612. APInt::getAllOnes(Bits /* alignment */)
  13613. .zext(Add.getScalarValueSizeInBits()))) {
  13614. SDNode *BasePtr = Add->getOperand(0).getNode();
  13615. for (SDNode *U : BasePtr->uses()) {
  13616. if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
  13617. cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
  13618. // We've found another LVSL/LVSR, and this address is an aligned
  13619. // multiple of that one. The results will be the same, so use the
  13620. // one we've just found instead.
  13621. return SDValue(U, 0);
  13622. }
  13623. }
  13624. }
  13625. if (isa<ConstantSDNode>(Add->getOperand(1))) {
  13626. SDNode *BasePtr = Add->getOperand(0).getNode();
  13627. for (SDNode *U : BasePtr->uses()) {
  13628. if (U->getOpcode() == ISD::ADD &&
  13629. isa<ConstantSDNode>(U->getOperand(1)) &&
  13630. (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
  13631. cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
  13632. (1ULL << Bits) ==
  13633. 0) {
  13634. SDNode *OtherAdd = U;
  13635. for (SDNode *V : OtherAdd->uses()) {
  13636. if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
  13637. cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
  13638. IID) {
  13639. return SDValue(V, 0);
  13640. }
  13641. }
  13642. }
  13643. }
  13644. }
  13645. }
  13646. // Combine vmaxsw/h/b(a, a's negation) to abs(a)
  13647. // Expose the vabsduw/h/b opportunity for down stream
  13648. if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
  13649. (IID == Intrinsic::ppc_altivec_vmaxsw ||
  13650. IID == Intrinsic::ppc_altivec_vmaxsh ||
  13651. IID == Intrinsic::ppc_altivec_vmaxsb)) {
  13652. SDValue V1 = N->getOperand(1);
  13653. SDValue V2 = N->getOperand(2);
  13654. if ((V1.getSimpleValueType() == MVT::v4i32 ||
  13655. V1.getSimpleValueType() == MVT::v8i16 ||
  13656. V1.getSimpleValueType() == MVT::v16i8) &&
  13657. V1.getSimpleValueType() == V2.getSimpleValueType()) {
  13658. // (0-a, a)
  13659. if (V1.getOpcode() == ISD::SUB &&
  13660. ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
  13661. V1.getOperand(1) == V2) {
  13662. return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
  13663. }
  13664. // (a, 0-a)
  13665. if (V2.getOpcode() == ISD::SUB &&
  13666. ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
  13667. V2.getOperand(1) == V1) {
  13668. return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
  13669. }
  13670. // (x-y, y-x)
  13671. if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
  13672. V1.getOperand(0) == V2.getOperand(1) &&
  13673. V1.getOperand(1) == V2.getOperand(0)) {
  13674. return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
  13675. }
  13676. }
  13677. }
  13678. }
  13679. break;
  13680. case ISD::INTRINSIC_W_CHAIN:
  13681. // For little endian, VSX loads require generating lxvd2x/xxswapd.
  13682. // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
  13683. if (Subtarget.needsSwapsForVSXMemOps()) {
  13684. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  13685. default:
  13686. break;
  13687. case Intrinsic::ppc_vsx_lxvw4x:
  13688. case Intrinsic::ppc_vsx_lxvd2x:
  13689. return expandVSXLoadForLE(N, DCI);
  13690. }
  13691. }
  13692. break;
  13693. case ISD::INTRINSIC_VOID:
  13694. // For little endian, VSX stores require generating xxswapd/stxvd2x.
  13695. // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
  13696. if (Subtarget.needsSwapsForVSXMemOps()) {
  13697. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  13698. default:
  13699. break;
  13700. case Intrinsic::ppc_vsx_stxvw4x:
  13701. case Intrinsic::ppc_vsx_stxvd2x:
  13702. return expandVSXStoreForLE(N, DCI);
  13703. }
  13704. }
  13705. break;
  13706. case ISD::BSWAP: {
  13707. // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
  13708. // For subtargets without LDBRX, we can still do better than the default
  13709. // expansion even for 64-bit BSWAP (LOAD).
  13710. bool Is64BitBswapOn64BitTgt =
  13711. Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
  13712. bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
  13713. N->getOperand(0).hasOneUse();
  13714. if (IsSingleUseNormalLd &&
  13715. (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
  13716. (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
  13717. SDValue Load = N->getOperand(0);
  13718. LoadSDNode *LD = cast<LoadSDNode>(Load);
  13719. // Create the byte-swapping load.
  13720. SDValue Ops[] = {
  13721. LD->getChain(), // Chain
  13722. LD->getBasePtr(), // Ptr
  13723. DAG.getValueType(N->getValueType(0)) // VT
  13724. };
  13725. SDValue BSLoad =
  13726. DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
  13727. DAG.getVTList(N->getValueType(0) == MVT::i64 ?
  13728. MVT::i64 : MVT::i32, MVT::Other),
  13729. Ops, LD->getMemoryVT(), LD->getMemOperand());
  13730. // If this is an i16 load, insert the truncate.
  13731. SDValue ResVal = BSLoad;
  13732. if (N->getValueType(0) == MVT::i16)
  13733. ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
  13734. // First, combine the bswap away. This makes the value produced by the
  13735. // load dead.
  13736. DCI.CombineTo(N, ResVal);
  13737. // Next, combine the load away, we give it a bogus result value but a real
  13738. // chain result. The result value is dead because the bswap is dead.
  13739. DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
  13740. // Return N so it doesn't get rechecked!
  13741. return SDValue(N, 0);
  13742. }
  13743. // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
  13744. // before legalization so that the BUILD_PAIR is handled correctly.
  13745. if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
  13746. !IsSingleUseNormalLd)
  13747. return SDValue();
  13748. LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
  13749. // Can't split volatile or atomic loads.
  13750. if (!LD->isSimple())
  13751. return SDValue();
  13752. SDValue BasePtr = LD->getBasePtr();
  13753. SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
  13754. LD->getPointerInfo(), LD->getAlignment());
  13755. Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
  13756. BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
  13757. DAG.getIntPtrConstant(4, dl));
  13758. MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
  13759. LD->getMemOperand(), 4, 4);
  13760. SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
  13761. Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
  13762. SDValue Res;
  13763. if (Subtarget.isLittleEndian())
  13764. Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
  13765. else
  13766. Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
  13767. SDValue TF =
  13768. DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  13769. Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
  13770. DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
  13771. return Res;
  13772. }
  13773. case PPCISD::VCMP:
  13774. // If a VCMP_rec node already exists with exactly the same operands as this
  13775. // node, use its result instead of this node (VCMP_rec computes both a CR6
  13776. // and a normal output).
  13777. //
  13778. if (!N->getOperand(0).hasOneUse() &&
  13779. !N->getOperand(1).hasOneUse() &&
  13780. !N->getOperand(2).hasOneUse()) {
  13781. // Scan all of the users of the LHS, looking for VCMP_rec's that match.
  13782. SDNode *VCMPrecNode = nullptr;
  13783. SDNode *LHSN = N->getOperand(0).getNode();
  13784. for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
  13785. UI != E; ++UI)
  13786. if (UI->getOpcode() == PPCISD::VCMP_rec &&
  13787. UI->getOperand(1) == N->getOperand(1) &&
  13788. UI->getOperand(2) == N->getOperand(2) &&
  13789. UI->getOperand(0) == N->getOperand(0)) {
  13790. VCMPrecNode = *UI;
  13791. break;
  13792. }
  13793. // If there is no VCMP_rec node, or if the flag value has a single use,
  13794. // don't transform this.
  13795. if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
  13796. break;
  13797. // Look at the (necessarily single) use of the flag value. If it has a
  13798. // chain, this transformation is more complex. Note that multiple things
  13799. // could use the value result, which we should ignore.
  13800. SDNode *FlagUser = nullptr;
  13801. for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
  13802. FlagUser == nullptr; ++UI) {
  13803. assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
  13804. SDNode *User = *UI;
  13805. for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
  13806. if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
  13807. FlagUser = User;
  13808. break;
  13809. }
  13810. }
  13811. }
  13812. // If the user is a MFOCRF instruction, we know this is safe.
  13813. // Otherwise we give up for right now.
  13814. if (FlagUser->getOpcode() == PPCISD::MFOCRF)
  13815. return SDValue(VCMPrecNode, 0);
  13816. }
  13817. break;
  13818. case ISD::BRCOND: {
  13819. SDValue Cond = N->getOperand(1);
  13820. SDValue Target = N->getOperand(2);
  13821. if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
  13822. cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
  13823. Intrinsic::loop_decrement) {
  13824. // We now need to make the intrinsic dead (it cannot be instruction
  13825. // selected).
  13826. DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
  13827. assert(Cond.getNode()->hasOneUse() &&
  13828. "Counter decrement has more than one use");
  13829. return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
  13830. N->getOperand(0), Target);
  13831. }
  13832. }
  13833. break;
  13834. case ISD::BR_CC: {
  13835. // If this is a branch on an altivec predicate comparison, lower this so
  13836. // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
  13837. // lowering is done pre-legalize, because the legalizer lowers the predicate
  13838. // compare down to code that is difficult to reassemble.
  13839. ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
  13840. SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
  13841. // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
  13842. // value. If so, pass-through the AND to get to the intrinsic.
  13843. if (LHS.getOpcode() == ISD::AND &&
  13844. LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
  13845. cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
  13846. Intrinsic::loop_decrement &&
  13847. isa<ConstantSDNode>(LHS.getOperand(1)) &&
  13848. !isNullConstant(LHS.getOperand(1)))
  13849. LHS = LHS.getOperand(0);
  13850. if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
  13851. cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
  13852. Intrinsic::loop_decrement &&
  13853. isa<ConstantSDNode>(RHS)) {
  13854. assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
  13855. "Counter decrement comparison is not EQ or NE");
  13856. unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
  13857. bool isBDNZ = (CC == ISD::SETEQ && Val) ||
  13858. (CC == ISD::SETNE && !Val);
  13859. // We now need to make the intrinsic dead (it cannot be instruction
  13860. // selected).
  13861. DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
  13862. assert(LHS.getNode()->hasOneUse() &&
  13863. "Counter decrement has more than one use");
  13864. return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
  13865. N->getOperand(0), N->getOperand(4));
  13866. }
  13867. int CompareOpc;
  13868. bool isDot;
  13869. if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
  13870. isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
  13871. getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
  13872. assert(isDot && "Can't compare against a vector result!");
  13873. // If this is a comparison against something other than 0/1, then we know
  13874. // that the condition is never/always true.
  13875. unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
  13876. if (Val != 0 && Val != 1) {
  13877. if (CC == ISD::SETEQ) // Cond never true, remove branch.
  13878. return N->getOperand(0);
  13879. // Always !=, turn it into an unconditional branch.
  13880. return DAG.getNode(ISD::BR, dl, MVT::Other,
  13881. N->getOperand(0), N->getOperand(4));
  13882. }
  13883. bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
  13884. // Create the PPCISD altivec 'dot' comparison node.
  13885. SDValue Ops[] = {
  13886. LHS.getOperand(2), // LHS of compare
  13887. LHS.getOperand(3), // RHS of compare
  13888. DAG.getConstant(CompareOpc, dl, MVT::i32)
  13889. };
  13890. EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
  13891. SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
  13892. // Unpack the result based on how the target uses it.
  13893. PPC::Predicate CompOpc;
  13894. switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
  13895. default: // Can't happen, don't crash on invalid number though.
  13896. case 0: // Branch on the value of the EQ bit of CR6.
  13897. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
  13898. break;
  13899. case 1: // Branch on the inverted value of the EQ bit of CR6.
  13900. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
  13901. break;
  13902. case 2: // Branch on the value of the LT bit of CR6.
  13903. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
  13904. break;
  13905. case 3: // Branch on the inverted value of the LT bit of CR6.
  13906. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
  13907. break;
  13908. }
  13909. return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
  13910. DAG.getConstant(CompOpc, dl, MVT::i32),
  13911. DAG.getRegister(PPC::CR6, MVT::i32),
  13912. N->getOperand(4), CompNode.getValue(1));
  13913. }
  13914. break;
  13915. }
  13916. case ISD::BUILD_VECTOR:
  13917. return DAGCombineBuildVector(N, DCI);
  13918. case ISD::ABS:
  13919. return combineABS(N, DCI);
  13920. case ISD::VSELECT:
  13921. return combineVSelect(N, DCI);
  13922. }
  13923. return SDValue();
  13924. }
  13925. SDValue
  13926. PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
  13927. SelectionDAG &DAG,
  13928. SmallVectorImpl<SDNode *> &Created) const {
  13929. // fold (sdiv X, pow2)
  13930. EVT VT = N->getValueType(0);
  13931. if (VT == MVT::i64 && !Subtarget.isPPC64())
  13932. return SDValue();
  13933. if ((VT != MVT::i32 && VT != MVT::i64) ||
  13934. !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
  13935. return SDValue();
  13936. SDLoc DL(N);
  13937. SDValue N0 = N->getOperand(0);
  13938. bool IsNegPow2 = Divisor.isNegatedPowerOf2();
  13939. unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
  13940. SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
  13941. SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
  13942. Created.push_back(Op.getNode());
  13943. if (IsNegPow2) {
  13944. Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
  13945. Created.push_back(Op.getNode());
  13946. }
  13947. return Op;
  13948. }
  13949. //===----------------------------------------------------------------------===//
  13950. // Inline Assembly Support
  13951. //===----------------------------------------------------------------------===//
  13952. void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
  13953. KnownBits &Known,
  13954. const APInt &DemandedElts,
  13955. const SelectionDAG &DAG,
  13956. unsigned Depth) const {
  13957. Known.resetAll();
  13958. switch (Op.getOpcode()) {
  13959. default: break;
  13960. case PPCISD::LBRX: {
  13961. // lhbrx is known to have the top bits cleared out.
  13962. if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
  13963. Known.Zero = 0xFFFF0000;
  13964. break;
  13965. }
  13966. case ISD::INTRINSIC_WO_CHAIN: {
  13967. switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
  13968. default: break;
  13969. case Intrinsic::ppc_altivec_vcmpbfp_p:
  13970. case Intrinsic::ppc_altivec_vcmpeqfp_p:
  13971. case Intrinsic::ppc_altivec_vcmpequb_p:
  13972. case Intrinsic::ppc_altivec_vcmpequh_p:
  13973. case Intrinsic::ppc_altivec_vcmpequw_p:
  13974. case Intrinsic::ppc_altivec_vcmpequd_p:
  13975. case Intrinsic::ppc_altivec_vcmpequq_p:
  13976. case Intrinsic::ppc_altivec_vcmpgefp_p:
  13977. case Intrinsic::ppc_altivec_vcmpgtfp_p:
  13978. case Intrinsic::ppc_altivec_vcmpgtsb_p:
  13979. case Intrinsic::ppc_altivec_vcmpgtsh_p:
  13980. case Intrinsic::ppc_altivec_vcmpgtsw_p:
  13981. case Intrinsic::ppc_altivec_vcmpgtsd_p:
  13982. case Intrinsic::ppc_altivec_vcmpgtsq_p:
  13983. case Intrinsic::ppc_altivec_vcmpgtub_p:
  13984. case Intrinsic::ppc_altivec_vcmpgtuh_p:
  13985. case Intrinsic::ppc_altivec_vcmpgtuw_p:
  13986. case Intrinsic::ppc_altivec_vcmpgtud_p:
  13987. case Intrinsic::ppc_altivec_vcmpgtuq_p:
  13988. Known.Zero = ~1U; // All bits but the low one are known to be zero.
  13989. break;
  13990. }
  13991. break;
  13992. }
  13993. case ISD::INTRINSIC_W_CHAIN: {
  13994. switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
  13995. default:
  13996. break;
  13997. case Intrinsic::ppc_load2r:
  13998. // Top bits are cleared for load2r (which is the same as lhbrx).
  13999. Known.Zero = 0xFFFF0000;
  14000. break;
  14001. }
  14002. break;
  14003. }
  14004. }
  14005. }
  14006. Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
  14007. switch (Subtarget.getCPUDirective()) {
  14008. default: break;
  14009. case PPC::DIR_970:
  14010. case PPC::DIR_PWR4:
  14011. case PPC::DIR_PWR5:
  14012. case PPC::DIR_PWR5X:
  14013. case PPC::DIR_PWR6:
  14014. case PPC::DIR_PWR6X:
  14015. case PPC::DIR_PWR7:
  14016. case PPC::DIR_PWR8:
  14017. case PPC::DIR_PWR9:
  14018. case PPC::DIR_PWR10:
  14019. case PPC::DIR_PWR_FUTURE: {
  14020. if (!ML)
  14021. break;
  14022. if (!DisableInnermostLoopAlign32) {
  14023. // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
  14024. // so that we can decrease cache misses and branch-prediction misses.
  14025. // Actual alignment of the loop will depend on the hotness check and other
  14026. // logic in alignBlocks.
  14027. if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
  14028. return Align(32);
  14029. }
  14030. const PPCInstrInfo *TII = Subtarget.getInstrInfo();
  14031. // For small loops (between 5 and 8 instructions), align to a 32-byte
  14032. // boundary so that the entire loop fits in one instruction-cache line.
  14033. uint64_t LoopSize = 0;
  14034. for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
  14035. for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
  14036. LoopSize += TII->getInstSizeInBytes(*J);
  14037. if (LoopSize > 32)
  14038. break;
  14039. }
  14040. if (LoopSize > 16 && LoopSize <= 32)
  14041. return Align(32);
  14042. break;
  14043. }
  14044. }
  14045. return TargetLowering::getPrefLoopAlignment(ML);
  14046. }
  14047. /// getConstraintType - Given a constraint, return the type of
  14048. /// constraint it is for this target.
  14049. PPCTargetLowering::ConstraintType
  14050. PPCTargetLowering::getConstraintType(StringRef Constraint) const {
  14051. if (Constraint.size() == 1) {
  14052. switch (Constraint[0]) {
  14053. default: break;
  14054. case 'b':
  14055. case 'r':
  14056. case 'f':
  14057. case 'd':
  14058. case 'v':
  14059. case 'y':
  14060. return C_RegisterClass;
  14061. case 'Z':
  14062. // FIXME: While Z does indicate a memory constraint, it specifically
  14063. // indicates an r+r address (used in conjunction with the 'y' modifier
  14064. // in the replacement string). Currently, we're forcing the base
  14065. // register to be r0 in the asm printer (which is interpreted as zero)
  14066. // and forming the complete address in the second register. This is
  14067. // suboptimal.
  14068. return C_Memory;
  14069. }
  14070. } else if (Constraint == "wc") { // individual CR bits.
  14071. return C_RegisterClass;
  14072. } else if (Constraint == "wa" || Constraint == "wd" ||
  14073. Constraint == "wf" || Constraint == "ws" ||
  14074. Constraint == "wi" || Constraint == "ww") {
  14075. return C_RegisterClass; // VSX registers.
  14076. }
  14077. return TargetLowering::getConstraintType(Constraint);
  14078. }
  14079. /// Examine constraint type and operand type and determine a weight value.
  14080. /// This object must already have been set up with the operand type
  14081. /// and the current alternative constraint selected.
  14082. TargetLowering::ConstraintWeight
  14083. PPCTargetLowering::getSingleConstraintMatchWeight(
  14084. AsmOperandInfo &info, const char *constraint) const {
  14085. ConstraintWeight weight = CW_Invalid;
  14086. Value *CallOperandVal = info.CallOperandVal;
  14087. // If we don't have a value, we can't do a match,
  14088. // but allow it at the lowest weight.
  14089. if (!CallOperandVal)
  14090. return CW_Default;
  14091. Type *type = CallOperandVal->getType();
  14092. // Look at the constraint type.
  14093. if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
  14094. return CW_Register; // an individual CR bit.
  14095. else if ((StringRef(constraint) == "wa" ||
  14096. StringRef(constraint) == "wd" ||
  14097. StringRef(constraint) == "wf") &&
  14098. type->isVectorTy())
  14099. return CW_Register;
  14100. else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
  14101. return CW_Register; // just hold 64-bit integers data.
  14102. else if (StringRef(constraint) == "ws" && type->isDoubleTy())
  14103. return CW_Register;
  14104. else if (StringRef(constraint) == "ww" && type->isFloatTy())
  14105. return CW_Register;
  14106. switch (*constraint) {
  14107. default:
  14108. weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
  14109. break;
  14110. case 'b':
  14111. if (type->isIntegerTy())
  14112. weight = CW_Register;
  14113. break;
  14114. case 'f':
  14115. if (type->isFloatTy())
  14116. weight = CW_Register;
  14117. break;
  14118. case 'd':
  14119. if (type->isDoubleTy())
  14120. weight = CW_Register;
  14121. break;
  14122. case 'v':
  14123. if (type->isVectorTy())
  14124. weight = CW_Register;
  14125. break;
  14126. case 'y':
  14127. weight = CW_Register;
  14128. break;
  14129. case 'Z':
  14130. weight = CW_Memory;
  14131. break;
  14132. }
  14133. return weight;
  14134. }
  14135. std::pair<unsigned, const TargetRegisterClass *>
  14136. PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
  14137. StringRef Constraint,
  14138. MVT VT) const {
  14139. if (Constraint.size() == 1) {
  14140. // GCC RS6000 Constraint Letters
  14141. switch (Constraint[0]) {
  14142. case 'b': // R1-R31
  14143. if (VT == MVT::i64 && Subtarget.isPPC64())
  14144. return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
  14145. return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
  14146. case 'r': // R0-R31
  14147. if (VT == MVT::i64 && Subtarget.isPPC64())
  14148. return std::make_pair(0U, &PPC::G8RCRegClass);
  14149. return std::make_pair(0U, &PPC::GPRCRegClass);
  14150. // 'd' and 'f' constraints are both defined to be "the floating point
  14151. // registers", where one is for 32-bit and the other for 64-bit. We don't
  14152. // really care overly much here so just give them all the same reg classes.
  14153. case 'd':
  14154. case 'f':
  14155. if (Subtarget.hasSPE()) {
  14156. if (VT == MVT::f32 || VT == MVT::i32)
  14157. return std::make_pair(0U, &PPC::GPRCRegClass);
  14158. if (VT == MVT::f64 || VT == MVT::i64)
  14159. return std::make_pair(0U, &PPC::SPERCRegClass);
  14160. } else {
  14161. if (VT == MVT::f32 || VT == MVT::i32)
  14162. return std::make_pair(0U, &PPC::F4RCRegClass);
  14163. if (VT == MVT::f64 || VT == MVT::i64)
  14164. return std::make_pair(0U, &PPC::F8RCRegClass);
  14165. }
  14166. break;
  14167. case 'v':
  14168. if (Subtarget.hasAltivec() && VT.isVector())
  14169. return std::make_pair(0U, &PPC::VRRCRegClass);
  14170. else if (Subtarget.hasVSX())
  14171. // Scalars in Altivec registers only make sense with VSX.
  14172. return std::make_pair(0U, &PPC::VFRCRegClass);
  14173. break;
  14174. case 'y': // crrc
  14175. return std::make_pair(0U, &PPC::CRRCRegClass);
  14176. }
  14177. } else if (Constraint == "wc" && Subtarget.useCRBits()) {
  14178. // An individual CR bit.
  14179. return std::make_pair(0U, &PPC::CRBITRCRegClass);
  14180. } else if ((Constraint == "wa" || Constraint == "wd" ||
  14181. Constraint == "wf" || Constraint == "wi") &&
  14182. Subtarget.hasVSX()) {
  14183. // A VSX register for either a scalar (FP) or vector. There is no
  14184. // support for single precision scalars on subtargets prior to Power8.
  14185. if (VT.isVector())
  14186. return std::make_pair(0U, &PPC::VSRCRegClass);
  14187. if (VT == MVT::f32 && Subtarget.hasP8Vector())
  14188. return std::make_pair(0U, &PPC::VSSRCRegClass);
  14189. return std::make_pair(0U, &PPC::VSFRCRegClass);
  14190. } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
  14191. if (VT == MVT::f32 && Subtarget.hasP8Vector())
  14192. return std::make_pair(0U, &PPC::VSSRCRegClass);
  14193. else
  14194. return std::make_pair(0U, &PPC::VSFRCRegClass);
  14195. } else if (Constraint == "lr") {
  14196. if (VT == MVT::i64)
  14197. return std::make_pair(0U, &PPC::LR8RCRegClass);
  14198. else
  14199. return std::make_pair(0U, &PPC::LRRCRegClass);
  14200. }
  14201. // Handle special cases of physical registers that are not properly handled
  14202. // by the base class.
  14203. if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
  14204. // If we name a VSX register, we can't defer to the base class because it
  14205. // will not recognize the correct register (their names will be VSL{0-31}
  14206. // and V{0-31} so they won't match). So we match them here.
  14207. if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
  14208. int VSNum = atoi(Constraint.data() + 3);
  14209. assert(VSNum >= 0 && VSNum <= 63 &&
  14210. "Attempted to access a vsr out of range");
  14211. if (VSNum < 32)
  14212. return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
  14213. return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
  14214. }
  14215. // For float registers, we can't defer to the base class as it will match
  14216. // the SPILLTOVSRRC class.
  14217. if (Constraint.size() > 3 && Constraint[1] == 'f') {
  14218. int RegNum = atoi(Constraint.data() + 2);
  14219. if (RegNum > 31 || RegNum < 0)
  14220. report_fatal_error("Invalid floating point register number");
  14221. if (VT == MVT::f32 || VT == MVT::i32)
  14222. return Subtarget.hasSPE()
  14223. ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
  14224. : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
  14225. if (VT == MVT::f64 || VT == MVT::i64)
  14226. return Subtarget.hasSPE()
  14227. ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
  14228. : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
  14229. }
  14230. }
  14231. std::pair<unsigned, const TargetRegisterClass *> R =
  14232. TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
  14233. // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
  14234. // (which we call X[0-9]+). If a 64-bit value has been requested, and a
  14235. // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
  14236. // register.
  14237. // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
  14238. // the AsmName field from *RegisterInfo.td, then this would not be necessary.
  14239. if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
  14240. PPC::GPRCRegClass.contains(R.first))
  14241. return std::make_pair(TRI->getMatchingSuperReg(R.first,
  14242. PPC::sub_32, &PPC::G8RCRegClass),
  14243. &PPC::G8RCRegClass);
  14244. // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
  14245. if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
  14246. R.first = PPC::CR0;
  14247. R.second = &PPC::CRRCRegClass;
  14248. }
  14249. // FIXME: This warning should ideally be emitted in the front end.
  14250. const auto &TM = getTargetMachine();
  14251. if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
  14252. if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
  14253. (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
  14254. (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
  14255. errs() << "warning: vector registers 20 to 32 are reserved in the "
  14256. "default AIX AltiVec ABI and cannot be used\n";
  14257. }
  14258. return R;
  14259. }
  14260. /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
  14261. /// vector. If it is invalid, don't add anything to Ops.
  14262. void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
  14263. std::string &Constraint,
  14264. std::vector<SDValue>&Ops,
  14265. SelectionDAG &DAG) const {
  14266. SDValue Result;
  14267. // Only support length 1 constraints.
  14268. if (Constraint.length() > 1) return;
  14269. char Letter = Constraint[0];
  14270. switch (Letter) {
  14271. default: break;
  14272. case 'I':
  14273. case 'J':
  14274. case 'K':
  14275. case 'L':
  14276. case 'M':
  14277. case 'N':
  14278. case 'O':
  14279. case 'P': {
  14280. ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
  14281. if (!CST) return; // Must be an immediate to match.
  14282. SDLoc dl(Op);
  14283. int64_t Value = CST->getSExtValue();
  14284. EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
  14285. // numbers are printed as such.
  14286. switch (Letter) {
  14287. default: llvm_unreachable("Unknown constraint letter!");
  14288. case 'I': // "I" is a signed 16-bit constant.
  14289. if (isInt<16>(Value))
  14290. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14291. break;
  14292. case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
  14293. if (isShiftedUInt<16, 16>(Value))
  14294. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14295. break;
  14296. case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
  14297. if (isShiftedInt<16, 16>(Value))
  14298. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14299. break;
  14300. case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
  14301. if (isUInt<16>(Value))
  14302. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14303. break;
  14304. case 'M': // "M" is a constant that is greater than 31.
  14305. if (Value > 31)
  14306. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14307. break;
  14308. case 'N': // "N" is a positive constant that is an exact power of two.
  14309. if (Value > 0 && isPowerOf2_64(Value))
  14310. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14311. break;
  14312. case 'O': // "O" is the constant zero.
  14313. if (Value == 0)
  14314. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14315. break;
  14316. case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
  14317. if (isInt<16>(-Value))
  14318. Result = DAG.getTargetConstant(Value, dl, TCVT);
  14319. break;
  14320. }
  14321. break;
  14322. }
  14323. }
  14324. if (Result.getNode()) {
  14325. Ops.push_back(Result);
  14326. return;
  14327. }
  14328. // Handle standard constraint letters.
  14329. TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
  14330. }
  14331. // isLegalAddressingMode - Return true if the addressing mode represented
  14332. // by AM is legal for this target, for a load/store of the specified type.
  14333. bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
  14334. const AddrMode &AM, Type *Ty,
  14335. unsigned AS,
  14336. Instruction *I) const {
  14337. // Vector type r+i form is supported since power9 as DQ form. We don't check
  14338. // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
  14339. // imm form is preferred and the offset can be adjusted to use imm form later
  14340. // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
  14341. // max offset to check legal addressing mode, we should be a little aggressive
  14342. // to contain other offsets for that LSRUse.
  14343. if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
  14344. return false;
  14345. // PPC allows a sign-extended 16-bit immediate field.
  14346. if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
  14347. return false;
  14348. // No global is ever allowed as a base.
  14349. if (AM.BaseGV)
  14350. return false;
  14351. // PPC only support r+r,
  14352. switch (AM.Scale) {
  14353. case 0: // "r+i" or just "i", depending on HasBaseReg.
  14354. break;
  14355. case 1:
  14356. if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
  14357. return false;
  14358. // Otherwise we have r+r or r+i.
  14359. break;
  14360. case 2:
  14361. if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
  14362. return false;
  14363. // Allow 2*r as r+r.
  14364. break;
  14365. default:
  14366. // No other scales are supported.
  14367. return false;
  14368. }
  14369. return true;
  14370. }
  14371. SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
  14372. SelectionDAG &DAG) const {
  14373. MachineFunction &MF = DAG.getMachineFunction();
  14374. MachineFrameInfo &MFI = MF.getFrameInfo();
  14375. MFI.setReturnAddressIsTaken(true);
  14376. if (verifyReturnAddressArgumentIsConstant(Op, DAG))
  14377. return SDValue();
  14378. SDLoc dl(Op);
  14379. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  14380. // Make sure the function does not optimize away the store of the RA to
  14381. // the stack.
  14382. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
  14383. FuncInfo->setLRStoreRequired();
  14384. bool isPPC64 = Subtarget.isPPC64();
  14385. auto PtrVT = getPointerTy(MF.getDataLayout());
  14386. if (Depth > 0) {
  14387. // The link register (return address) is saved in the caller's frame
  14388. // not the callee's stack frame. So we must get the caller's frame
  14389. // address and load the return address at the LR offset from there.
  14390. SDValue FrameAddr =
  14391. DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
  14392. LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
  14393. SDValue Offset =
  14394. DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
  14395. isPPC64 ? MVT::i64 : MVT::i32);
  14396. return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
  14397. DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
  14398. MachinePointerInfo());
  14399. }
  14400. // Just load the return address off the stack.
  14401. SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
  14402. return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
  14403. MachinePointerInfo());
  14404. }
  14405. SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
  14406. SelectionDAG &DAG) const {
  14407. SDLoc dl(Op);
  14408. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  14409. MachineFunction &MF = DAG.getMachineFunction();
  14410. MachineFrameInfo &MFI = MF.getFrameInfo();
  14411. MFI.setFrameAddressIsTaken(true);
  14412. EVT PtrVT = getPointerTy(MF.getDataLayout());
  14413. bool isPPC64 = PtrVT == MVT::i64;
  14414. // Naked functions never have a frame pointer, and so we use r1. For all
  14415. // other functions, this decision must be delayed until during PEI.
  14416. unsigned FrameReg;
  14417. if (MF.getFunction().hasFnAttribute(Attribute::Naked))
  14418. FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
  14419. else
  14420. FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
  14421. SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
  14422. PtrVT);
  14423. while (Depth--)
  14424. FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
  14425. FrameAddr, MachinePointerInfo());
  14426. return FrameAddr;
  14427. }
  14428. // FIXME? Maybe this could be a TableGen attribute on some registers and
  14429. // this table could be generated automatically from RegInfo.
  14430. Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
  14431. const MachineFunction &MF) const {
  14432. bool isPPC64 = Subtarget.isPPC64();
  14433. bool is64Bit = isPPC64 && VT == LLT::scalar(64);
  14434. if (!is64Bit && VT != LLT::scalar(32))
  14435. report_fatal_error("Invalid register global variable type");
  14436. Register Reg = StringSwitch<Register>(RegName)
  14437. .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
  14438. .Case("r2", isPPC64 ? Register() : PPC::R2)
  14439. .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
  14440. .Default(Register());
  14441. if (Reg)
  14442. return Reg;
  14443. report_fatal_error("Invalid register name global variable");
  14444. }
  14445. bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
  14446. // 32-bit SVR4 ABI access everything as got-indirect.
  14447. if (Subtarget.is32BitELFABI())
  14448. return true;
  14449. // AIX accesses everything indirectly through the TOC, which is similar to
  14450. // the GOT.
  14451. if (Subtarget.isAIXABI())
  14452. return true;
  14453. CodeModel::Model CModel = getTargetMachine().getCodeModel();
  14454. // If it is small or large code model, module locals are accessed
  14455. // indirectly by loading their address from .toc/.got.
  14456. if (CModel == CodeModel::Small || CModel == CodeModel::Large)
  14457. return true;
  14458. // JumpTable and BlockAddress are accessed as got-indirect.
  14459. if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
  14460. return true;
  14461. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
  14462. return Subtarget.isGVIndirectSymbol(G->getGlobal());
  14463. return false;
  14464. }
  14465. bool
  14466. PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
  14467. // The PowerPC target isn't yet aware of offsets.
  14468. return false;
  14469. }
  14470. bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
  14471. const CallInst &I,
  14472. MachineFunction &MF,
  14473. unsigned Intrinsic) const {
  14474. switch (Intrinsic) {
  14475. case Intrinsic::ppc_atomicrmw_xchg_i128:
  14476. case Intrinsic::ppc_atomicrmw_add_i128:
  14477. case Intrinsic::ppc_atomicrmw_sub_i128:
  14478. case Intrinsic::ppc_atomicrmw_nand_i128:
  14479. case Intrinsic::ppc_atomicrmw_and_i128:
  14480. case Intrinsic::ppc_atomicrmw_or_i128:
  14481. case Intrinsic::ppc_atomicrmw_xor_i128:
  14482. case Intrinsic::ppc_cmpxchg_i128:
  14483. Info.opc = ISD::INTRINSIC_W_CHAIN;
  14484. Info.memVT = MVT::i128;
  14485. Info.ptrVal = I.getArgOperand(0);
  14486. Info.offset = 0;
  14487. Info.align = Align(16);
  14488. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
  14489. MachineMemOperand::MOVolatile;
  14490. return true;
  14491. case Intrinsic::ppc_atomic_load_i128:
  14492. Info.opc = ISD::INTRINSIC_W_CHAIN;
  14493. Info.memVT = MVT::i128;
  14494. Info.ptrVal = I.getArgOperand(0);
  14495. Info.offset = 0;
  14496. Info.align = Align(16);
  14497. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
  14498. return true;
  14499. case Intrinsic::ppc_atomic_store_i128:
  14500. Info.opc = ISD::INTRINSIC_VOID;
  14501. Info.memVT = MVT::i128;
  14502. Info.ptrVal = I.getArgOperand(2);
  14503. Info.offset = 0;
  14504. Info.align = Align(16);
  14505. Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
  14506. return true;
  14507. case Intrinsic::ppc_altivec_lvx:
  14508. case Intrinsic::ppc_altivec_lvxl:
  14509. case Intrinsic::ppc_altivec_lvebx:
  14510. case Intrinsic::ppc_altivec_lvehx:
  14511. case Intrinsic::ppc_altivec_lvewx:
  14512. case Intrinsic::ppc_vsx_lxvd2x:
  14513. case Intrinsic::ppc_vsx_lxvw4x:
  14514. case Intrinsic::ppc_vsx_lxvd2x_be:
  14515. case Intrinsic::ppc_vsx_lxvw4x_be:
  14516. case Intrinsic::ppc_vsx_lxvl:
  14517. case Intrinsic::ppc_vsx_lxvll: {
  14518. EVT VT;
  14519. switch (Intrinsic) {
  14520. case Intrinsic::ppc_altivec_lvebx:
  14521. VT = MVT::i8;
  14522. break;
  14523. case Intrinsic::ppc_altivec_lvehx:
  14524. VT = MVT::i16;
  14525. break;
  14526. case Intrinsic::ppc_altivec_lvewx:
  14527. VT = MVT::i32;
  14528. break;
  14529. case Intrinsic::ppc_vsx_lxvd2x:
  14530. case Intrinsic::ppc_vsx_lxvd2x_be:
  14531. VT = MVT::v2f64;
  14532. break;
  14533. default:
  14534. VT = MVT::v4i32;
  14535. break;
  14536. }
  14537. Info.opc = ISD::INTRINSIC_W_CHAIN;
  14538. Info.memVT = VT;
  14539. Info.ptrVal = I.getArgOperand(0);
  14540. Info.offset = -VT.getStoreSize()+1;
  14541. Info.size = 2*VT.getStoreSize()-1;
  14542. Info.align = Align(1);
  14543. Info.flags = MachineMemOperand::MOLoad;
  14544. return true;
  14545. }
  14546. case Intrinsic::ppc_altivec_stvx:
  14547. case Intrinsic::ppc_altivec_stvxl:
  14548. case Intrinsic::ppc_altivec_stvebx:
  14549. case Intrinsic::ppc_altivec_stvehx:
  14550. case Intrinsic::ppc_altivec_stvewx:
  14551. case Intrinsic::ppc_vsx_stxvd2x:
  14552. case Intrinsic::ppc_vsx_stxvw4x:
  14553. case Intrinsic::ppc_vsx_stxvd2x_be:
  14554. case Intrinsic::ppc_vsx_stxvw4x_be:
  14555. case Intrinsic::ppc_vsx_stxvl:
  14556. case Intrinsic::ppc_vsx_stxvll: {
  14557. EVT VT;
  14558. switch (Intrinsic) {
  14559. case Intrinsic::ppc_altivec_stvebx:
  14560. VT = MVT::i8;
  14561. break;
  14562. case Intrinsic::ppc_altivec_stvehx:
  14563. VT = MVT::i16;
  14564. break;
  14565. case Intrinsic::ppc_altivec_stvewx:
  14566. VT = MVT::i32;
  14567. break;
  14568. case Intrinsic::ppc_vsx_stxvd2x:
  14569. case Intrinsic::ppc_vsx_stxvd2x_be:
  14570. VT = MVT::v2f64;
  14571. break;
  14572. default:
  14573. VT = MVT::v4i32;
  14574. break;
  14575. }
  14576. Info.opc = ISD::INTRINSIC_VOID;
  14577. Info.memVT = VT;
  14578. Info.ptrVal = I.getArgOperand(1);
  14579. Info.offset = -VT.getStoreSize()+1;
  14580. Info.size = 2*VT.getStoreSize()-1;
  14581. Info.align = Align(1);
  14582. Info.flags = MachineMemOperand::MOStore;
  14583. return true;
  14584. }
  14585. default:
  14586. break;
  14587. }
  14588. return false;
  14589. }
  14590. /// It returns EVT::Other if the type should be determined using generic
  14591. /// target-independent logic.
  14592. EVT PPCTargetLowering::getOptimalMemOpType(
  14593. const MemOp &Op, const AttributeList &FuncAttributes) const {
  14594. if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
  14595. // We should use Altivec/VSX loads and stores when available. For unaligned
  14596. // addresses, unaligned VSX loads are only fast starting with the P8.
  14597. if (Subtarget.hasAltivec() && Op.size() >= 16 &&
  14598. (Op.isAligned(Align(16)) ||
  14599. ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
  14600. return MVT::v4i32;
  14601. }
  14602. if (Subtarget.isPPC64()) {
  14603. return MVT::i64;
  14604. }
  14605. return MVT::i32;
  14606. }
  14607. /// Returns true if it is beneficial to convert a load of a constant
  14608. /// to just the constant itself.
  14609. bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
  14610. Type *Ty) const {
  14611. assert(Ty->isIntegerTy());
  14612. unsigned BitSize = Ty->getPrimitiveSizeInBits();
  14613. return !(BitSize == 0 || BitSize > 64);
  14614. }
  14615. bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
  14616. if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
  14617. return false;
  14618. unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
  14619. unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
  14620. return NumBits1 == 64 && NumBits2 == 32;
  14621. }
  14622. bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
  14623. if (!VT1.isInteger() || !VT2.isInteger())
  14624. return false;
  14625. unsigned NumBits1 = VT1.getSizeInBits();
  14626. unsigned NumBits2 = VT2.getSizeInBits();
  14627. return NumBits1 == 64 && NumBits2 == 32;
  14628. }
  14629. bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
  14630. // Generally speaking, zexts are not free, but they are free when they can be
  14631. // folded with other operations.
  14632. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
  14633. EVT MemVT = LD->getMemoryVT();
  14634. if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
  14635. (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
  14636. (LD->getExtensionType() == ISD::NON_EXTLOAD ||
  14637. LD->getExtensionType() == ISD::ZEXTLOAD))
  14638. return true;
  14639. }
  14640. // FIXME: Add other cases...
  14641. // - 32-bit shifts with a zext to i64
  14642. // - zext after ctlz, bswap, etc.
  14643. // - zext after and by a constant mask
  14644. return TargetLowering::isZExtFree(Val, VT2);
  14645. }
  14646. bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
  14647. assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
  14648. "invalid fpext types");
  14649. // Extending to float128 is not free.
  14650. if (DestVT == MVT::f128)
  14651. return false;
  14652. return true;
  14653. }
  14654. bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
  14655. return isInt<16>(Imm) || isUInt<16>(Imm);
  14656. }
  14657. bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
  14658. return isInt<16>(Imm) || isUInt<16>(Imm);
  14659. }
  14660. bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
  14661. MachineMemOperand::Flags,
  14662. bool *Fast) const {
  14663. if (DisablePPCUnaligned)
  14664. return false;
  14665. // PowerPC supports unaligned memory access for simple non-vector types.
  14666. // Although accessing unaligned addresses is not as efficient as accessing
  14667. // aligned addresses, it is generally more efficient than manual expansion,
  14668. // and generally only traps for software emulation when crossing page
  14669. // boundaries.
  14670. if (!VT.isSimple())
  14671. return false;
  14672. if (VT.isFloatingPoint() && !VT.isVector() &&
  14673. !Subtarget.allowsUnalignedFPAccess())
  14674. return false;
  14675. if (VT.getSimpleVT().isVector()) {
  14676. if (Subtarget.hasVSX()) {
  14677. if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
  14678. VT != MVT::v4f32 && VT != MVT::v4i32)
  14679. return false;
  14680. } else {
  14681. return false;
  14682. }
  14683. }
  14684. if (VT == MVT::ppcf128)
  14685. return false;
  14686. if (Fast)
  14687. *Fast = true;
  14688. return true;
  14689. }
  14690. bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
  14691. SDValue C) const {
  14692. // Check integral scalar types.
  14693. if (!VT.isScalarInteger())
  14694. return false;
  14695. if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
  14696. if (!ConstNode->getAPIntValue().isSignedIntN(64))
  14697. return false;
  14698. // This transformation will generate >= 2 operations. But the following
  14699. // cases will generate <= 2 instructions during ISEL. So exclude them.
  14700. // 1. If the constant multiplier fits 16 bits, it can be handled by one
  14701. // HW instruction, ie. MULLI
  14702. // 2. If the multiplier after shifted fits 16 bits, an extra shift
  14703. // instruction is needed than case 1, ie. MULLI and RLDICR
  14704. int64_t Imm = ConstNode->getSExtValue();
  14705. unsigned Shift = countTrailingZeros<uint64_t>(Imm);
  14706. Imm >>= Shift;
  14707. if (isInt<16>(Imm))
  14708. return false;
  14709. uint64_t UImm = static_cast<uint64_t>(Imm);
  14710. if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
  14711. isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
  14712. return true;
  14713. }
  14714. return false;
  14715. }
  14716. bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
  14717. EVT VT) const {
  14718. return isFMAFasterThanFMulAndFAdd(
  14719. MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
  14720. }
  14721. bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
  14722. Type *Ty) const {
  14723. switch (Ty->getScalarType()->getTypeID()) {
  14724. case Type::FloatTyID:
  14725. case Type::DoubleTyID:
  14726. return true;
  14727. case Type::FP128TyID:
  14728. return Subtarget.hasP9Vector();
  14729. default:
  14730. return false;
  14731. }
  14732. }
  14733. // FIXME: add more patterns which are not profitable to hoist.
  14734. bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
  14735. if (!I->hasOneUse())
  14736. return true;
  14737. Instruction *User = I->user_back();
  14738. assert(User && "A single use instruction with no uses.");
  14739. switch (I->getOpcode()) {
  14740. case Instruction::FMul: {
  14741. // Don't break FMA, PowerPC prefers FMA.
  14742. if (User->getOpcode() != Instruction::FSub &&
  14743. User->getOpcode() != Instruction::FAdd)
  14744. return true;
  14745. const TargetOptions &Options = getTargetMachine().Options;
  14746. const Function *F = I->getFunction();
  14747. const DataLayout &DL = F->getParent()->getDataLayout();
  14748. Type *Ty = User->getOperand(0)->getType();
  14749. return !(
  14750. isFMAFasterThanFMulAndFAdd(*F, Ty) &&
  14751. isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
  14752. (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
  14753. }
  14754. case Instruction::Load: {
  14755. // Don't break "store (load float*)" pattern, this pattern will be combined
  14756. // to "store (load int32)" in later InstCombine pass. See function
  14757. // combineLoadToOperationType. On PowerPC, loading a float point takes more
  14758. // cycles than loading a 32 bit integer.
  14759. LoadInst *LI = cast<LoadInst>(I);
  14760. // For the loads that combineLoadToOperationType does nothing, like
  14761. // ordered load, it should be profitable to hoist them.
  14762. // For swifterror load, it can only be used for pointer to pointer type, so
  14763. // later type check should get rid of this case.
  14764. if (!LI->isUnordered())
  14765. return true;
  14766. if (User->getOpcode() != Instruction::Store)
  14767. return true;
  14768. if (I->getType()->getTypeID() != Type::FloatTyID)
  14769. return true;
  14770. return false;
  14771. }
  14772. default:
  14773. return true;
  14774. }
  14775. return true;
  14776. }
  14777. const MCPhysReg *
  14778. PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
  14779. // LR is a callee-save register, but we must treat it as clobbered by any call
  14780. // site. Hence we include LR in the scratch registers, which are in turn added
  14781. // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
  14782. // to CTR, which is used by any indirect call.
  14783. static const MCPhysReg ScratchRegs[] = {
  14784. PPC::X12, PPC::LR8, PPC::CTR8, 0
  14785. };
  14786. return ScratchRegs;
  14787. }
  14788. Register PPCTargetLowering::getExceptionPointerRegister(
  14789. const Constant *PersonalityFn) const {
  14790. return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
  14791. }
  14792. Register PPCTargetLowering::getExceptionSelectorRegister(
  14793. const Constant *PersonalityFn) const {
  14794. return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
  14795. }
  14796. bool
  14797. PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
  14798. EVT VT , unsigned DefinedValues) const {
  14799. if (VT == MVT::v2i64)
  14800. return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
  14801. if (Subtarget.hasVSX())
  14802. return true;
  14803. return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
  14804. }
  14805. Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
  14806. if (DisableILPPref || Subtarget.enableMachineScheduler())
  14807. return TargetLowering::getSchedulingPreference(N);
  14808. return Sched::ILP;
  14809. }
  14810. // Create a fast isel object.
  14811. FastISel *
  14812. PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
  14813. const TargetLibraryInfo *LibInfo) const {
  14814. return PPC::createFastISel(FuncInfo, LibInfo);
  14815. }
  14816. // 'Inverted' means the FMA opcode after negating one multiplicand.
  14817. // For example, (fma -a b c) = (fnmsub a b c)
  14818. static unsigned invertFMAOpcode(unsigned Opc) {
  14819. switch (Opc) {
  14820. default:
  14821. llvm_unreachable("Invalid FMA opcode for PowerPC!");
  14822. case ISD::FMA:
  14823. return PPCISD::FNMSUB;
  14824. case PPCISD::FNMSUB:
  14825. return ISD::FMA;
  14826. }
  14827. }
  14828. SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
  14829. bool LegalOps, bool OptForSize,
  14830. NegatibleCost &Cost,
  14831. unsigned Depth) const {
  14832. if (Depth > SelectionDAG::MaxRecursionDepth)
  14833. return SDValue();
  14834. unsigned Opc = Op.getOpcode();
  14835. EVT VT = Op.getValueType();
  14836. SDNodeFlags Flags = Op.getNode()->getFlags();
  14837. switch (Opc) {
  14838. case PPCISD::FNMSUB:
  14839. if (!Op.hasOneUse() || !isTypeLegal(VT))
  14840. break;
  14841. const TargetOptions &Options = getTargetMachine().Options;
  14842. SDValue N0 = Op.getOperand(0);
  14843. SDValue N1 = Op.getOperand(1);
  14844. SDValue N2 = Op.getOperand(2);
  14845. SDLoc Loc(Op);
  14846. NegatibleCost N2Cost = NegatibleCost::Expensive;
  14847. SDValue NegN2 =
  14848. getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
  14849. if (!NegN2)
  14850. return SDValue();
  14851. // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
  14852. // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
  14853. // These transformations may change sign of zeroes. For example,
  14854. // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
  14855. if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
  14856. // Try and choose the cheaper one to negate.
  14857. NegatibleCost N0Cost = NegatibleCost::Expensive;
  14858. SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
  14859. N0Cost, Depth + 1);
  14860. NegatibleCost N1Cost = NegatibleCost::Expensive;
  14861. SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
  14862. N1Cost, Depth + 1);
  14863. if (NegN0 && N0Cost <= N1Cost) {
  14864. Cost = std::min(N0Cost, N2Cost);
  14865. return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
  14866. } else if (NegN1) {
  14867. Cost = std::min(N1Cost, N2Cost);
  14868. return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
  14869. }
  14870. }
  14871. // (fneg (fnmsub a b c)) => (fma a b (fneg c))
  14872. if (isOperationLegal(ISD::FMA, VT)) {
  14873. Cost = N2Cost;
  14874. return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
  14875. }
  14876. break;
  14877. }
  14878. return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
  14879. Cost, Depth);
  14880. }
  14881. // Override to enable LOAD_STACK_GUARD lowering on Linux.
  14882. bool PPCTargetLowering::useLoadStackGuardNode() const {
  14883. if (!Subtarget.isTargetLinux())
  14884. return TargetLowering::useLoadStackGuardNode();
  14885. return true;
  14886. }
  14887. // Override to disable global variable loading on Linux and insert AIX canary
  14888. // word declaration.
  14889. void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
  14890. if (Subtarget.isAIXABI()) {
  14891. M.getOrInsertGlobal(AIXSSPCanaryWordName,
  14892. Type::getInt8PtrTy(M.getContext()));
  14893. return;
  14894. }
  14895. if (!Subtarget.isTargetLinux())
  14896. return TargetLowering::insertSSPDeclarations(M);
  14897. }
  14898. Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
  14899. if (Subtarget.isAIXABI())
  14900. return M.getGlobalVariable(AIXSSPCanaryWordName);
  14901. return TargetLowering::getSDagStackGuard(M);
  14902. }
  14903. bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
  14904. bool ForCodeSize) const {
  14905. if (!VT.isSimple() || !Subtarget.hasVSX())
  14906. return false;
  14907. switch(VT.getSimpleVT().SimpleTy) {
  14908. default:
  14909. // For FP types that are currently not supported by PPC backend, return
  14910. // false. Examples: f16, f80.
  14911. return false;
  14912. case MVT::f32:
  14913. case MVT::f64:
  14914. if (Subtarget.hasPrefixInstrs()) {
  14915. // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
  14916. return true;
  14917. }
  14918. LLVM_FALLTHROUGH;
  14919. case MVT::ppcf128:
  14920. return Imm.isPosZero();
  14921. }
  14922. }
  14923. // For vector shift operation op, fold
  14924. // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
  14925. static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
  14926. SelectionDAG &DAG) {
  14927. SDValue N0 = N->getOperand(0);
  14928. SDValue N1 = N->getOperand(1);
  14929. EVT VT = N0.getValueType();
  14930. unsigned OpSizeInBits = VT.getScalarSizeInBits();
  14931. unsigned Opcode = N->getOpcode();
  14932. unsigned TargetOpcode;
  14933. switch (Opcode) {
  14934. default:
  14935. llvm_unreachable("Unexpected shift operation");
  14936. case ISD::SHL:
  14937. TargetOpcode = PPCISD::SHL;
  14938. break;
  14939. case ISD::SRL:
  14940. TargetOpcode = PPCISD::SRL;
  14941. break;
  14942. case ISD::SRA:
  14943. TargetOpcode = PPCISD::SRA;
  14944. break;
  14945. }
  14946. if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
  14947. N1->getOpcode() == ISD::AND)
  14948. if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
  14949. if (Mask->getZExtValue() == OpSizeInBits - 1)
  14950. return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
  14951. return SDValue();
  14952. }
  14953. SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
  14954. if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
  14955. return Value;
  14956. SDValue N0 = N->getOperand(0);
  14957. ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
  14958. if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
  14959. N0.getOpcode() != ISD::SIGN_EXTEND ||
  14960. N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
  14961. N->getValueType(0) != MVT::i64)
  14962. return SDValue();
  14963. // We can't save an operation here if the value is already extended, and
  14964. // the existing shift is easier to combine.
  14965. SDValue ExtsSrc = N0.getOperand(0);
  14966. if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
  14967. ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
  14968. return SDValue();
  14969. SDLoc DL(N0);
  14970. SDValue ShiftBy = SDValue(CN1, 0);
  14971. // We want the shift amount to be i32 on the extswli, but the shift could
  14972. // have an i64.
  14973. if (ShiftBy.getValueType() == MVT::i64)
  14974. ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
  14975. return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
  14976. ShiftBy);
  14977. }
  14978. SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
  14979. if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
  14980. return Value;
  14981. return SDValue();
  14982. }
  14983. SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
  14984. if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
  14985. return Value;
  14986. return SDValue();
  14987. }
  14988. // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
  14989. // Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
  14990. // When C is zero, the equation (addi Z, -C) can be simplified to Z
  14991. // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
  14992. static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
  14993. const PPCSubtarget &Subtarget) {
  14994. if (!Subtarget.isPPC64())
  14995. return SDValue();
  14996. SDValue LHS = N->getOperand(0);
  14997. SDValue RHS = N->getOperand(1);
  14998. auto isZextOfCompareWithConstant = [](SDValue Op) {
  14999. if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
  15000. Op.getValueType() != MVT::i64)
  15001. return false;
  15002. SDValue Cmp = Op.getOperand(0);
  15003. if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
  15004. Cmp.getOperand(0).getValueType() != MVT::i64)
  15005. return false;
  15006. if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
  15007. int64_t NegConstant = 0 - Constant->getSExtValue();
  15008. // Due to the limitations of the addi instruction,
  15009. // -C is required to be [-32768, 32767].
  15010. return isInt<16>(NegConstant);
  15011. }
  15012. return false;
  15013. };
  15014. bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
  15015. bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
  15016. // If there is a pattern, canonicalize a zext operand to the RHS.
  15017. if (LHSHasPattern && !RHSHasPattern)
  15018. std::swap(LHS, RHS);
  15019. else if (!LHSHasPattern && !RHSHasPattern)
  15020. return SDValue();
  15021. SDLoc DL(N);
  15022. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
  15023. SDValue Cmp = RHS.getOperand(0);
  15024. SDValue Z = Cmp.getOperand(0);
  15025. auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
  15026. int64_t NegConstant = 0 - Constant->getSExtValue();
  15027. switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
  15028. default: break;
  15029. case ISD::SETNE: {
  15030. // when C == 0
  15031. // --> addze X, (addic Z, -1).carry
  15032. // /
  15033. // add X, (zext(setne Z, C))--
  15034. // \ when -32768 <= -C <= 32767 && C != 0
  15035. // --> addze X, (addic (addi Z, -C), -1).carry
  15036. SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
  15037. DAG.getConstant(NegConstant, DL, MVT::i64));
  15038. SDValue AddOrZ = NegConstant != 0 ? Add : Z;
  15039. SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
  15040. AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
  15041. return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
  15042. SDValue(Addc.getNode(), 1));
  15043. }
  15044. case ISD::SETEQ: {
  15045. // when C == 0
  15046. // --> addze X, (subfic Z, 0).carry
  15047. // /
  15048. // add X, (zext(sete Z, C))--
  15049. // \ when -32768 <= -C <= 32767 && C != 0
  15050. // --> addze X, (subfic (addi Z, -C), 0).carry
  15051. SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
  15052. DAG.getConstant(NegConstant, DL, MVT::i64));
  15053. SDValue AddOrZ = NegConstant != 0 ? Add : Z;
  15054. SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
  15055. DAG.getConstant(0, DL, MVT::i64), AddOrZ);
  15056. return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
  15057. SDValue(Subc.getNode(), 1));
  15058. }
  15059. }
  15060. return SDValue();
  15061. }
  15062. // Transform
  15063. // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
  15064. // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
  15065. // In this case both C1 and C2 must be known constants.
  15066. // C1+C2 must fit into a 34 bit signed integer.
  15067. static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
  15068. const PPCSubtarget &Subtarget) {
  15069. if (!Subtarget.isUsingPCRelativeCalls())
  15070. return SDValue();
  15071. // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
  15072. // If we find that node try to cast the Global Address and the Constant.
  15073. SDValue LHS = N->getOperand(0);
  15074. SDValue RHS = N->getOperand(1);
  15075. if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
  15076. std::swap(LHS, RHS);
  15077. if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
  15078. return SDValue();
  15079. // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
  15080. GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
  15081. ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
  15082. // Check that both casts succeeded.
  15083. if (!GSDN || !ConstNode)
  15084. return SDValue();
  15085. int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
  15086. SDLoc DL(GSDN);
  15087. // The signed int offset needs to fit in 34 bits.
  15088. if (!isInt<34>(NewOffset))
  15089. return SDValue();
  15090. // The new global address is a copy of the old global address except
  15091. // that it has the updated Offset.
  15092. SDValue GA =
  15093. DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
  15094. NewOffset, GSDN->getTargetFlags());
  15095. SDValue MatPCRel =
  15096. DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
  15097. return MatPCRel;
  15098. }
  15099. SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
  15100. if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
  15101. return Value;
  15102. if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
  15103. return Value;
  15104. return SDValue();
  15105. }
  15106. // Detect TRUNCATE operations on bitcasts of float128 values.
  15107. // What we are looking for here is the situtation where we extract a subset
  15108. // of bits from a 128 bit float.
  15109. // This can be of two forms:
  15110. // 1) BITCAST of f128 feeding TRUNCATE
  15111. // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
  15112. // The reason this is required is because we do not have a legal i128 type
  15113. // and so we want to prevent having to store the f128 and then reload part
  15114. // of it.
  15115. SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
  15116. DAGCombinerInfo &DCI) const {
  15117. // If we are using CRBits then try that first.
  15118. if (Subtarget.useCRBits()) {
  15119. // Check if CRBits did anything and return that if it did.
  15120. if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
  15121. return CRTruncValue;
  15122. }
  15123. SDLoc dl(N);
  15124. SDValue Op0 = N->getOperand(0);
  15125. // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
  15126. if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
  15127. EVT VT = N->getValueType(0);
  15128. if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
  15129. return SDValue();
  15130. SDValue Sub = Op0.getOperand(0);
  15131. if (Sub.getOpcode() == ISD::SUB) {
  15132. SDValue SubOp0 = Sub.getOperand(0);
  15133. SDValue SubOp1 = Sub.getOperand(1);
  15134. if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
  15135. (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
  15136. return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
  15137. SubOp1.getOperand(0),
  15138. DCI.DAG.getTargetConstant(0, dl, MVT::i32));
  15139. }
  15140. }
  15141. }
  15142. // Looking for a truncate of i128 to i64.
  15143. if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
  15144. return SDValue();
  15145. int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
  15146. // SRL feeding TRUNCATE.
  15147. if (Op0.getOpcode() == ISD::SRL) {
  15148. ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
  15149. // The right shift has to be by 64 bits.
  15150. if (!ConstNode || ConstNode->getZExtValue() != 64)
  15151. return SDValue();
  15152. // Switch the element number to extract.
  15153. EltToExtract = EltToExtract ? 0 : 1;
  15154. // Update Op0 past the SRL.
  15155. Op0 = Op0.getOperand(0);
  15156. }
  15157. // BITCAST feeding a TRUNCATE possibly via SRL.
  15158. if (Op0.getOpcode() == ISD::BITCAST &&
  15159. Op0.getValueType() == MVT::i128 &&
  15160. Op0.getOperand(0).getValueType() == MVT::f128) {
  15161. SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
  15162. return DCI.DAG.getNode(
  15163. ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
  15164. DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
  15165. }
  15166. return SDValue();
  15167. }
  15168. SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
  15169. SelectionDAG &DAG = DCI.DAG;
  15170. ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
  15171. if (!ConstOpOrElement)
  15172. return SDValue();
  15173. // An imul is usually smaller than the alternative sequence for legal type.
  15174. if (DAG.getMachineFunction().getFunction().hasMinSize() &&
  15175. isOperationLegal(ISD::MUL, N->getValueType(0)))
  15176. return SDValue();
  15177. auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
  15178. switch (this->Subtarget.getCPUDirective()) {
  15179. default:
  15180. // TODO: enhance the condition for subtarget before pwr8
  15181. return false;
  15182. case PPC::DIR_PWR8:
  15183. // type mul add shl
  15184. // scalar 4 1 1
  15185. // vector 7 2 2
  15186. return true;
  15187. case PPC::DIR_PWR9:
  15188. case PPC::DIR_PWR10:
  15189. case PPC::DIR_PWR_FUTURE:
  15190. // type mul add shl
  15191. // scalar 5 2 2
  15192. // vector 7 2 2
  15193. // The cycle RATIO of related operations are showed as a table above.
  15194. // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
  15195. // scalar and vector type. For 2 instrs patterns, add/sub + shl
  15196. // are 4, it is always profitable; but for 3 instrs patterns
  15197. // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
  15198. // So we should only do it for vector type.
  15199. return IsAddOne && IsNeg ? VT.isVector() : true;
  15200. }
  15201. };
  15202. EVT VT = N->getValueType(0);
  15203. SDLoc DL(N);
  15204. const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
  15205. bool IsNeg = MulAmt.isNegative();
  15206. APInt MulAmtAbs = MulAmt.abs();
  15207. if ((MulAmtAbs - 1).isPowerOf2()) {
  15208. // (mul x, 2^N + 1) => (add (shl x, N), x)
  15209. // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
  15210. if (!IsProfitable(IsNeg, true, VT))
  15211. return SDValue();
  15212. SDValue Op0 = N->getOperand(0);
  15213. SDValue Op1 =
  15214. DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
  15215. DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
  15216. SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
  15217. if (!IsNeg)
  15218. return Res;
  15219. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
  15220. } else if ((MulAmtAbs + 1).isPowerOf2()) {
  15221. // (mul x, 2^N - 1) => (sub (shl x, N), x)
  15222. // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
  15223. if (!IsProfitable(IsNeg, false, VT))
  15224. return SDValue();
  15225. SDValue Op0 = N->getOperand(0);
  15226. SDValue Op1 =
  15227. DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
  15228. DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
  15229. if (!IsNeg)
  15230. return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
  15231. else
  15232. return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
  15233. } else {
  15234. return SDValue();
  15235. }
  15236. }
  15237. // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
  15238. // in combiner since we need to check SD flags and other subtarget features.
  15239. SDValue PPCTargetLowering::combineFMALike(SDNode *N,
  15240. DAGCombinerInfo &DCI) const {
  15241. SDValue N0 = N->getOperand(0);
  15242. SDValue N1 = N->getOperand(1);
  15243. SDValue N2 = N->getOperand(2);
  15244. SDNodeFlags Flags = N->getFlags();
  15245. EVT VT = N->getValueType(0);
  15246. SelectionDAG &DAG = DCI.DAG;
  15247. const TargetOptions &Options = getTargetMachine().Options;
  15248. unsigned Opc = N->getOpcode();
  15249. bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
  15250. bool LegalOps = !DCI.isBeforeLegalizeOps();
  15251. SDLoc Loc(N);
  15252. if (!isOperationLegal(ISD::FMA, VT))
  15253. return SDValue();
  15254. // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
  15255. // since (fnmsub a b c)=-0 while c-ab=+0.
  15256. if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
  15257. return SDValue();
  15258. // (fma (fneg a) b c) => (fnmsub a b c)
  15259. // (fnmsub (fneg a) b c) => (fma a b c)
  15260. if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
  15261. return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
  15262. // (fma a (fneg b) c) => (fnmsub a b c)
  15263. // (fnmsub a (fneg b) c) => (fma a b c)
  15264. if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
  15265. return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
  15266. return SDValue();
  15267. }
  15268. bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
  15269. // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
  15270. if (!Subtarget.is64BitELFABI())
  15271. return false;
  15272. // If not a tail call then no need to proceed.
  15273. if (!CI->isTailCall())
  15274. return false;
  15275. // If sibling calls have been disabled and tail-calls aren't guaranteed
  15276. // there is no reason to duplicate.
  15277. auto &TM = getTargetMachine();
  15278. if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
  15279. return false;
  15280. // Can't tail call a function called indirectly, or if it has variadic args.
  15281. const Function *Callee = CI->getCalledFunction();
  15282. if (!Callee || Callee->isVarArg())
  15283. return false;
  15284. // Make sure the callee and caller calling conventions are eligible for tco.
  15285. const Function *Caller = CI->getParent()->getParent();
  15286. if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
  15287. CI->getCallingConv()))
  15288. return false;
  15289. // If the function is local then we have a good chance at tail-calling it
  15290. return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
  15291. }
  15292. bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
  15293. if (!Subtarget.hasVSX())
  15294. return false;
  15295. if (Subtarget.hasP9Vector() && VT == MVT::f128)
  15296. return true;
  15297. return VT == MVT::f32 || VT == MVT::f64 ||
  15298. VT == MVT::v4f32 || VT == MVT::v2f64;
  15299. }
  15300. bool PPCTargetLowering::
  15301. isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
  15302. const Value *Mask = AndI.getOperand(1);
  15303. // If the mask is suitable for andi. or andis. we should sink the and.
  15304. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
  15305. // Can't handle constants wider than 64-bits.
  15306. if (CI->getBitWidth() > 64)
  15307. return false;
  15308. int64_t ConstVal = CI->getZExtValue();
  15309. return isUInt<16>(ConstVal) ||
  15310. (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
  15311. }
  15312. // For non-constant masks, we can always use the record-form and.
  15313. return true;
  15314. }
  15315. // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
  15316. // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
  15317. // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
  15318. // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
  15319. // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
  15320. SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
  15321. assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
  15322. assert(Subtarget.hasP9Altivec() &&
  15323. "Only combine this when P9 altivec supported!");
  15324. EVT VT = N->getValueType(0);
  15325. if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
  15326. return SDValue();
  15327. SelectionDAG &DAG = DCI.DAG;
  15328. SDLoc dl(N);
  15329. if (N->getOperand(0).getOpcode() == ISD::SUB) {
  15330. // Even for signed integers, if it's known to be positive (as signed
  15331. // integer) due to zero-extended inputs.
  15332. unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
  15333. unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
  15334. if ((SubOpcd0 == ISD::ZERO_EXTEND ||
  15335. SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
  15336. (SubOpcd1 == ISD::ZERO_EXTEND ||
  15337. SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
  15338. return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
  15339. N->getOperand(0)->getOperand(0),
  15340. N->getOperand(0)->getOperand(1),
  15341. DAG.getTargetConstant(0, dl, MVT::i32));
  15342. }
  15343. // For type v4i32, it can be optimized with xvnegsp + vabsduw
  15344. if (N->getOperand(0).getValueType() == MVT::v4i32 &&
  15345. N->getOperand(0).hasOneUse()) {
  15346. return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
  15347. N->getOperand(0)->getOperand(0),
  15348. N->getOperand(0)->getOperand(1),
  15349. DAG.getTargetConstant(1, dl, MVT::i32));
  15350. }
  15351. }
  15352. return SDValue();
  15353. }
  15354. // For type v4i32/v8ii16/v16i8, transform
  15355. // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
  15356. // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
  15357. // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
  15358. // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
  15359. SDValue PPCTargetLowering::combineVSelect(SDNode *N,
  15360. DAGCombinerInfo &DCI) const {
  15361. assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
  15362. assert(Subtarget.hasP9Altivec() &&
  15363. "Only combine this when P9 altivec supported!");
  15364. SelectionDAG &DAG = DCI.DAG;
  15365. SDLoc dl(N);
  15366. SDValue Cond = N->getOperand(0);
  15367. SDValue TrueOpnd = N->getOperand(1);
  15368. SDValue FalseOpnd = N->getOperand(2);
  15369. EVT VT = N->getOperand(1).getValueType();
  15370. if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
  15371. FalseOpnd.getOpcode() != ISD::SUB)
  15372. return SDValue();
  15373. // ABSD only available for type v4i32/v8i16/v16i8
  15374. if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
  15375. return SDValue();
  15376. // At least to save one more dependent computation
  15377. if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
  15378. return SDValue();
  15379. ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
  15380. // Can only handle unsigned comparison here
  15381. switch (CC) {
  15382. default:
  15383. return SDValue();
  15384. case ISD::SETUGT:
  15385. case ISD::SETUGE:
  15386. break;
  15387. case ISD::SETULT:
  15388. case ISD::SETULE:
  15389. std::swap(TrueOpnd, FalseOpnd);
  15390. break;
  15391. }
  15392. SDValue CmpOpnd1 = Cond.getOperand(0);
  15393. SDValue CmpOpnd2 = Cond.getOperand(1);
  15394. // SETCC CmpOpnd1 CmpOpnd2 cond
  15395. // TrueOpnd = CmpOpnd1 - CmpOpnd2
  15396. // FalseOpnd = CmpOpnd2 - CmpOpnd1
  15397. if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
  15398. TrueOpnd.getOperand(1) == CmpOpnd2 &&
  15399. FalseOpnd.getOperand(0) == CmpOpnd2 &&
  15400. FalseOpnd.getOperand(1) == CmpOpnd1) {
  15401. return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
  15402. CmpOpnd1, CmpOpnd2,
  15403. DAG.getTargetConstant(0, dl, MVT::i32));
  15404. }
  15405. return SDValue();
  15406. }
  15407. /// getAddrModeForFlags - Based on the set of address flags, select the most
  15408. /// optimal instruction format to match by.
  15409. PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
  15410. // This is not a node we should be handling here.
  15411. if (Flags == PPC::MOF_None)
  15412. return PPC::AM_None;
  15413. // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
  15414. for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
  15415. if ((Flags & FlagSet) == FlagSet)
  15416. return PPC::AM_DForm;
  15417. for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
  15418. if ((Flags & FlagSet) == FlagSet)
  15419. return PPC::AM_DSForm;
  15420. for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
  15421. if ((Flags & FlagSet) == FlagSet)
  15422. return PPC::AM_DQForm;
  15423. for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
  15424. if ((Flags & FlagSet) == FlagSet)
  15425. return PPC::AM_PrefixDForm;
  15426. // If no other forms are selected, return an X-Form as it is the most
  15427. // general addressing mode.
  15428. return PPC::AM_XForm;
  15429. }
  15430. /// Set alignment flags based on whether or not the Frame Index is aligned.
  15431. /// Utilized when computing flags for address computation when selecting
  15432. /// load and store instructions.
  15433. static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
  15434. SelectionDAG &DAG) {
  15435. bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
  15436. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
  15437. if (!FI)
  15438. return;
  15439. const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  15440. unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
  15441. // If this is (add $FI, $S16Imm), the alignment flags are already set
  15442. // based on the immediate. We just need to clear the alignment flags
  15443. // if the FI alignment is weaker.
  15444. if ((FrameIndexAlign % 4) != 0)
  15445. FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
  15446. if ((FrameIndexAlign % 16) != 0)
  15447. FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
  15448. // If the address is a plain FrameIndex, set alignment flags based on
  15449. // FI alignment.
  15450. if (!IsAdd) {
  15451. if ((FrameIndexAlign % 4) == 0)
  15452. FlagSet |= PPC::MOF_RPlusSImm16Mult4;
  15453. if ((FrameIndexAlign % 16) == 0)
  15454. FlagSet |= PPC::MOF_RPlusSImm16Mult16;
  15455. }
  15456. }
  15457. /// Given a node, compute flags that are used for address computation when
  15458. /// selecting load and store instructions. The flags computed are stored in
  15459. /// FlagSet. This function takes into account whether the node is a constant,
  15460. /// an ADD, OR, or a constant, and computes the address flags accordingly.
  15461. static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
  15462. SelectionDAG &DAG) {
  15463. // Set the alignment flags for the node depending on if the node is
  15464. // 4-byte or 16-byte aligned.
  15465. auto SetAlignFlagsForImm = [&](uint64_t Imm) {
  15466. if ((Imm & 0x3) == 0)
  15467. FlagSet |= PPC::MOF_RPlusSImm16Mult4;
  15468. if ((Imm & 0xf) == 0)
  15469. FlagSet |= PPC::MOF_RPlusSImm16Mult16;
  15470. };
  15471. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
  15472. // All 32-bit constants can be computed as LIS + Disp.
  15473. const APInt &ConstImm = CN->getAPIntValue();
  15474. if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
  15475. FlagSet |= PPC::MOF_AddrIsSImm32;
  15476. SetAlignFlagsForImm(ConstImm.getZExtValue());
  15477. setAlignFlagsForFI(N, FlagSet, DAG);
  15478. }
  15479. if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
  15480. FlagSet |= PPC::MOF_RPlusSImm34;
  15481. else // Let constant materialization handle large constants.
  15482. FlagSet |= PPC::MOF_NotAddNorCst;
  15483. } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
  15484. // This address can be represented as an addition of:
  15485. // - Register + Imm16 (possibly a multiple of 4/16)
  15486. // - Register + Imm34
  15487. // - Register + PPCISD::Lo
  15488. // - Register + Register
  15489. // In any case, we won't have to match this as Base + Zero.
  15490. SDValue RHS = N.getOperand(1);
  15491. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
  15492. const APInt &ConstImm = CN->getAPIntValue();
  15493. if (ConstImm.isSignedIntN(16)) {
  15494. FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
  15495. SetAlignFlagsForImm(ConstImm.getZExtValue());
  15496. setAlignFlagsForFI(N, FlagSet, DAG);
  15497. }
  15498. if (ConstImm.isSignedIntN(34))
  15499. FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
  15500. else
  15501. FlagSet |= PPC::MOF_RPlusR; // Register.
  15502. } else if (RHS.getOpcode() == PPCISD::Lo &&
  15503. !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
  15504. FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
  15505. else
  15506. FlagSet |= PPC::MOF_RPlusR;
  15507. } else { // The address computation is not a constant or an addition.
  15508. setAlignFlagsForFI(N, FlagSet, DAG);
  15509. FlagSet |= PPC::MOF_NotAddNorCst;
  15510. }
  15511. }
  15512. static bool isPCRelNode(SDValue N) {
  15513. return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
  15514. isValidPCRelNode<ConstantPoolSDNode>(N) ||
  15515. isValidPCRelNode<GlobalAddressSDNode>(N) ||
  15516. isValidPCRelNode<JumpTableSDNode>(N) ||
  15517. isValidPCRelNode<BlockAddressSDNode>(N));
  15518. }
  15519. /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
  15520. /// the address flags of the load/store instruction that is to be matched.
  15521. unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
  15522. SelectionDAG &DAG) const {
  15523. unsigned FlagSet = PPC::MOF_None;
  15524. // Compute subtarget flags.
  15525. if (!Subtarget.hasP9Vector())
  15526. FlagSet |= PPC::MOF_SubtargetBeforeP9;
  15527. else {
  15528. FlagSet |= PPC::MOF_SubtargetP9;
  15529. if (Subtarget.hasPrefixInstrs())
  15530. FlagSet |= PPC::MOF_SubtargetP10;
  15531. }
  15532. if (Subtarget.hasSPE())
  15533. FlagSet |= PPC::MOF_SubtargetSPE;
  15534. // Check if we have a PCRel node and return early.
  15535. if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
  15536. return FlagSet;
  15537. // If the node is the paired load/store intrinsics, compute flags for
  15538. // address computation and return early.
  15539. unsigned ParentOp = Parent->getOpcode();
  15540. if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
  15541. (ParentOp == ISD::INTRINSIC_VOID))) {
  15542. unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
  15543. if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
  15544. SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
  15545. ? Parent->getOperand(2)
  15546. : Parent->getOperand(3);
  15547. computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
  15548. FlagSet |= PPC::MOF_Vector;
  15549. return FlagSet;
  15550. }
  15551. }
  15552. // Mark this as something we don't want to handle here if it is atomic
  15553. // or pre-increment instruction.
  15554. if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
  15555. if (LSB->isIndexed())
  15556. return PPC::MOF_None;
  15557. // Compute in-memory type flags. This is based on if there are scalars,
  15558. // floats or vectors.
  15559. const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
  15560. assert(MN && "Parent should be a MemSDNode!");
  15561. EVT MemVT = MN->getMemoryVT();
  15562. unsigned Size = MemVT.getSizeInBits();
  15563. if (MemVT.isScalarInteger()) {
  15564. assert(Size <= 128 &&
  15565. "Not expecting scalar integers larger than 16 bytes!");
  15566. if (Size < 32)
  15567. FlagSet |= PPC::MOF_SubWordInt;
  15568. else if (Size == 32)
  15569. FlagSet |= PPC::MOF_WordInt;
  15570. else
  15571. FlagSet |= PPC::MOF_DoubleWordInt;
  15572. } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
  15573. if (Size == 128)
  15574. FlagSet |= PPC::MOF_Vector;
  15575. else if (Size == 256) {
  15576. assert(Subtarget.pairedVectorMemops() &&
  15577. "256-bit vectors are only available when paired vector memops is "
  15578. "enabled!");
  15579. FlagSet |= PPC::MOF_Vector;
  15580. } else
  15581. llvm_unreachable("Not expecting illegal vectors!");
  15582. } else { // Floating point type: can be scalar, f128 or vector types.
  15583. if (Size == 32 || Size == 64)
  15584. FlagSet |= PPC::MOF_ScalarFloat;
  15585. else if (MemVT == MVT::f128 || MemVT.isVector())
  15586. FlagSet |= PPC::MOF_Vector;
  15587. else
  15588. llvm_unreachable("Not expecting illegal scalar floats!");
  15589. }
  15590. // Compute flags for address computation.
  15591. computeFlagsForAddressComputation(N, FlagSet, DAG);
  15592. // Compute type extension flags.
  15593. if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
  15594. switch (LN->getExtensionType()) {
  15595. case ISD::SEXTLOAD:
  15596. FlagSet |= PPC::MOF_SExt;
  15597. break;
  15598. case ISD::EXTLOAD:
  15599. case ISD::ZEXTLOAD:
  15600. FlagSet |= PPC::MOF_ZExt;
  15601. break;
  15602. case ISD::NON_EXTLOAD:
  15603. FlagSet |= PPC::MOF_NoExt;
  15604. break;
  15605. }
  15606. } else
  15607. FlagSet |= PPC::MOF_NoExt;
  15608. // For integers, no extension is the same as zero extension.
  15609. // We set the extension mode to zero extension so we don't have
  15610. // to add separate entries in AddrModesMap for loads and stores.
  15611. if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
  15612. FlagSet |= PPC::MOF_ZExt;
  15613. FlagSet &= ~PPC::MOF_NoExt;
  15614. }
  15615. // If we don't have prefixed instructions, 34-bit constants should be
  15616. // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
  15617. bool IsNonP1034BitConst =
  15618. ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
  15619. FlagSet) == PPC::MOF_RPlusSImm34;
  15620. if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
  15621. IsNonP1034BitConst)
  15622. FlagSet |= PPC::MOF_NotAddNorCst;
  15623. return FlagSet;
  15624. }
  15625. /// SelectForceXFormMode - Given the specified address, force it to be
  15626. /// represented as an indexed [r+r] operation (an XForm instruction).
  15627. PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
  15628. SDValue &Base,
  15629. SelectionDAG &DAG) const {
  15630. PPC::AddrMode Mode = PPC::AM_XForm;
  15631. int16_t ForceXFormImm = 0;
  15632. if (provablyDisjointOr(DAG, N) &&
  15633. !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
  15634. Disp = N.getOperand(0);
  15635. Base = N.getOperand(1);
  15636. return Mode;
  15637. }
  15638. // If the address is the result of an add, we will utilize the fact that the
  15639. // address calculation includes an implicit add. However, we can reduce
  15640. // register pressure if we do not materialize a constant just for use as the
  15641. // index register. We only get rid of the add if it is not an add of a
  15642. // value and a 16-bit signed constant and both have a single use.
  15643. if (N.getOpcode() == ISD::ADD &&
  15644. (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
  15645. !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
  15646. Disp = N.getOperand(0);
  15647. Base = N.getOperand(1);
  15648. return Mode;
  15649. }
  15650. // Otherwise, use R0 as the base register.
  15651. Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  15652. N.getValueType());
  15653. Base = N;
  15654. return Mode;
  15655. }
  15656. bool PPCTargetLowering::splitValueIntoRegisterParts(
  15657. SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
  15658. unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
  15659. EVT ValVT = Val.getValueType();
  15660. // If we are splitting a scalar integer into f64 parts (i.e. so they
  15661. // can be placed into VFRC registers), we need to zero extend and
  15662. // bitcast the values. This will ensure the value is placed into a
  15663. // VSR using direct moves or stack operations as needed.
  15664. if (PartVT == MVT::f64 &&
  15665. (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
  15666. Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
  15667. Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
  15668. Parts[0] = Val;
  15669. return true;
  15670. }
  15671. return false;
  15672. }
  15673. // If we happen to match to an aligned D-Form, check if the Frame Index is
  15674. // adequately aligned. If it is not, reset the mode to match to X-Form.
  15675. static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
  15676. PPC::AddrMode &Mode) {
  15677. if (!isa<FrameIndexSDNode>(N))
  15678. return;
  15679. if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
  15680. (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
  15681. Mode = PPC::AM_XForm;
  15682. }
  15683. /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
  15684. /// compute the address flags of the node, get the optimal address mode based
  15685. /// on the flags, and set the Base and Disp based on the address mode.
  15686. PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
  15687. SDValue N, SDValue &Disp,
  15688. SDValue &Base,
  15689. SelectionDAG &DAG,
  15690. MaybeAlign Align) const {
  15691. SDLoc DL(Parent);
  15692. // Compute the address flags.
  15693. unsigned Flags = computeMOFlags(Parent, N, DAG);
  15694. // Get the optimal address mode based on the Flags.
  15695. PPC::AddrMode Mode = getAddrModeForFlags(Flags);
  15696. // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
  15697. // Select an X-Form load if it is not.
  15698. setXFormForUnalignedFI(N, Flags, Mode);
  15699. // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
  15700. if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
  15701. assert(Subtarget.isUsingPCRelativeCalls() &&
  15702. "Must be using PC-Relative calls when a valid PC-Relative node is "
  15703. "present!");
  15704. Mode = PPC::AM_PCRel;
  15705. }
  15706. // Set Base and Disp accordingly depending on the address mode.
  15707. switch (Mode) {
  15708. case PPC::AM_DForm:
  15709. case PPC::AM_DSForm:
  15710. case PPC::AM_DQForm: {
  15711. // This is a register plus a 16-bit immediate. The base will be the
  15712. // register and the displacement will be the immediate unless it
  15713. // isn't sufficiently aligned.
  15714. if (Flags & PPC::MOF_RPlusSImm16) {
  15715. SDValue Op0 = N.getOperand(0);
  15716. SDValue Op1 = N.getOperand(1);
  15717. int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
  15718. if (!Align || isAligned(*Align, Imm)) {
  15719. Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
  15720. Base = Op0;
  15721. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
  15722. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  15723. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  15724. }
  15725. break;
  15726. }
  15727. }
  15728. // This is a register plus the @lo relocation. The base is the register
  15729. // and the displacement is the global address.
  15730. else if (Flags & PPC::MOF_RPlusLo) {
  15731. Disp = N.getOperand(1).getOperand(0); // The global address.
  15732. assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
  15733. Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
  15734. Disp.getOpcode() == ISD::TargetConstantPool ||
  15735. Disp.getOpcode() == ISD::TargetJumpTable);
  15736. Base = N.getOperand(0);
  15737. break;
  15738. }
  15739. // This is a constant address at most 32 bits. The base will be
  15740. // zero or load-immediate-shifted and the displacement will be
  15741. // the low 16 bits of the address.
  15742. else if (Flags & PPC::MOF_AddrIsSImm32) {
  15743. auto *CN = cast<ConstantSDNode>(N);
  15744. EVT CNType = CN->getValueType(0);
  15745. uint64_t CNImm = CN->getZExtValue();
  15746. // If this address fits entirely in a 16-bit sext immediate field, codegen
  15747. // this as "d, 0".
  15748. int16_t Imm;
  15749. if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
  15750. Disp = DAG.getTargetConstant(Imm, DL, CNType);
  15751. Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  15752. CNType);
  15753. break;
  15754. }
  15755. // Handle 32-bit sext immediate with LIS + Addr mode.
  15756. if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
  15757. (!Align || isAligned(*Align, CNImm))) {
  15758. int32_t Addr = (int32_t)CNImm;
  15759. // Otherwise, break this down into LIS + Disp.
  15760. Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
  15761. Base =
  15762. DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
  15763. uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
  15764. Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
  15765. break;
  15766. }
  15767. }
  15768. // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
  15769. Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
  15770. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
  15771. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  15772. fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
  15773. } else
  15774. Base = N;
  15775. break;
  15776. }
  15777. case PPC::AM_PrefixDForm: {
  15778. int64_t Imm34 = 0;
  15779. unsigned Opcode = N.getOpcode();
  15780. if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
  15781. (isIntS34Immediate(N.getOperand(1), Imm34))) {
  15782. // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
  15783. Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
  15784. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
  15785. Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
  15786. else
  15787. Base = N.getOperand(0);
  15788. } else if (isIntS34Immediate(N, Imm34)) {
  15789. // The address is a 34-bit signed immediate.
  15790. Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
  15791. Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
  15792. }
  15793. break;
  15794. }
  15795. case PPC::AM_PCRel: {
  15796. // When selecting PC-Relative instructions, "Base" is not utilized as
  15797. // we select the address as [PC+imm].
  15798. Disp = N;
  15799. break;
  15800. }
  15801. case PPC::AM_None:
  15802. break;
  15803. default: { // By default, X-Form is always available to be selected.
  15804. // When a frame index is not aligned, we also match by XForm.
  15805. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
  15806. Base = FI ? N : N.getOperand(1);
  15807. Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
  15808. N.getValueType())
  15809. : N.getOperand(0);
  15810. break;
  15811. }
  15812. }
  15813. return Mode;
  15814. }
  15815. CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
  15816. bool Return,
  15817. bool IsVarArg) const {
  15818. switch (CC) {
  15819. case CallingConv::Cold:
  15820. return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
  15821. default:
  15822. return CC_PPC64_ELF_FIS;
  15823. }
  15824. }
  15825. TargetLowering::AtomicExpansionKind
  15826. PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
  15827. unsigned Size = AI->getType()->getPrimitiveSizeInBits();
  15828. if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
  15829. return AtomicExpansionKind::MaskedIntrinsic;
  15830. return TargetLowering::shouldExpandAtomicRMWInIR(AI);
  15831. }
  15832. TargetLowering::AtomicExpansionKind
  15833. PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
  15834. unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
  15835. if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
  15836. return AtomicExpansionKind::MaskedIntrinsic;
  15837. return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
  15838. }
  15839. static Intrinsic::ID
  15840. getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
  15841. switch (BinOp) {
  15842. default:
  15843. llvm_unreachable("Unexpected AtomicRMW BinOp");
  15844. case AtomicRMWInst::Xchg:
  15845. return Intrinsic::ppc_atomicrmw_xchg_i128;
  15846. case AtomicRMWInst::Add:
  15847. return Intrinsic::ppc_atomicrmw_add_i128;
  15848. case AtomicRMWInst::Sub:
  15849. return Intrinsic::ppc_atomicrmw_sub_i128;
  15850. case AtomicRMWInst::And:
  15851. return Intrinsic::ppc_atomicrmw_and_i128;
  15852. case AtomicRMWInst::Or:
  15853. return Intrinsic::ppc_atomicrmw_or_i128;
  15854. case AtomicRMWInst::Xor:
  15855. return Intrinsic::ppc_atomicrmw_xor_i128;
  15856. case AtomicRMWInst::Nand:
  15857. return Intrinsic::ppc_atomicrmw_nand_i128;
  15858. }
  15859. }
  15860. Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
  15861. IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
  15862. Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
  15863. assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
  15864. "Only support quadword now");
  15865. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  15866. Type *ValTy = AlignedAddr->getType()->getPointerElementType();
  15867. assert(ValTy->getPrimitiveSizeInBits() == 128);
  15868. Function *RMW = Intrinsic::getDeclaration(
  15869. M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
  15870. Type *Int64Ty = Type::getInt64Ty(M->getContext());
  15871. Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
  15872. Value *IncrHi =
  15873. Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
  15874. Value *Addr =
  15875. Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
  15876. Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
  15877. Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
  15878. Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
  15879. Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
  15880. Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
  15881. return Builder.CreateOr(
  15882. Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
  15883. }
  15884. Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
  15885. IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
  15886. Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
  15887. assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
  15888. "Only support quadword now");
  15889. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  15890. Type *ValTy = AlignedAddr->getType()->getPointerElementType();
  15891. assert(ValTy->getPrimitiveSizeInBits() == 128);
  15892. Function *IntCmpXchg =
  15893. Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
  15894. Type *Int64Ty = Type::getInt64Ty(M->getContext());
  15895. Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
  15896. Value *CmpHi =
  15897. Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
  15898. Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
  15899. Value *NewHi =
  15900. Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
  15901. Value *Addr =
  15902. Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
  15903. emitLeadingFence(Builder, CI, Ord);
  15904. Value *LoHi =
  15905. Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
  15906. emitTrailingFence(Builder, CI, Ord);
  15907. Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
  15908. Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
  15909. Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
  15910. Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
  15911. return Builder.CreateOr(
  15912. Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
  15913. }