SelectionDAGBuilder.cpp 291 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452
  1. //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #define DEBUG_TYPE "isel"
  14. #include "SelectionDAGBuilder.h"
  15. #include "SDNodeDbgValue.h"
  16. #include "llvm/ADT/BitVector.h"
  17. #include "llvm/ADT/Optional.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/BranchProbabilityInfo.h"
  21. #include "llvm/Analysis/ConstantFolding.h"
  22. #include "llvm/Analysis/ValueTracking.h"
  23. #include "llvm/CodeGen/Analysis.h"
  24. #include "llvm/CodeGen/FastISel.h"
  25. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  26. #include "llvm/CodeGen/GCMetadata.h"
  27. #include "llvm/CodeGen/GCStrategy.h"
  28. #include "llvm/CodeGen/MachineFrameInfo.h"
  29. #include "llvm/CodeGen/MachineFunction.h"
  30. #include "llvm/CodeGen/MachineInstrBuilder.h"
  31. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  32. #include "llvm/CodeGen/MachineModuleInfo.h"
  33. #include "llvm/CodeGen/MachineRegisterInfo.h"
  34. #include "llvm/CodeGen/SelectionDAG.h"
  35. #include "llvm/CodeGen/StackMaps.h"
  36. #include "llvm/DebugInfo.h"
  37. #include "llvm/IR/CallingConv.h"
  38. #include "llvm/IR/Constants.h"
  39. #include "llvm/IR/DataLayout.h"
  40. #include "llvm/IR/DerivedTypes.h"
  41. #include "llvm/IR/Function.h"
  42. #include "llvm/IR/GlobalVariable.h"
  43. #include "llvm/IR/InlineAsm.h"
  44. #include "llvm/IR/Instructions.h"
  45. #include "llvm/IR/IntrinsicInst.h"
  46. #include "llvm/IR/Intrinsics.h"
  47. #include "llvm/IR/LLVMContext.h"
  48. #include "llvm/IR/Module.h"
  49. #include "llvm/Support/CommandLine.h"
  50. #include "llvm/Support/Debug.h"
  51. #include "llvm/Support/ErrorHandling.h"
  52. #include "llvm/Support/MathExtras.h"
  53. #include "llvm/Support/raw_ostream.h"
  54. #include "llvm/Target/TargetFrameLowering.h"
  55. #include "llvm/Target/TargetInstrInfo.h"
  56. #include "llvm/Target/TargetIntrinsicInfo.h"
  57. #include "llvm/Target/TargetLibraryInfo.h"
  58. #include "llvm/Target/TargetLowering.h"
  59. #include "llvm/Target/TargetOptions.h"
  60. #include "llvm/Target/TargetSelectionDAGInfo.h"
  61. #include <algorithm>
  62. using namespace llvm;
  63. /// LimitFloatPrecision - Generate low-precision inline sequences for
  64. /// some float libcalls (6, 8 or 12 bits).
  65. static unsigned LimitFloatPrecision;
  66. static cl::opt<unsigned, true>
  67. LimitFPPrecision("limit-float-precision",
  68. cl::desc("Generate low-precision inline sequences "
  69. "for some float libcalls"),
  70. cl::location(LimitFloatPrecision),
  71. cl::init(0));
  72. // Limit the width of DAG chains. This is important in general to prevent
  73. // prevent DAG-based analysis from blowing up. For example, alias analysis and
  74. // load clustering may not complete in reasonable time. It is difficult to
  75. // recognize and avoid this situation within each individual analysis, and
  76. // future analyses are likely to have the same behavior. Limiting DAG width is
  77. // the safe approach, and will be especially important with global DAGs.
  78. //
  79. // MaxParallelChains default is arbitrarily high to avoid affecting
  80. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  81. // sequence over this should have been converted to llvm.memcpy by the
  82. // frontend. It easy to induce this behavior with .ll code such as:
  83. // %buffer = alloca [4096 x i8]
  84. // %data = load [4096 x i8]* %argPtr
  85. // store [4096 x i8] %data, [4096 x i8]* %buffer
  86. static const unsigned MaxParallelChains = 64;
  87. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
  88. const SDValue *Parts, unsigned NumParts,
  89. MVT PartVT, EVT ValueVT, const Value *V);
  90. /// getCopyFromParts - Create a value that contains the specified legal parts
  91. /// combined into the value they represent. If the parts combine to a type
  92. /// larger then ValueVT then AssertOp can be used to specify whether the extra
  93. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  94. /// (ISD::AssertSext).
  95. static SDValue getCopyFromParts(SelectionDAG &DAG, SDLoc DL,
  96. const SDValue *Parts,
  97. unsigned NumParts, MVT PartVT, EVT ValueVT,
  98. const Value *V,
  99. ISD::NodeType AssertOp = ISD::DELETED_NODE) {
  100. if (ValueVT.isVector())
  101. return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
  102. PartVT, ValueVT, V);
  103. assert(NumParts > 0 && "No parts to assemble!");
  104. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  105. SDValue Val = Parts[0];
  106. if (NumParts > 1) {
  107. // Assemble the value from multiple parts.
  108. if (ValueVT.isInteger()) {
  109. unsigned PartBits = PartVT.getSizeInBits();
  110. unsigned ValueBits = ValueVT.getSizeInBits();
  111. // Assemble the power of 2 part.
  112. unsigned RoundParts = NumParts & (NumParts - 1) ?
  113. 1 << Log2_32(NumParts) : NumParts;
  114. unsigned RoundBits = PartBits * RoundParts;
  115. EVT RoundVT = RoundBits == ValueBits ?
  116. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  117. SDValue Lo, Hi;
  118. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  119. if (RoundParts > 2) {
  120. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  121. PartVT, HalfVT, V);
  122. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  123. RoundParts / 2, PartVT, HalfVT, V);
  124. } else {
  125. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  126. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  127. }
  128. if (TLI.isBigEndian())
  129. std::swap(Lo, Hi);
  130. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  131. if (RoundParts < NumParts) {
  132. // Assemble the trailing non-power-of-2 part.
  133. unsigned OddParts = NumParts - RoundParts;
  134. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  135. Hi = getCopyFromParts(DAG, DL,
  136. Parts + RoundParts, OddParts, PartVT, OddVT, V);
  137. // Combine the round and odd parts.
  138. Lo = Val;
  139. if (TLI.isBigEndian())
  140. std::swap(Lo, Hi);
  141. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  142. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  143. Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  144. DAG.getConstant(Lo.getValueType().getSizeInBits(),
  145. TLI.getPointerTy()));
  146. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  147. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  148. }
  149. } else if (PartVT.isFloatingPoint()) {
  150. // FP split into multiple FP parts (for ppcf128)
  151. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  152. "Unexpected split");
  153. SDValue Lo, Hi;
  154. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  155. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  156. if (TLI.isBigEndian())
  157. std::swap(Lo, Hi);
  158. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  159. } else {
  160. // FP split into integer parts (soft fp)
  161. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  162. !PartVT.isVector() && "Unexpected split");
  163. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  164. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
  165. }
  166. }
  167. // There is now one part, held in Val. Correct it to match ValueVT.
  168. EVT PartEVT = Val.getValueType();
  169. if (PartEVT == ValueVT)
  170. return Val;
  171. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  172. if (ValueVT.bitsLT(PartEVT)) {
  173. // For a truncate, see if we have any information to
  174. // indicate whether the truncated bits will always be
  175. // zero or sign-extension.
  176. if (AssertOp != ISD::DELETED_NODE)
  177. Val = DAG.getNode(AssertOp, DL, PartEVT, Val,
  178. DAG.getValueType(ValueVT));
  179. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  180. }
  181. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  182. }
  183. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  184. // FP_ROUND's are always exact here.
  185. if (ValueVT.bitsLT(Val.getValueType()))
  186. return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
  187. DAG.getTargetConstant(1, TLI.getPointerTy()));
  188. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  189. }
  190. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  191. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  192. llvm_unreachable("Unknown mismatch!");
  193. }
  194. /// getCopyFromPartsVector - Create a value that contains the specified legal
  195. /// parts combined into the value they represent. If the parts combine to a
  196. /// type larger then ValueVT then AssertOp can be used to specify whether the
  197. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  198. /// ValueVT (ISD::AssertSext).
  199. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, SDLoc DL,
  200. const SDValue *Parts, unsigned NumParts,
  201. MVT PartVT, EVT ValueVT, const Value *V) {
  202. assert(ValueVT.isVector() && "Not a vector value");
  203. assert(NumParts > 0 && "No parts to assemble!");
  204. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  205. SDValue Val = Parts[0];
  206. // Handle a multi-element vector.
  207. if (NumParts > 1) {
  208. EVT IntermediateVT;
  209. MVT RegisterVT;
  210. unsigned NumIntermediates;
  211. unsigned NumRegs =
  212. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  213. NumIntermediates, RegisterVT);
  214. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  215. NumParts = NumRegs; // Silence a compiler warning.
  216. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  217. assert(RegisterVT == Parts[0].getSimpleValueType() &&
  218. "Part type doesn't match part!");
  219. // Assemble the parts into intermediate operands.
  220. SmallVector<SDValue, 8> Ops(NumIntermediates);
  221. if (NumIntermediates == NumParts) {
  222. // If the register was not expanded, truncate or copy the value,
  223. // as appropriate.
  224. for (unsigned i = 0; i != NumParts; ++i)
  225. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  226. PartVT, IntermediateVT, V);
  227. } else if (NumParts > 0) {
  228. // If the intermediate type was expanded, build the intermediate
  229. // operands from the parts.
  230. assert(NumParts % NumIntermediates == 0 &&
  231. "Must expand into a divisible number of parts!");
  232. unsigned Factor = NumParts / NumIntermediates;
  233. for (unsigned i = 0; i != NumIntermediates; ++i)
  234. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  235. PartVT, IntermediateVT, V);
  236. }
  237. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  238. // intermediate operands.
  239. Val = DAG.getNode(IntermediateVT.isVector() ?
  240. ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
  241. ValueVT, &Ops[0], NumIntermediates);
  242. }
  243. // There is now one part, held in Val. Correct it to match ValueVT.
  244. EVT PartEVT = Val.getValueType();
  245. if (PartEVT == ValueVT)
  246. return Val;
  247. if (PartEVT.isVector()) {
  248. // If the element type of the source/dest vectors are the same, but the
  249. // parts vector has more elements than the value vector, then we have a
  250. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  251. // elements we want.
  252. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  253. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  254. "Cannot narrow, it would be a lossy transformation");
  255. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  256. DAG.getConstant(0, TLI.getVectorIdxTy()));
  257. }
  258. // Vector/Vector bitcast.
  259. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  260. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  261. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  262. "Cannot handle this kind of promotion");
  263. // Promoted vector extract
  264. bool Smaller = ValueVT.bitsLE(PartEVT);
  265. return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  266. DL, ValueVT, Val);
  267. }
  268. // Trivial bitcast if the types are the same size and the destination
  269. // vector type is legal.
  270. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  271. TLI.isTypeLegal(ValueVT))
  272. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  273. // Handle cases such as i8 -> <1 x i1>
  274. if (ValueVT.getVectorNumElements() != 1) {
  275. LLVMContext &Ctx = *DAG.getContext();
  276. Twine ErrMsg("non-trivial scalar-to-vector conversion");
  277. if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
  278. if (const CallInst *CI = dyn_cast<CallInst>(I))
  279. if (isa<InlineAsm>(CI->getCalledValue()))
  280. ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
  281. Ctx.emitError(I, ErrMsg);
  282. } else {
  283. Ctx.emitError(ErrMsg);
  284. }
  285. return DAG.getUNDEF(ValueVT);
  286. }
  287. if (ValueVT.getVectorNumElements() == 1 &&
  288. ValueVT.getVectorElementType() != PartEVT) {
  289. bool Smaller = ValueVT.bitsLE(PartEVT);
  290. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  291. DL, ValueVT.getScalarType(), Val);
  292. }
  293. return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
  294. }
  295. static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc dl,
  296. SDValue Val, SDValue *Parts, unsigned NumParts,
  297. MVT PartVT, const Value *V);
  298. /// getCopyToParts - Create a series of nodes that contain the specified value
  299. /// split into legal parts. If the parts contain more bits than Val, then, for
  300. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  301. static void getCopyToParts(SelectionDAG &DAG, SDLoc DL,
  302. SDValue Val, SDValue *Parts, unsigned NumParts,
  303. MVT PartVT, const Value *V,
  304. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  305. EVT ValueVT = Val.getValueType();
  306. // Handle the vector case separately.
  307. if (ValueVT.isVector())
  308. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
  309. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  310. unsigned PartBits = PartVT.getSizeInBits();
  311. unsigned OrigNumParts = NumParts;
  312. assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
  313. if (NumParts == 0)
  314. return;
  315. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  316. EVT PartEVT = PartVT;
  317. if (PartEVT == ValueVT) {
  318. assert(NumParts == 1 && "No-op copy with multiple parts!");
  319. Parts[0] = Val;
  320. return;
  321. }
  322. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  323. // If the parts cover more bits than the value has, promote the value.
  324. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  325. assert(NumParts == 1 && "Do not know what to promote to!");
  326. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  327. } else {
  328. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  329. ValueVT.isInteger() &&
  330. "Unknown mismatch!");
  331. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  332. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  333. if (PartVT == MVT::x86mmx)
  334. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  335. }
  336. } else if (PartBits == ValueVT.getSizeInBits()) {
  337. // Different types of the same size.
  338. assert(NumParts == 1 && PartEVT != ValueVT);
  339. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  340. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  341. // If the parts cover less bits than value has, truncate the value.
  342. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  343. ValueVT.isInteger() &&
  344. "Unknown mismatch!");
  345. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  346. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  347. if (PartVT == MVT::x86mmx)
  348. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  349. }
  350. // The value may have changed - recompute ValueVT.
  351. ValueVT = Val.getValueType();
  352. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  353. "Failed to tile the value with PartVT!");
  354. if (NumParts == 1) {
  355. if (PartEVT != ValueVT) {
  356. LLVMContext &Ctx = *DAG.getContext();
  357. Twine ErrMsg("scalar-to-vector conversion failed");
  358. if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
  359. if (const CallInst *CI = dyn_cast<CallInst>(I))
  360. if (isa<InlineAsm>(CI->getCalledValue()))
  361. ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
  362. Ctx.emitError(I, ErrMsg);
  363. } else {
  364. Ctx.emitError(ErrMsg);
  365. }
  366. }
  367. Parts[0] = Val;
  368. return;
  369. }
  370. // Expand the value into multiple parts.
  371. if (NumParts & (NumParts - 1)) {
  372. // The number of parts is not a power of 2. Split off and copy the tail.
  373. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  374. "Do not know what to expand to!");
  375. unsigned RoundParts = 1 << Log2_32(NumParts);
  376. unsigned RoundBits = RoundParts * PartBits;
  377. unsigned OddParts = NumParts - RoundParts;
  378. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  379. DAG.getIntPtrConstant(RoundBits));
  380. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
  381. if (TLI.isBigEndian())
  382. // The odd parts were reversed by getCopyToParts - unreverse them.
  383. std::reverse(Parts + RoundParts, Parts + NumParts);
  384. NumParts = RoundParts;
  385. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  386. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  387. }
  388. // The number of parts is a power of 2. Repeatedly bisect the value using
  389. // EXTRACT_ELEMENT.
  390. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  391. EVT::getIntegerVT(*DAG.getContext(),
  392. ValueVT.getSizeInBits()),
  393. Val);
  394. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  395. for (unsigned i = 0; i < NumParts; i += StepSize) {
  396. unsigned ThisBits = StepSize * PartBits / 2;
  397. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  398. SDValue &Part0 = Parts[i];
  399. SDValue &Part1 = Parts[i+StepSize/2];
  400. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  401. ThisVT, Part0, DAG.getIntPtrConstant(1));
  402. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  403. ThisVT, Part0, DAG.getIntPtrConstant(0));
  404. if (ThisBits == PartBits && ThisVT != PartVT) {
  405. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  406. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  407. }
  408. }
  409. }
  410. if (TLI.isBigEndian())
  411. std::reverse(Parts, Parts + OrigNumParts);
  412. }
  413. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  414. /// value split into legal parts.
  415. static void getCopyToPartsVector(SelectionDAG &DAG, SDLoc DL,
  416. SDValue Val, SDValue *Parts, unsigned NumParts,
  417. MVT PartVT, const Value *V) {
  418. EVT ValueVT = Val.getValueType();
  419. assert(ValueVT.isVector() && "Not a vector");
  420. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  421. if (NumParts == 1) {
  422. EVT PartEVT = PartVT;
  423. if (PartEVT == ValueVT) {
  424. // Nothing to do.
  425. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  426. // Bitconvert vector->vector case.
  427. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  428. } else if (PartVT.isVector() &&
  429. PartEVT.getVectorElementType() == ValueVT.getVectorElementType() &&
  430. PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  431. EVT ElementVT = PartVT.getVectorElementType();
  432. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  433. // undef elements.
  434. SmallVector<SDValue, 16> Ops;
  435. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  436. Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  437. ElementVT, Val, DAG.getConstant(i,
  438. TLI.getVectorIdxTy())));
  439. for (unsigned i = ValueVT.getVectorNumElements(),
  440. e = PartVT.getVectorNumElements(); i != e; ++i)
  441. Ops.push_back(DAG.getUNDEF(ElementVT));
  442. Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
  443. // FIXME: Use CONCAT for 2x -> 4x.
  444. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  445. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  446. } else if (PartVT.isVector() &&
  447. PartEVT.getVectorElementType().bitsGE(
  448. ValueVT.getVectorElementType()) &&
  449. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  450. // Promoted vector extract
  451. bool Smaller = PartEVT.bitsLE(ValueVT);
  452. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  453. DL, PartVT, Val);
  454. } else{
  455. // Vector -> scalar conversion.
  456. assert(ValueVT.getVectorNumElements() == 1 &&
  457. "Only trivial vector-to-scalar conversions should get here!");
  458. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  459. PartVT, Val, DAG.getConstant(0, TLI.getVectorIdxTy()));
  460. bool Smaller = ValueVT.bitsLE(PartVT);
  461. Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
  462. DL, PartVT, Val);
  463. }
  464. Parts[0] = Val;
  465. return;
  466. }
  467. // Handle a multi-element vector.
  468. EVT IntermediateVT;
  469. MVT RegisterVT;
  470. unsigned NumIntermediates;
  471. unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
  472. IntermediateVT,
  473. NumIntermediates, RegisterVT);
  474. unsigned NumElements = ValueVT.getVectorNumElements();
  475. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  476. NumParts = NumRegs; // Silence a compiler warning.
  477. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  478. // Split the vector into intermediate operands.
  479. SmallVector<SDValue, 8> Ops(NumIntermediates);
  480. for (unsigned i = 0; i != NumIntermediates; ++i) {
  481. if (IntermediateVT.isVector())
  482. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
  483. IntermediateVT, Val,
  484. DAG.getConstant(i * (NumElements / NumIntermediates),
  485. TLI.getVectorIdxTy()));
  486. else
  487. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  488. IntermediateVT, Val,
  489. DAG.getConstant(i, TLI.getVectorIdxTy()));
  490. }
  491. // Split the intermediate operands into legal parts.
  492. if (NumParts == NumIntermediates) {
  493. // If the register was not expanded, promote or copy the value,
  494. // as appropriate.
  495. for (unsigned i = 0; i != NumParts; ++i)
  496. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
  497. } else if (NumParts > 0) {
  498. // If the intermediate type was expanded, split each the value into
  499. // legal parts.
  500. assert(NumParts % NumIntermediates == 0 &&
  501. "Must expand into a divisible number of parts!");
  502. unsigned Factor = NumParts / NumIntermediates;
  503. for (unsigned i = 0; i != NumIntermediates; ++i)
  504. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
  505. }
  506. }
  507. namespace {
  508. /// RegsForValue - This struct represents the registers (physical or virtual)
  509. /// that a particular set of values is assigned, and the type information
  510. /// about the value. The most common situation is to represent one value at a
  511. /// time, but struct or array values are handled element-wise as multiple
  512. /// values. The splitting of aggregates is performed recursively, so that we
  513. /// never have aggregate-typed registers. The values at this point do not
  514. /// necessarily have legal types, so each value may require one or more
  515. /// registers of some legal type.
  516. ///
  517. struct RegsForValue {
  518. /// ValueVTs - The value types of the values, which may not be legal, and
  519. /// may need be promoted or synthesized from one or more registers.
  520. ///
  521. SmallVector<EVT, 4> ValueVTs;
  522. /// RegVTs - The value types of the registers. This is the same size as
  523. /// ValueVTs and it records, for each value, what the type of the assigned
  524. /// register or registers are. (Individual values are never synthesized
  525. /// from more than one type of register.)
  526. ///
  527. /// With virtual registers, the contents of RegVTs is redundant with TLI's
  528. /// getRegisterType member function, however when with physical registers
  529. /// it is necessary to have a separate record of the types.
  530. ///
  531. SmallVector<MVT, 4> RegVTs;
  532. /// Regs - This list holds the registers assigned to the values.
  533. /// Each legal or promoted value requires one register, and each
  534. /// expanded value requires multiple registers.
  535. ///
  536. SmallVector<unsigned, 4> Regs;
  537. RegsForValue() {}
  538. RegsForValue(const SmallVector<unsigned, 4> &regs,
  539. MVT regvt, EVT valuevt)
  540. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
  541. RegsForValue(LLVMContext &Context, const TargetLowering &tli,
  542. unsigned Reg, Type *Ty) {
  543. ComputeValueVTs(tli, Ty, ValueVTs);
  544. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  545. EVT ValueVT = ValueVTs[Value];
  546. unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
  547. MVT RegisterVT = tli.getRegisterType(Context, ValueVT);
  548. for (unsigned i = 0; i != NumRegs; ++i)
  549. Regs.push_back(Reg + i);
  550. RegVTs.push_back(RegisterVT);
  551. Reg += NumRegs;
  552. }
  553. }
  554. /// areValueTypesLegal - Return true if types of all the values are legal.
  555. bool areValueTypesLegal(const TargetLowering &TLI) {
  556. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  557. MVT RegisterVT = RegVTs[Value];
  558. if (!TLI.isTypeLegal(RegisterVT))
  559. return false;
  560. }
  561. return true;
  562. }
  563. /// append - Add the specified values to this one.
  564. void append(const RegsForValue &RHS) {
  565. ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
  566. RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
  567. Regs.append(RHS.Regs.begin(), RHS.Regs.end());
  568. }
  569. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  570. /// this value and returns the result as a ValueVTs value. This uses
  571. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  572. /// If the Flag pointer is NULL, no flag is used.
  573. SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
  574. SDLoc dl,
  575. SDValue &Chain, SDValue *Flag,
  576. const Value *V = 0) const;
  577. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  578. /// specified value into the registers specified by this object. This uses
  579. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  580. /// If the Flag pointer is NULL, no flag is used.
  581. void getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
  582. SDValue &Chain, SDValue *Flag, const Value *V) const;
  583. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  584. /// operand list. This adds the code marker, matching input operand index
  585. /// (if applicable), and includes the number of values added into it.
  586. void AddInlineAsmOperands(unsigned Kind,
  587. bool HasMatching, unsigned MatchingIdx,
  588. SelectionDAG &DAG,
  589. std::vector<SDValue> &Ops) const;
  590. };
  591. }
  592. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  593. /// this value and returns the result as a ValueVT value. This uses
  594. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  595. /// If the Flag pointer is NULL, no flag is used.
  596. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  597. FunctionLoweringInfo &FuncInfo,
  598. SDLoc dl,
  599. SDValue &Chain, SDValue *Flag,
  600. const Value *V) const {
  601. // A Value with type {} or [0 x %t] needs no registers.
  602. if (ValueVTs.empty())
  603. return SDValue();
  604. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  605. // Assemble the legal parts into the final values.
  606. SmallVector<SDValue, 4> Values(ValueVTs.size());
  607. SmallVector<SDValue, 8> Parts;
  608. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  609. // Copy the legal parts from the registers.
  610. EVT ValueVT = ValueVTs[Value];
  611. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  612. MVT RegisterVT = RegVTs[Value];
  613. Parts.resize(NumRegs);
  614. for (unsigned i = 0; i != NumRegs; ++i) {
  615. SDValue P;
  616. if (Flag == 0) {
  617. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  618. } else {
  619. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  620. *Flag = P.getValue(2);
  621. }
  622. Chain = P.getValue(1);
  623. Parts[i] = P;
  624. // If the source register was virtual and if we know something about it,
  625. // add an assert node.
  626. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  627. !RegisterVT.isInteger() || RegisterVT.isVector())
  628. continue;
  629. const FunctionLoweringInfo::LiveOutInfo *LOI =
  630. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  631. if (!LOI)
  632. continue;
  633. unsigned RegSize = RegisterVT.getSizeInBits();
  634. unsigned NumSignBits = LOI->NumSignBits;
  635. unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
  636. if (NumZeroBits == RegSize) {
  637. // The current value is a zero.
  638. // Explicitly express that as it would be easier for
  639. // optimizations to kick in.
  640. Parts[i] = DAG.getConstant(0, RegisterVT);
  641. continue;
  642. }
  643. // FIXME: We capture more information than the dag can represent. For
  644. // now, just use the tightest assertzext/assertsext possible.
  645. bool isSExt = true;
  646. EVT FromVT(MVT::Other);
  647. if (NumSignBits == RegSize)
  648. isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
  649. else if (NumZeroBits >= RegSize-1)
  650. isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
  651. else if (NumSignBits > RegSize-8)
  652. isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
  653. else if (NumZeroBits >= RegSize-8)
  654. isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
  655. else if (NumSignBits > RegSize-16)
  656. isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
  657. else if (NumZeroBits >= RegSize-16)
  658. isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
  659. else if (NumSignBits > RegSize-32)
  660. isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
  661. else if (NumZeroBits >= RegSize-32)
  662. isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
  663. else
  664. continue;
  665. // Add an assertion node.
  666. assert(FromVT != MVT::Other);
  667. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  668. RegisterVT, P, DAG.getValueType(FromVT));
  669. }
  670. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  671. NumRegs, RegisterVT, ValueVT, V);
  672. Part += NumRegs;
  673. Parts.clear();
  674. }
  675. return DAG.getNode(ISD::MERGE_VALUES, dl,
  676. DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
  677. &Values[0], ValueVTs.size());
  678. }
  679. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  680. /// specified value into the registers specified by this object. This uses
  681. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  682. /// If the Flag pointer is NULL, no flag is used.
  683. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, SDLoc dl,
  684. SDValue &Chain, SDValue *Flag,
  685. const Value *V) const {
  686. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  687. // Get the list of the values's legal parts.
  688. unsigned NumRegs = Regs.size();
  689. SmallVector<SDValue, 8> Parts(NumRegs);
  690. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  691. EVT ValueVT = ValueVTs[Value];
  692. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  693. MVT RegisterVT = RegVTs[Value];
  694. ISD::NodeType ExtendKind =
  695. TLI.isZExtFree(Val, RegisterVT)? ISD::ZERO_EXTEND: ISD::ANY_EXTEND;
  696. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  697. &Parts[Part], NumParts, RegisterVT, V, ExtendKind);
  698. Part += NumParts;
  699. }
  700. // Copy the parts into the registers.
  701. SmallVector<SDValue, 8> Chains(NumRegs);
  702. for (unsigned i = 0; i != NumRegs; ++i) {
  703. SDValue Part;
  704. if (Flag == 0) {
  705. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  706. } else {
  707. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  708. *Flag = Part.getValue(1);
  709. }
  710. Chains[i] = Part.getValue(0);
  711. }
  712. if (NumRegs == 1 || Flag)
  713. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  714. // flagged to it. That is the CopyToReg nodes and the user are considered
  715. // a single scheduling unit. If we create a TokenFactor and return it as
  716. // chain, then the TokenFactor is both a predecessor (operand) of the
  717. // user as well as a successor (the TF operands are flagged to the user).
  718. // c1, f1 = CopyToReg
  719. // c2, f2 = CopyToReg
  720. // c3 = TokenFactor c1, c2
  721. // ...
  722. // = op c3, ..., f2
  723. Chain = Chains[NumRegs-1];
  724. else
  725. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
  726. }
  727. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  728. /// operand list. This adds the code marker and includes the number of
  729. /// values added into it.
  730. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  731. unsigned MatchingIdx,
  732. SelectionDAG &DAG,
  733. std::vector<SDValue> &Ops) const {
  734. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  735. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  736. if (HasMatching)
  737. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  738. else if (!Regs.empty() &&
  739. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  740. // Put the register class of the virtual registers in the flag word. That
  741. // way, later passes can recompute register class constraints for inline
  742. // assembly as well as normal instructions.
  743. // Don't do this for tied operands that can use the regclass information
  744. // from the def.
  745. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  746. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  747. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  748. }
  749. SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
  750. Ops.push_back(Res);
  751. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  752. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  753. MVT RegisterVT = RegVTs[Value];
  754. for (unsigned i = 0; i != NumRegs; ++i) {
  755. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  756. Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
  757. }
  758. }
  759. }
  760. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
  761. const TargetLibraryInfo *li) {
  762. AA = &aa;
  763. GFI = gfi;
  764. LibInfo = li;
  765. TD = DAG.getTarget().getDataLayout();
  766. Context = DAG.getContext();
  767. LPadToCallSiteMap.clear();
  768. }
  769. /// clear - Clear out the current SelectionDAG and the associated
  770. /// state and prepare this SelectionDAGBuilder object to be used
  771. /// for a new block. This doesn't clear out information about
  772. /// additional blocks that are needed to complete switch lowering
  773. /// or PHI node updating; that information is cleared out as it is
  774. /// consumed.
  775. void SelectionDAGBuilder::clear() {
  776. NodeMap.clear();
  777. UnusedArgNodeMap.clear();
  778. PendingLoads.clear();
  779. PendingExports.clear();
  780. CurInst = NULL;
  781. HasTailCall = false;
  782. }
  783. /// clearDanglingDebugInfo - Clear the dangling debug information
  784. /// map. This function is separated from the clear so that debug
  785. /// information that is dangling in a basic block can be properly
  786. /// resolved in a different basic block. This allows the
  787. /// SelectionDAG to resolve dangling debug information attached
  788. /// to PHI nodes.
  789. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  790. DanglingDebugInfoMap.clear();
  791. }
  792. /// getRoot - Return the current virtual root of the Selection DAG,
  793. /// flushing any PendingLoad items. This must be done before emitting
  794. /// a store or any other node that may need to be ordered after any
  795. /// prior load instructions.
  796. ///
  797. SDValue SelectionDAGBuilder::getRoot() {
  798. if (PendingLoads.empty())
  799. return DAG.getRoot();
  800. if (PendingLoads.size() == 1) {
  801. SDValue Root = PendingLoads[0];
  802. DAG.setRoot(Root);
  803. PendingLoads.clear();
  804. return Root;
  805. }
  806. // Otherwise, we have to make a token factor node.
  807. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  808. &PendingLoads[0], PendingLoads.size());
  809. PendingLoads.clear();
  810. DAG.setRoot(Root);
  811. return Root;
  812. }
  813. /// getControlRoot - Similar to getRoot, but instead of flushing all the
  814. /// PendingLoad items, flush all the PendingExports items. It is necessary
  815. /// to do this before emitting a terminator instruction.
  816. ///
  817. SDValue SelectionDAGBuilder::getControlRoot() {
  818. SDValue Root = DAG.getRoot();
  819. if (PendingExports.empty())
  820. return Root;
  821. // Turn all of the CopyToReg chains into one factored node.
  822. if (Root.getOpcode() != ISD::EntryToken) {
  823. unsigned i = 0, e = PendingExports.size();
  824. for (; i != e; ++i) {
  825. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  826. if (PendingExports[i].getNode()->getOperand(0) == Root)
  827. break; // Don't add the root if we already indirectly depend on it.
  828. }
  829. if (i == e)
  830. PendingExports.push_back(Root);
  831. }
  832. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  833. &PendingExports[0],
  834. PendingExports.size());
  835. PendingExports.clear();
  836. DAG.setRoot(Root);
  837. return Root;
  838. }
  839. void SelectionDAGBuilder::visit(const Instruction &I) {
  840. // Set up outgoing PHI node register values before emitting the terminator.
  841. if (isa<TerminatorInst>(&I))
  842. HandlePHINodesInSuccessorBlocks(I.getParent());
  843. ++SDNodeOrder;
  844. CurInst = &I;
  845. visit(I.getOpcode(), I);
  846. if (!isa<TerminatorInst>(&I) && !HasTailCall)
  847. CopyToExportRegsIfNeeded(&I);
  848. CurInst = NULL;
  849. }
  850. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  851. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  852. }
  853. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  854. // Note: this doesn't use InstVisitor, because it has to work with
  855. // ConstantExpr's in addition to instructions.
  856. switch (Opcode) {
  857. default: llvm_unreachable("Unknown instruction type encountered!");
  858. // Build the switch statement using the Instruction.def file.
  859. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  860. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  861. #include "llvm/IR/Instruction.def"
  862. }
  863. }
  864. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  865. // generate the debug data structures now that we've seen its definition.
  866. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  867. SDValue Val) {
  868. DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
  869. if (DDI.getDI()) {
  870. const DbgValueInst *DI = DDI.getDI();
  871. DebugLoc dl = DDI.getdl();
  872. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  873. MDNode *Variable = DI->getVariable();
  874. uint64_t Offset = DI->getOffset();
  875. SDDbgValue *SDV;
  876. if (Val.getNode()) {
  877. if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
  878. SDV = DAG.getDbgValue(Variable, Val.getNode(),
  879. Val.getResNo(), Offset, dl, DbgSDNodeOrder);
  880. DAG.AddDbgValue(SDV, Val.getNode(), false);
  881. }
  882. } else
  883. DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  884. DanglingDebugInfoMap[V] = DanglingDebugInfo();
  885. }
  886. }
  887. /// getValue - Return an SDValue for the given Value.
  888. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  889. // If we already have an SDValue for this value, use it. It's important
  890. // to do this first, so that we don't create a CopyFromReg if we already
  891. // have a regular SDValue.
  892. SDValue &N = NodeMap[V];
  893. if (N.getNode()) return N;
  894. // If there's a virtual register allocated and initialized for this
  895. // value, use it.
  896. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  897. if (It != FuncInfo.ValueMap.end()) {
  898. unsigned InReg = It->second;
  899. RegsForValue RFV(*DAG.getContext(), *TM.getTargetLowering(),
  900. InReg, V->getType());
  901. SDValue Chain = DAG.getEntryNode();
  902. N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
  903. resolveDanglingDebugInfo(V, N);
  904. return N;
  905. }
  906. // Otherwise create a new SDValue and remember it.
  907. SDValue Val = getValueImpl(V);
  908. NodeMap[V] = Val;
  909. resolveDanglingDebugInfo(V, Val);
  910. return Val;
  911. }
  912. /// getNonRegisterValue - Return an SDValue for the given Value, but
  913. /// don't look in FuncInfo.ValueMap for a virtual register.
  914. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  915. // If we already have an SDValue for this value, use it.
  916. SDValue &N = NodeMap[V];
  917. if (N.getNode()) return N;
  918. // Otherwise create a new SDValue and remember it.
  919. SDValue Val = getValueImpl(V);
  920. NodeMap[V] = Val;
  921. resolveDanglingDebugInfo(V, Val);
  922. return Val;
  923. }
  924. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  925. /// Create an SDValue for the given value.
  926. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  927. const TargetLowering *TLI = TM.getTargetLowering();
  928. if (const Constant *C = dyn_cast<Constant>(V)) {
  929. EVT VT = TLI->getValueType(V->getType(), true);
  930. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  931. return DAG.getConstant(*CI, VT);
  932. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  933. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  934. if (isa<ConstantPointerNull>(C))
  935. return DAG.getConstant(0, TLI->getPointerTy());
  936. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  937. return DAG.getConstantFP(*CFP, VT);
  938. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  939. return DAG.getUNDEF(VT);
  940. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  941. visit(CE->getOpcode(), *CE);
  942. SDValue N1 = NodeMap[V];
  943. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  944. return N1;
  945. }
  946. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  947. SmallVector<SDValue, 4> Constants;
  948. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  949. OI != OE; ++OI) {
  950. SDNode *Val = getValue(*OI).getNode();
  951. // If the operand is an empty aggregate, there are no values.
  952. if (!Val) continue;
  953. // Add each leaf value from the operand to the Constants list
  954. // to form a flattened list of all the values.
  955. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  956. Constants.push_back(SDValue(Val, i));
  957. }
  958. return DAG.getMergeValues(&Constants[0], Constants.size(),
  959. getCurSDLoc());
  960. }
  961. if (const ConstantDataSequential *CDS =
  962. dyn_cast<ConstantDataSequential>(C)) {
  963. SmallVector<SDValue, 4> Ops;
  964. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  965. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  966. // Add each leaf value from the operand to the Constants list
  967. // to form a flattened list of all the values.
  968. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  969. Ops.push_back(SDValue(Val, i));
  970. }
  971. if (isa<ArrayType>(CDS->getType()))
  972. return DAG.getMergeValues(&Ops[0], Ops.size(), getCurSDLoc());
  973. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
  974. VT, &Ops[0], Ops.size());
  975. }
  976. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  977. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  978. "Unknown struct or array constant!");
  979. SmallVector<EVT, 4> ValueVTs;
  980. ComputeValueVTs(*TLI, C->getType(), ValueVTs);
  981. unsigned NumElts = ValueVTs.size();
  982. if (NumElts == 0)
  983. return SDValue(); // empty struct
  984. SmallVector<SDValue, 4> Constants(NumElts);
  985. for (unsigned i = 0; i != NumElts; ++i) {
  986. EVT EltVT = ValueVTs[i];
  987. if (isa<UndefValue>(C))
  988. Constants[i] = DAG.getUNDEF(EltVT);
  989. else if (EltVT.isFloatingPoint())
  990. Constants[i] = DAG.getConstantFP(0, EltVT);
  991. else
  992. Constants[i] = DAG.getConstant(0, EltVT);
  993. }
  994. return DAG.getMergeValues(&Constants[0], NumElts,
  995. getCurSDLoc());
  996. }
  997. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  998. return DAG.getBlockAddress(BA, VT);
  999. VectorType *VecTy = cast<VectorType>(V->getType());
  1000. unsigned NumElements = VecTy->getNumElements();
  1001. // Now that we know the number and type of the elements, get that number of
  1002. // elements into the Ops array based on what kind of constant it is.
  1003. SmallVector<SDValue, 16> Ops;
  1004. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1005. for (unsigned i = 0; i != NumElements; ++i)
  1006. Ops.push_back(getValue(CV->getOperand(i)));
  1007. } else {
  1008. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1009. EVT EltVT = TLI->getValueType(VecTy->getElementType());
  1010. SDValue Op;
  1011. if (EltVT.isFloatingPoint())
  1012. Op = DAG.getConstantFP(0, EltVT);
  1013. else
  1014. Op = DAG.getConstant(0, EltVT);
  1015. Ops.assign(NumElements, Op);
  1016. }
  1017. // Create a BUILD_VECTOR node.
  1018. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
  1019. VT, &Ops[0], Ops.size());
  1020. }
  1021. // If this is a static alloca, generate it as the frameindex instead of
  1022. // computation.
  1023. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1024. DenseMap<const AllocaInst*, int>::iterator SI =
  1025. FuncInfo.StaticAllocaMap.find(AI);
  1026. if (SI != FuncInfo.StaticAllocaMap.end())
  1027. return DAG.getFrameIndex(SI->second, TLI->getPointerTy());
  1028. }
  1029. // If this is an instruction which fast-isel has deferred, select it now.
  1030. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1031. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1032. RegsForValue RFV(*DAG.getContext(), *TLI, InReg, Inst->getType());
  1033. SDValue Chain = DAG.getEntryNode();
  1034. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, NULL, V);
  1035. }
  1036. llvm_unreachable("Can't get register for value!");
  1037. }
  1038. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1039. const TargetLowering *TLI = TM.getTargetLowering();
  1040. SDValue Chain = getControlRoot();
  1041. SmallVector<ISD::OutputArg, 8> Outs;
  1042. SmallVector<SDValue, 8> OutVals;
  1043. if (!FuncInfo.CanLowerReturn) {
  1044. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1045. const Function *F = I.getParent()->getParent();
  1046. // Emit a store of the return value through the virtual register.
  1047. // Leave Outs empty so that LowerReturn won't try to load return
  1048. // registers the usual way.
  1049. SmallVector<EVT, 1> PtrValueVTs;
  1050. ComputeValueVTs(*TLI, PointerType::getUnqual(F->getReturnType()),
  1051. PtrValueVTs);
  1052. SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
  1053. SDValue RetOp = getValue(I.getOperand(0));
  1054. SmallVector<EVT, 4> ValueVTs;
  1055. SmallVector<uint64_t, 4> Offsets;
  1056. ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1057. unsigned NumValues = ValueVTs.size();
  1058. SmallVector<SDValue, 4> Chains(NumValues);
  1059. for (unsigned i = 0; i != NumValues; ++i) {
  1060. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(),
  1061. RetPtr.getValueType(), RetPtr,
  1062. DAG.getIntPtrConstant(Offsets[i]));
  1063. Chains[i] =
  1064. DAG.getStore(Chain, getCurSDLoc(),
  1065. SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1066. // FIXME: better loc info would be nice.
  1067. Add, MachinePointerInfo(), false, false, 0);
  1068. }
  1069. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1070. MVT::Other, &Chains[0], NumValues);
  1071. } else if (I.getNumOperands() != 0) {
  1072. SmallVector<EVT, 4> ValueVTs;
  1073. ComputeValueVTs(*TLI, I.getOperand(0)->getType(), ValueVTs);
  1074. unsigned NumValues = ValueVTs.size();
  1075. if (NumValues) {
  1076. SDValue RetOp = getValue(I.getOperand(0));
  1077. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  1078. EVT VT = ValueVTs[j];
  1079. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1080. const Function *F = I.getParent()->getParent();
  1081. if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1082. Attribute::SExt))
  1083. ExtendKind = ISD::SIGN_EXTEND;
  1084. else if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1085. Attribute::ZExt))
  1086. ExtendKind = ISD::ZERO_EXTEND;
  1087. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1088. VT = TLI->getTypeForExtArgOrReturn(VT.getSimpleVT(), ExtendKind);
  1089. unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), VT);
  1090. MVT PartVT = TLI->getRegisterType(*DAG.getContext(), VT);
  1091. SmallVector<SDValue, 4> Parts(NumParts);
  1092. getCopyToParts(DAG, getCurSDLoc(),
  1093. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1094. &Parts[0], NumParts, PartVT, &I, ExtendKind);
  1095. // 'inreg' on function refers to return value
  1096. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1097. if (F->getAttributes().hasAttribute(AttributeSet::ReturnIndex,
  1098. Attribute::InReg))
  1099. Flags.setInReg();
  1100. // Propagate extension type if any
  1101. if (ExtendKind == ISD::SIGN_EXTEND)
  1102. Flags.setSExt();
  1103. else if (ExtendKind == ISD::ZERO_EXTEND)
  1104. Flags.setZExt();
  1105. for (unsigned i = 0; i < NumParts; ++i) {
  1106. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1107. VT, /*isfixed=*/true, 0, 0));
  1108. OutVals.push_back(Parts[i]);
  1109. }
  1110. }
  1111. }
  1112. }
  1113. bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
  1114. CallingConv::ID CallConv =
  1115. DAG.getMachineFunction().getFunction()->getCallingConv();
  1116. Chain = TM.getTargetLowering()->LowerReturn(Chain, CallConv, isVarArg,
  1117. Outs, OutVals, getCurSDLoc(),
  1118. DAG);
  1119. // Verify that the target's LowerReturn behaved as expected.
  1120. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1121. "LowerReturn didn't return a valid chain!");
  1122. // Update the DAG with the new chain value resulting from return lowering.
  1123. DAG.setRoot(Chain);
  1124. }
  1125. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1126. /// created for it, emit nodes to copy the value into the virtual
  1127. /// registers.
  1128. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1129. // Skip empty types
  1130. if (V->getType()->isEmptyTy())
  1131. return;
  1132. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1133. if (VMI != FuncInfo.ValueMap.end()) {
  1134. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1135. CopyValueToVirtualRegister(V, VMI->second);
  1136. }
  1137. }
  1138. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1139. /// the current basic block, add it to ValueMap now so that we'll get a
  1140. /// CopyTo/FromReg.
  1141. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1142. // No need to export constants.
  1143. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1144. // Already exported?
  1145. if (FuncInfo.isExportedInst(V)) return;
  1146. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1147. CopyValueToVirtualRegister(V, Reg);
  1148. }
  1149. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1150. const BasicBlock *FromBB) {
  1151. // The operands of the setcc have to be in this block. We don't know
  1152. // how to export them from some other block.
  1153. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1154. // Can export from current BB.
  1155. if (VI->getParent() == FromBB)
  1156. return true;
  1157. // Is already exported, noop.
  1158. return FuncInfo.isExportedInst(V);
  1159. }
  1160. // If this is an argument, we can export it if the BB is the entry block or
  1161. // if it is already exported.
  1162. if (isa<Argument>(V)) {
  1163. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1164. return true;
  1165. // Otherwise, can only export this if it is already exported.
  1166. return FuncInfo.isExportedInst(V);
  1167. }
  1168. // Otherwise, constants can always be exported.
  1169. return true;
  1170. }
  1171. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1172. uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
  1173. const MachineBasicBlock *Dst) const {
  1174. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1175. if (!BPI)
  1176. return 0;
  1177. const BasicBlock *SrcBB = Src->getBasicBlock();
  1178. const BasicBlock *DstBB = Dst->getBasicBlock();
  1179. return BPI->getEdgeWeight(SrcBB, DstBB);
  1180. }
  1181. void SelectionDAGBuilder::
  1182. addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
  1183. uint32_t Weight /* = 0 */) {
  1184. if (!Weight)
  1185. Weight = getEdgeWeight(Src, Dst);
  1186. Src->addSuccessor(Dst, Weight);
  1187. }
  1188. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1189. if (const Instruction *I = dyn_cast<Instruction>(V))
  1190. return I->getParent() == BB;
  1191. return true;
  1192. }
  1193. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1194. /// This function emits a branch and is used at the leaves of an OR or an
  1195. /// AND operator tree.
  1196. ///
  1197. void
  1198. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1199. MachineBasicBlock *TBB,
  1200. MachineBasicBlock *FBB,
  1201. MachineBasicBlock *CurBB,
  1202. MachineBasicBlock *SwitchBB) {
  1203. const BasicBlock *BB = CurBB->getBasicBlock();
  1204. // If the leaf of the tree is a comparison, merge the condition into
  1205. // the caseblock.
  1206. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1207. // The operands of the cmp have to be in this block. We don't know
  1208. // how to export them from some other block. If this is the first block
  1209. // of the sequence, no exporting is needed.
  1210. if (CurBB == SwitchBB ||
  1211. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1212. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1213. ISD::CondCode Condition;
  1214. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1215. Condition = getICmpCondCode(IC->getPredicate());
  1216. } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
  1217. Condition = getFCmpCondCode(FC->getPredicate());
  1218. if (TM.Options.NoNaNsFPMath)
  1219. Condition = getFCmpCodeWithoutNaN(Condition);
  1220. } else {
  1221. Condition = ISD::SETEQ; // silence warning.
  1222. llvm_unreachable("Unknown compare instruction");
  1223. }
  1224. CaseBlock CB(Condition, BOp->getOperand(0),
  1225. BOp->getOperand(1), NULL, TBB, FBB, CurBB);
  1226. SwitchCases.push_back(CB);
  1227. return;
  1228. }
  1229. }
  1230. // Create a CaseBlock record representing this branch.
  1231. CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1232. NULL, TBB, FBB, CurBB);
  1233. SwitchCases.push_back(CB);
  1234. }
  1235. /// FindMergedConditions - If Cond is an expression like
  1236. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1237. MachineBasicBlock *TBB,
  1238. MachineBasicBlock *FBB,
  1239. MachineBasicBlock *CurBB,
  1240. MachineBasicBlock *SwitchBB,
  1241. unsigned Opc) {
  1242. // If this node is not part of the or/and tree, emit it as a branch.
  1243. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1244. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1245. (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
  1246. BOp->getParent() != CurBB->getBasicBlock() ||
  1247. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1248. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1249. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
  1250. return;
  1251. }
  1252. // Create TmpBB after CurBB.
  1253. MachineFunction::iterator BBI = CurBB;
  1254. MachineFunction &MF = DAG.getMachineFunction();
  1255. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1256. CurBB->getParent()->insert(++BBI, TmpBB);
  1257. if (Opc == Instruction::Or) {
  1258. // Codegen X | Y as:
  1259. // jmp_if_X TBB
  1260. // jmp TmpBB
  1261. // TmpBB:
  1262. // jmp_if_Y TBB
  1263. // jmp FBB
  1264. //
  1265. // Emit the LHS condition.
  1266. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
  1267. // Emit the RHS condition into TmpBB.
  1268. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
  1269. } else {
  1270. assert(Opc == Instruction::And && "Unknown merge op!");
  1271. // Codegen X & Y as:
  1272. // jmp_if_X TmpBB
  1273. // jmp FBB
  1274. // TmpBB:
  1275. // jmp_if_Y TBB
  1276. // jmp FBB
  1277. //
  1278. // This requires creation of TmpBB after CurBB.
  1279. // Emit the LHS condition.
  1280. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
  1281. // Emit the RHS condition into TmpBB.
  1282. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
  1283. }
  1284. }
  1285. /// If the set of cases should be emitted as a series of branches, return true.
  1286. /// If we should emit this as a bunch of and/or'd together conditions, return
  1287. /// false.
  1288. bool
  1289. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1290. if (Cases.size() != 2) return true;
  1291. // If this is two comparisons of the same values or'd or and'd together, they
  1292. // will get folded into a single comparison, so don't emit two blocks.
  1293. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1294. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1295. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1296. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1297. return false;
  1298. }
  1299. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1300. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1301. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1302. Cases[0].CC == Cases[1].CC &&
  1303. isa<Constant>(Cases[0].CmpRHS) &&
  1304. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1305. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1306. return false;
  1307. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1308. return false;
  1309. }
  1310. return true;
  1311. }
  1312. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1313. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1314. // Update machine-CFG edges.
  1315. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1316. // Figure out which block is immediately after the current one.
  1317. MachineBasicBlock *NextBlock = 0;
  1318. MachineFunction::iterator BBI = BrMBB;
  1319. if (++BBI != FuncInfo.MF->end())
  1320. NextBlock = BBI;
  1321. if (I.isUnconditional()) {
  1322. // Update machine-CFG edges.
  1323. BrMBB->addSuccessor(Succ0MBB);
  1324. // If this is not a fall-through branch, emit the branch.
  1325. if (Succ0MBB != NextBlock)
  1326. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1327. MVT::Other, getControlRoot(),
  1328. DAG.getBasicBlock(Succ0MBB)));
  1329. return;
  1330. }
  1331. // If this condition is one of the special cases we handle, do special stuff
  1332. // now.
  1333. const Value *CondVal = I.getCondition();
  1334. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1335. // If this is a series of conditions that are or'd or and'd together, emit
  1336. // this as a sequence of branches instead of setcc's with and/or operations.
  1337. // As long as jumps are not expensive, this should improve performance.
  1338. // For example, instead of something like:
  1339. // cmp A, B
  1340. // C = seteq
  1341. // cmp D, E
  1342. // F = setle
  1343. // or C, F
  1344. // jnz foo
  1345. // Emit:
  1346. // cmp A, B
  1347. // je foo
  1348. // cmp D, E
  1349. // jle foo
  1350. //
  1351. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1352. if (!TM.getTargetLowering()->isJumpExpensive() &&
  1353. BOp->hasOneUse() &&
  1354. (BOp->getOpcode() == Instruction::And ||
  1355. BOp->getOpcode() == Instruction::Or)) {
  1356. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1357. BOp->getOpcode());
  1358. // If the compares in later blocks need to use values not currently
  1359. // exported from this block, export them now. This block should always
  1360. // be the first entry.
  1361. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1362. // Allow some cases to be rejected.
  1363. if (ShouldEmitAsBranches(SwitchCases)) {
  1364. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1365. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1366. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1367. }
  1368. // Emit the branch for this block.
  1369. visitSwitchCase(SwitchCases[0], BrMBB);
  1370. SwitchCases.erase(SwitchCases.begin());
  1371. return;
  1372. }
  1373. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1374. // SwitchCases.
  1375. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1376. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1377. SwitchCases.clear();
  1378. }
  1379. }
  1380. // Create a CaseBlock record representing this branch.
  1381. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1382. NULL, Succ0MBB, Succ1MBB, BrMBB);
  1383. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1384. // cond branch.
  1385. visitSwitchCase(CB, BrMBB);
  1386. }
  1387. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1388. /// the binary search tree resulting from lowering a switch instruction.
  1389. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1390. MachineBasicBlock *SwitchBB) {
  1391. SDValue Cond;
  1392. SDValue CondLHS = getValue(CB.CmpLHS);
  1393. SDLoc dl = getCurSDLoc();
  1394. // Build the setcc now.
  1395. if (CB.CmpMHS == NULL) {
  1396. // Fold "(X == true)" to X and "(X == false)" to !X to
  1397. // handle common cases produced by branch lowering.
  1398. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1399. CB.CC == ISD::SETEQ)
  1400. Cond = CondLHS;
  1401. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1402. CB.CC == ISD::SETEQ) {
  1403. SDValue True = DAG.getConstant(1, CondLHS.getValueType());
  1404. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1405. } else
  1406. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1407. } else {
  1408. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1409. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1410. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1411. SDValue CmpOp = getValue(CB.CmpMHS);
  1412. EVT VT = CmpOp.getValueType();
  1413. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1414. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
  1415. ISD::SETLE);
  1416. } else {
  1417. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1418. VT, CmpOp, DAG.getConstant(Low, VT));
  1419. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1420. DAG.getConstant(High-Low, VT), ISD::SETULE);
  1421. }
  1422. }
  1423. // Update successor info
  1424. addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
  1425. // TrueBB and FalseBB are always different unless the incoming IR is
  1426. // degenerate. This only happens when running llc on weird IR.
  1427. if (CB.TrueBB != CB.FalseBB)
  1428. addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
  1429. // Set NextBlock to be the MBB immediately after the current one, if any.
  1430. // This is used to avoid emitting unnecessary branches to the next block.
  1431. MachineBasicBlock *NextBlock = 0;
  1432. MachineFunction::iterator BBI = SwitchBB;
  1433. if (++BBI != FuncInfo.MF->end())
  1434. NextBlock = BBI;
  1435. // If the lhs block is the next block, invert the condition so that we can
  1436. // fall through to the lhs instead of the rhs block.
  1437. if (CB.TrueBB == NextBlock) {
  1438. std::swap(CB.TrueBB, CB.FalseBB);
  1439. SDValue True = DAG.getConstant(1, Cond.getValueType());
  1440. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1441. }
  1442. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1443. MVT::Other, getControlRoot(), Cond,
  1444. DAG.getBasicBlock(CB.TrueBB));
  1445. // Insert the false branch. Do this even if it's a fall through branch,
  1446. // this makes it easier to do DAG optimizations which require inverting
  1447. // the branch condition.
  1448. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1449. DAG.getBasicBlock(CB.FalseBB));
  1450. DAG.setRoot(BrCond);
  1451. }
  1452. /// visitJumpTable - Emit JumpTable node in the current MBB
  1453. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1454. // Emit the code for the jump table
  1455. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1456. EVT PTy = TM.getTargetLowering()->getPointerTy();
  1457. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1458. JT.Reg, PTy);
  1459. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1460. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  1461. MVT::Other, Index.getValue(1),
  1462. Table, Index);
  1463. DAG.setRoot(BrJumpTable);
  1464. }
  1465. /// visitJumpTableHeader - This function emits necessary code to produce index
  1466. /// in the JumpTable from switch case.
  1467. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1468. JumpTableHeader &JTH,
  1469. MachineBasicBlock *SwitchBB) {
  1470. // Subtract the lowest switch case value from the value being switched on and
  1471. // conditional branch to default mbb if the result is greater than the
  1472. // difference between smallest and largest cases.
  1473. SDValue SwitchOp = getValue(JTH.SValue);
  1474. EVT VT = SwitchOp.getValueType();
  1475. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
  1476. DAG.getConstant(JTH.First, VT));
  1477. // The SDNode we just created, which holds the value being switched on minus
  1478. // the smallest case value, needs to be copied to a virtual register so it
  1479. // can be used as an index into the jump table in a subsequent basic block.
  1480. // This value may be smaller or larger than the target's pointer type, and
  1481. // therefore require extension or truncating.
  1482. const TargetLowering *TLI = TM.getTargetLowering();
  1483. SwitchOp = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), TLI->getPointerTy());
  1484. unsigned JumpTableReg = FuncInfo.CreateReg(TLI->getPointerTy());
  1485. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
  1486. JumpTableReg, SwitchOp);
  1487. JT.Reg = JumpTableReg;
  1488. // Emit the range check for the jump table, and branch to the default block
  1489. // for the switch statement if the value being switched on exceeds the largest
  1490. // case in the switch.
  1491. SDValue CMP = DAG.getSetCC(getCurSDLoc(),
  1492. TLI->getSetCCResultType(*DAG.getContext(),
  1493. Sub.getValueType()),
  1494. Sub,
  1495. DAG.getConstant(JTH.Last - JTH.First,VT),
  1496. ISD::SETUGT);
  1497. // Set NextBlock to be the MBB immediately after the current one, if any.
  1498. // This is used to avoid emitting unnecessary branches to the next block.
  1499. MachineBasicBlock *NextBlock = 0;
  1500. MachineFunction::iterator BBI = SwitchBB;
  1501. if (++BBI != FuncInfo.MF->end())
  1502. NextBlock = BBI;
  1503. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1504. MVT::Other, CopyTo, CMP,
  1505. DAG.getBasicBlock(JT.Default));
  1506. if (JT.MBB != NextBlock)
  1507. BrCond = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrCond,
  1508. DAG.getBasicBlock(JT.MBB));
  1509. DAG.setRoot(BrCond);
  1510. }
  1511. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  1512. /// tail spliced into a stack protector check success bb.
  1513. ///
  1514. /// For a high level explanation of how this fits into the stack protector
  1515. /// generation see the comment on the declaration of class
  1516. /// StackProtectorDescriptor.
  1517. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  1518. MachineBasicBlock *ParentBB) {
  1519. // First create the loads to the guard/stack slot for the comparison.
  1520. const TargetLowering *TLI = TM.getTargetLowering();
  1521. EVT PtrTy = TLI->getPointerTy();
  1522. MachineFrameInfo *MFI = ParentBB->getParent()->getFrameInfo();
  1523. int FI = MFI->getStackProtectorIndex();
  1524. const Value *IRGuard = SPD.getGuard();
  1525. SDValue GuardPtr = getValue(IRGuard);
  1526. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  1527. unsigned Align =
  1528. TLI->getDataLayout()->getPrefTypeAlignment(IRGuard->getType());
  1529. SDValue Guard = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
  1530. GuardPtr, MachinePointerInfo(IRGuard, 0),
  1531. true, false, false, Align);
  1532. SDValue StackSlot = DAG.getLoad(PtrTy, getCurSDLoc(), DAG.getEntryNode(),
  1533. StackSlotPtr,
  1534. MachinePointerInfo::getFixedStack(FI),
  1535. true, false, false, Align);
  1536. // Perform the comparison via a subtract/getsetcc.
  1537. EVT VT = Guard.getValueType();
  1538. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, Guard, StackSlot);
  1539. SDValue Cmp = DAG.getSetCC(getCurSDLoc(),
  1540. TLI->getSetCCResultType(*DAG.getContext(),
  1541. Sub.getValueType()),
  1542. Sub, DAG.getConstant(0, VT),
  1543. ISD::SETNE);
  1544. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  1545. // branch to failure MBB.
  1546. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1547. MVT::Other, StackSlot.getOperand(0),
  1548. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  1549. // Otherwise branch to success MBB.
  1550. SDValue Br = DAG.getNode(ISD::BR, getCurSDLoc(),
  1551. MVT::Other, BrCond,
  1552. DAG.getBasicBlock(SPD.getSuccessMBB()));
  1553. DAG.setRoot(Br);
  1554. }
  1555. /// Codegen the failure basic block for a stack protector check.
  1556. ///
  1557. /// A failure stack protector machine basic block consists simply of a call to
  1558. /// __stack_chk_fail().
  1559. ///
  1560. /// For a high level explanation of how this fits into the stack protector
  1561. /// generation see the comment on the declaration of class
  1562. /// StackProtectorDescriptor.
  1563. void
  1564. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  1565. const TargetLowering *TLI = TM.getTargetLowering();
  1566. SDValue Chain = TLI->makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
  1567. MVT::isVoid, 0, 0, false, getCurSDLoc(),
  1568. false, false).second;
  1569. DAG.setRoot(Chain);
  1570. }
  1571. /// visitBitTestHeader - This function emits necessary code to produce value
  1572. /// suitable for "bit tests"
  1573. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  1574. MachineBasicBlock *SwitchBB) {
  1575. // Subtract the minimum value
  1576. SDValue SwitchOp = getValue(B.SValue);
  1577. EVT VT = SwitchOp.getValueType();
  1578. SDValue Sub = DAG.getNode(ISD::SUB, getCurSDLoc(), VT, SwitchOp,
  1579. DAG.getConstant(B.First, VT));
  1580. // Check range
  1581. const TargetLowering *TLI = TM.getTargetLowering();
  1582. SDValue RangeCmp = DAG.getSetCC(getCurSDLoc(),
  1583. TLI->getSetCCResultType(*DAG.getContext(),
  1584. Sub.getValueType()),
  1585. Sub, DAG.getConstant(B.Range, VT),
  1586. ISD::SETUGT);
  1587. // Determine the type of the test operands.
  1588. bool UsePtrType = false;
  1589. if (!TLI->isTypeLegal(VT))
  1590. UsePtrType = true;
  1591. else {
  1592. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  1593. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  1594. // Switch table case range are encoded into series of masks.
  1595. // Just use pointer type, it's guaranteed to fit.
  1596. UsePtrType = true;
  1597. break;
  1598. }
  1599. }
  1600. if (UsePtrType) {
  1601. VT = TLI->getPointerTy();
  1602. Sub = DAG.getZExtOrTrunc(Sub, getCurSDLoc(), VT);
  1603. }
  1604. B.RegVT = VT.getSimpleVT();
  1605. B.Reg = FuncInfo.CreateReg(B.RegVT);
  1606. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurSDLoc(),
  1607. B.Reg, Sub);
  1608. // Set NextBlock to be the MBB immediately after the current one, if any.
  1609. // This is used to avoid emitting unnecessary branches to the next block.
  1610. MachineBasicBlock *NextBlock = 0;
  1611. MachineFunction::iterator BBI = SwitchBB;
  1612. if (++BBI != FuncInfo.MF->end())
  1613. NextBlock = BBI;
  1614. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1615. addSuccessorWithWeight(SwitchBB, B.Default);
  1616. addSuccessorWithWeight(SwitchBB, MBB);
  1617. SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1618. MVT::Other, CopyTo, RangeCmp,
  1619. DAG.getBasicBlock(B.Default));
  1620. if (MBB != NextBlock)
  1621. BrRange = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, CopyTo,
  1622. DAG.getBasicBlock(MBB));
  1623. DAG.setRoot(BrRange);
  1624. }
  1625. /// visitBitTestCase - this function produces one "bit test"
  1626. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  1627. MachineBasicBlock* NextMBB,
  1628. uint32_t BranchWeightToNext,
  1629. unsigned Reg,
  1630. BitTestCase &B,
  1631. MachineBasicBlock *SwitchBB) {
  1632. MVT VT = BB.RegVT;
  1633. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  1634. Reg, VT);
  1635. SDValue Cmp;
  1636. unsigned PopCount = CountPopulation_64(B.Mask);
  1637. const TargetLowering *TLI = TM.getTargetLowering();
  1638. if (PopCount == 1) {
  1639. // Testing for a single bit; just compare the shift count with what it
  1640. // would need to be to shift a 1 bit in that position.
  1641. Cmp = DAG.getSetCC(getCurSDLoc(),
  1642. TLI->getSetCCResultType(*DAG.getContext(), VT),
  1643. ShiftOp,
  1644. DAG.getConstant(countTrailingZeros(B.Mask), VT),
  1645. ISD::SETEQ);
  1646. } else if (PopCount == BB.Range) {
  1647. // There is only one zero bit in the range, test for it directly.
  1648. Cmp = DAG.getSetCC(getCurSDLoc(),
  1649. TLI->getSetCCResultType(*DAG.getContext(), VT),
  1650. ShiftOp,
  1651. DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
  1652. ISD::SETNE);
  1653. } else {
  1654. // Make desired shift
  1655. SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurSDLoc(), VT,
  1656. DAG.getConstant(1, VT), ShiftOp);
  1657. // Emit bit tests and jumps
  1658. SDValue AndOp = DAG.getNode(ISD::AND, getCurSDLoc(),
  1659. VT, SwitchVal, DAG.getConstant(B.Mask, VT));
  1660. Cmp = DAG.getSetCC(getCurSDLoc(),
  1661. TLI->getSetCCResultType(*DAG.getContext(), VT),
  1662. AndOp, DAG.getConstant(0, VT),
  1663. ISD::SETNE);
  1664. }
  1665. // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
  1666. addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
  1667. // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
  1668. addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
  1669. SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurSDLoc(),
  1670. MVT::Other, getControlRoot(),
  1671. Cmp, DAG.getBasicBlock(B.TargetBB));
  1672. // Set NextBlock to be the MBB immediately after the current one, if any.
  1673. // This is used to avoid emitting unnecessary branches to the next block.
  1674. MachineBasicBlock *NextBlock = 0;
  1675. MachineFunction::iterator BBI = SwitchBB;
  1676. if (++BBI != FuncInfo.MF->end())
  1677. NextBlock = BBI;
  1678. if (NextMBB != NextBlock)
  1679. BrAnd = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, BrAnd,
  1680. DAG.getBasicBlock(NextMBB));
  1681. DAG.setRoot(BrAnd);
  1682. }
  1683. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  1684. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  1685. // Retrieve successors.
  1686. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1687. MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
  1688. const Value *Callee(I.getCalledValue());
  1689. const Function *Fn = dyn_cast<Function>(Callee);
  1690. if (isa<InlineAsm>(Callee))
  1691. visitInlineAsm(&I);
  1692. else if (Fn && Fn->isIntrinsic()) {
  1693. assert(Fn->getIntrinsicID() == Intrinsic::donothing);
  1694. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  1695. } else
  1696. LowerCallTo(&I, getValue(Callee), false, LandingPad);
  1697. // If the value of the invoke is used outside of its defining block, make it
  1698. // available as a virtual register.
  1699. CopyToExportRegsIfNeeded(&I);
  1700. // Update successor info
  1701. addSuccessorWithWeight(InvokeMBB, Return);
  1702. addSuccessorWithWeight(InvokeMBB, LandingPad);
  1703. // Drop into normal successor.
  1704. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1705. MVT::Other, getControlRoot(),
  1706. DAG.getBasicBlock(Return)));
  1707. }
  1708. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  1709. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  1710. }
  1711. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  1712. assert(FuncInfo.MBB->isLandingPad() &&
  1713. "Call to landingpad not in landing pad!");
  1714. MachineBasicBlock *MBB = FuncInfo.MBB;
  1715. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  1716. AddLandingPadInfo(LP, MMI, MBB);
  1717. // If there aren't registers to copy the values into (e.g., during SjLj
  1718. // exceptions), then don't bother to create these DAG nodes.
  1719. const TargetLowering *TLI = TM.getTargetLowering();
  1720. if (TLI->getExceptionPointerRegister() == 0 &&
  1721. TLI->getExceptionSelectorRegister() == 0)
  1722. return;
  1723. SmallVector<EVT, 2> ValueVTs;
  1724. ComputeValueVTs(*TLI, LP.getType(), ValueVTs);
  1725. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  1726. // Get the two live-in registers as SDValues. The physregs have already been
  1727. // copied into virtual registers.
  1728. SDValue Ops[2];
  1729. Ops[0] = DAG.getZExtOrTrunc(
  1730. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1731. FuncInfo.ExceptionPointerVirtReg, TLI->getPointerTy()),
  1732. getCurSDLoc(), ValueVTs[0]);
  1733. Ops[1] = DAG.getZExtOrTrunc(
  1734. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1735. FuncInfo.ExceptionSelectorVirtReg, TLI->getPointerTy()),
  1736. getCurSDLoc(), ValueVTs[1]);
  1737. // Merge into one.
  1738. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  1739. DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
  1740. &Ops[0], 2);
  1741. setValue(&LP, Res);
  1742. }
  1743. /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
  1744. /// small case ranges).
  1745. bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
  1746. CaseRecVector& WorkList,
  1747. const Value* SV,
  1748. MachineBasicBlock *Default,
  1749. MachineBasicBlock *SwitchBB) {
  1750. // Size is the number of Cases represented by this range.
  1751. size_t Size = CR.Range.second - CR.Range.first;
  1752. if (Size > 3)
  1753. return false;
  1754. // Get the MachineFunction which holds the current MBB. This is used when
  1755. // inserting any additional MBBs necessary to represent the switch.
  1756. MachineFunction *CurMF = FuncInfo.MF;
  1757. // Figure out which block is immediately after the current one.
  1758. MachineBasicBlock *NextBlock = 0;
  1759. MachineFunction::iterator BBI = CR.CaseBB;
  1760. if (++BBI != FuncInfo.MF->end())
  1761. NextBlock = BBI;
  1762. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1763. // If any two of the cases has the same destination, and if one value
  1764. // is the same as the other, but has one bit unset that the other has set,
  1765. // use bit manipulation to do two compares at once. For example:
  1766. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  1767. // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
  1768. // TODO: Handle cases where CR.CaseBB != SwitchBB.
  1769. if (Size == 2 && CR.CaseBB == SwitchBB) {
  1770. Case &Small = *CR.Range.first;
  1771. Case &Big = *(CR.Range.second-1);
  1772. if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
  1773. const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
  1774. const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
  1775. // Check that there is only one bit different.
  1776. if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
  1777. (SmallValue | BigValue) == BigValue) {
  1778. // Isolate the common bit.
  1779. APInt CommonBit = BigValue & ~SmallValue;
  1780. assert((SmallValue | CommonBit) == BigValue &&
  1781. CommonBit.countPopulation() == 1 && "Not a common bit?");
  1782. SDValue CondLHS = getValue(SV);
  1783. EVT VT = CondLHS.getValueType();
  1784. SDLoc DL = getCurSDLoc();
  1785. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  1786. DAG.getConstant(CommonBit, VT));
  1787. SDValue Cond = DAG.getSetCC(DL, MVT::i1,
  1788. Or, DAG.getConstant(BigValue, VT),
  1789. ISD::SETEQ);
  1790. // Update successor info.
  1791. // Both Small and Big will jump to Small.BB, so we sum up the weights.
  1792. addSuccessorWithWeight(SwitchBB, Small.BB,
  1793. Small.ExtraWeight + Big.ExtraWeight);
  1794. addSuccessorWithWeight(SwitchBB, Default,
  1795. // The default destination is the first successor in IR.
  1796. BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
  1797. // Insert the true branch.
  1798. SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
  1799. getControlRoot(), Cond,
  1800. DAG.getBasicBlock(Small.BB));
  1801. // Insert the false branch.
  1802. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  1803. DAG.getBasicBlock(Default));
  1804. DAG.setRoot(BrCond);
  1805. return true;
  1806. }
  1807. }
  1808. }
  1809. // Order cases by weight so the most likely case will be checked first.
  1810. uint32_t UnhandledWeights = 0;
  1811. if (BPI) {
  1812. for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
  1813. uint32_t IWeight = I->ExtraWeight;
  1814. UnhandledWeights += IWeight;
  1815. for (CaseItr J = CR.Range.first; J < I; ++J) {
  1816. uint32_t JWeight = J->ExtraWeight;
  1817. if (IWeight > JWeight)
  1818. std::swap(*I, *J);
  1819. }
  1820. }
  1821. }
  1822. // Rearrange the case blocks so that the last one falls through if possible.
  1823. Case &BackCase = *(CR.Range.second-1);
  1824. if (Size > 1 &&
  1825. NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
  1826. // The last case block won't fall through into 'NextBlock' if we emit the
  1827. // branches in this order. See if rearranging a case value would help.
  1828. // We start at the bottom as it's the case with the least weight.
  1829. for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I)
  1830. if (I->BB == NextBlock) {
  1831. std::swap(*I, BackCase);
  1832. break;
  1833. }
  1834. }
  1835. // Create a CaseBlock record representing a conditional branch to
  1836. // the Case's target mbb if the value being switched on SV is equal
  1837. // to C.
  1838. MachineBasicBlock *CurBlock = CR.CaseBB;
  1839. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  1840. MachineBasicBlock *FallThrough;
  1841. if (I != E-1) {
  1842. FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
  1843. CurMF->insert(BBI, FallThrough);
  1844. // Put SV in a virtual register to make it available from the new blocks.
  1845. ExportFromCurrentBlock(SV);
  1846. } else {
  1847. // If the last case doesn't match, go to the default block.
  1848. FallThrough = Default;
  1849. }
  1850. const Value *RHS, *LHS, *MHS;
  1851. ISD::CondCode CC;
  1852. if (I->High == I->Low) {
  1853. // This is just small small case range :) containing exactly 1 case
  1854. CC = ISD::SETEQ;
  1855. LHS = SV; RHS = I->High; MHS = NULL;
  1856. } else {
  1857. CC = ISD::SETLE;
  1858. LHS = I->Low; MHS = SV; RHS = I->High;
  1859. }
  1860. // The false weight should be sum of all un-handled cases.
  1861. UnhandledWeights -= I->ExtraWeight;
  1862. CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
  1863. /* me */ CurBlock,
  1864. /* trueweight */ I->ExtraWeight,
  1865. /* falseweight */ UnhandledWeights);
  1866. // If emitting the first comparison, just call visitSwitchCase to emit the
  1867. // code into the current block. Otherwise, push the CaseBlock onto the
  1868. // vector to be later processed by SDISel, and insert the node's MBB
  1869. // before the next MBB.
  1870. if (CurBlock == SwitchBB)
  1871. visitSwitchCase(CB, SwitchBB);
  1872. else
  1873. SwitchCases.push_back(CB);
  1874. CurBlock = FallThrough;
  1875. }
  1876. return true;
  1877. }
  1878. static inline bool areJTsAllowed(const TargetLowering &TLI) {
  1879. return TLI.supportJumpTables() &&
  1880. (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  1881. TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
  1882. }
  1883. static APInt ComputeRange(const APInt &First, const APInt &Last) {
  1884. uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
  1885. APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
  1886. return (LastExt - FirstExt + 1ULL);
  1887. }
  1888. /// handleJTSwitchCase - Emit jumptable for current switch case range
  1889. bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
  1890. CaseRecVector &WorkList,
  1891. const Value *SV,
  1892. MachineBasicBlock *Default,
  1893. MachineBasicBlock *SwitchBB) {
  1894. Case& FrontCase = *CR.Range.first;
  1895. Case& BackCase = *(CR.Range.second-1);
  1896. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1897. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  1898. APInt TSize(First.getBitWidth(), 0);
  1899. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
  1900. TSize += I->size();
  1901. const TargetLowering *TLI = TM.getTargetLowering();
  1902. if (!areJTsAllowed(*TLI) || TSize.ult(TLI->getMinimumJumpTableEntries()))
  1903. return false;
  1904. APInt Range = ComputeRange(First, Last);
  1905. // The density is TSize / Range. Require at least 40%.
  1906. // It should not be possible for IntTSize to saturate for sane code, but make
  1907. // sure we handle Range saturation correctly.
  1908. uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
  1909. uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
  1910. if (IntTSize * 10 < IntRange * 4)
  1911. return false;
  1912. DEBUG(dbgs() << "Lowering jump table\n"
  1913. << "First entry: " << First << ". Last entry: " << Last << '\n'
  1914. << "Range: " << Range << ". Size: " << TSize << ".\n\n");
  1915. // Get the MachineFunction which holds the current MBB. This is used when
  1916. // inserting any additional MBBs necessary to represent the switch.
  1917. MachineFunction *CurMF = FuncInfo.MF;
  1918. // Figure out which block is immediately after the current one.
  1919. MachineFunction::iterator BBI = CR.CaseBB;
  1920. ++BBI;
  1921. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1922. // Create a new basic block to hold the code for loading the address
  1923. // of the jump table, and jumping to it. Update successor information;
  1924. // we will either branch to the default case for the switch, or the jump
  1925. // table.
  1926. MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1927. CurMF->insert(BBI, JumpTableBB);
  1928. addSuccessorWithWeight(CR.CaseBB, Default);
  1929. addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
  1930. // Build a vector of destination BBs, corresponding to each target
  1931. // of the jump table. If the value of the jump table slot corresponds to
  1932. // a case statement, push the case's BB onto the vector, otherwise, push
  1933. // the default BB.
  1934. std::vector<MachineBasicBlock*> DestBBs;
  1935. APInt TEI = First;
  1936. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
  1937. const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
  1938. const APInt &High = cast<ConstantInt>(I->High)->getValue();
  1939. if (Low.sle(TEI) && TEI.sle(High)) {
  1940. DestBBs.push_back(I->BB);
  1941. if (TEI==High)
  1942. ++I;
  1943. } else {
  1944. DestBBs.push_back(Default);
  1945. }
  1946. }
  1947. // Calculate weight for each unique destination in CR.
  1948. DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
  1949. if (FuncInfo.BPI)
  1950. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  1951. DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
  1952. DestWeights.find(I->BB);
  1953. if (Itr != DestWeights.end())
  1954. Itr->second += I->ExtraWeight;
  1955. else
  1956. DestWeights[I->BB] = I->ExtraWeight;
  1957. }
  1958. // Update successor info. Add one edge to each unique successor.
  1959. BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
  1960. for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
  1961. E = DestBBs.end(); I != E; ++I) {
  1962. if (!SuccsHandled[(*I)->getNumber()]) {
  1963. SuccsHandled[(*I)->getNumber()] = true;
  1964. DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
  1965. DestWeights.find(*I);
  1966. addSuccessorWithWeight(JumpTableBB, *I,
  1967. Itr != DestWeights.end() ? Itr->second : 0);
  1968. }
  1969. }
  1970. // Create a jump table index for this jump table.
  1971. unsigned JTEncoding = TLI->getJumpTableEncoding();
  1972. unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
  1973. ->createJumpTableIndex(DestBBs);
  1974. // Set the jump table information so that we can codegen it as a second
  1975. // MachineBasicBlock
  1976. JumpTable JT(-1U, JTI, JumpTableBB, Default);
  1977. JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
  1978. if (CR.CaseBB == SwitchBB)
  1979. visitJumpTableHeader(JT, JTH, SwitchBB);
  1980. JTCases.push_back(JumpTableBlock(JTH, JT));
  1981. return true;
  1982. }
  1983. /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
  1984. /// 2 subtrees.
  1985. bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
  1986. CaseRecVector& WorkList,
  1987. const Value* SV,
  1988. MachineBasicBlock* Default,
  1989. MachineBasicBlock* SwitchBB) {
  1990. // Get the MachineFunction which holds the current MBB. This is used when
  1991. // inserting any additional MBBs necessary to represent the switch.
  1992. MachineFunction *CurMF = FuncInfo.MF;
  1993. // Figure out which block is immediately after the current one.
  1994. MachineFunction::iterator BBI = CR.CaseBB;
  1995. ++BBI;
  1996. Case& FrontCase = *CR.Range.first;
  1997. Case& BackCase = *(CR.Range.second-1);
  1998. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1999. // Size is the number of Cases represented by this range.
  2000. unsigned Size = CR.Range.second - CR.Range.first;
  2001. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  2002. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  2003. double FMetric = 0;
  2004. CaseItr Pivot = CR.Range.first + Size/2;
  2005. // Select optimal pivot, maximizing sum density of LHS and RHS. This will
  2006. // (heuristically) allow us to emit JumpTable's later.
  2007. APInt TSize(First.getBitWidth(), 0);
  2008. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  2009. I!=E; ++I)
  2010. TSize += I->size();
  2011. APInt LSize = FrontCase.size();
  2012. APInt RSize = TSize-LSize;
  2013. DEBUG(dbgs() << "Selecting best pivot: \n"
  2014. << "First: " << First << ", Last: " << Last <<'\n'
  2015. << "LSize: " << LSize << ", RSize: " << RSize << '\n');
  2016. for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
  2017. J!=E; ++I, ++J) {
  2018. const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
  2019. const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
  2020. APInt Range = ComputeRange(LEnd, RBegin);
  2021. assert((Range - 2ULL).isNonNegative() &&
  2022. "Invalid case distance");
  2023. // Use volatile double here to avoid excess precision issues on some hosts,
  2024. // e.g. that use 80-bit X87 registers.
  2025. volatile double LDensity =
  2026. (double)LSize.roundToDouble() /
  2027. (LEnd - First + 1ULL).roundToDouble();
  2028. volatile double RDensity =
  2029. (double)RSize.roundToDouble() /
  2030. (Last - RBegin + 1ULL).roundToDouble();
  2031. double Metric = Range.logBase2()*(LDensity+RDensity);
  2032. // Should always split in some non-trivial place
  2033. DEBUG(dbgs() <<"=>Step\n"
  2034. << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
  2035. << "LDensity: " << LDensity
  2036. << ", RDensity: " << RDensity << '\n'
  2037. << "Metric: " << Metric << '\n');
  2038. if (FMetric < Metric) {
  2039. Pivot = J;
  2040. FMetric = Metric;
  2041. DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
  2042. }
  2043. LSize += J->size();
  2044. RSize -= J->size();
  2045. }
  2046. const TargetLowering *TLI = TM.getTargetLowering();
  2047. if (areJTsAllowed(*TLI)) {
  2048. // If our case is dense we *really* should handle it earlier!
  2049. assert((FMetric > 0) && "Should handle dense range earlier!");
  2050. } else {
  2051. Pivot = CR.Range.first + Size/2;
  2052. }
  2053. CaseRange LHSR(CR.Range.first, Pivot);
  2054. CaseRange RHSR(Pivot, CR.Range.second);
  2055. const Constant *C = Pivot->Low;
  2056. MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
  2057. // We know that we branch to the LHS if the Value being switched on is
  2058. // less than the Pivot value, C. We use this to optimize our binary
  2059. // tree a bit, by recognizing that if SV is greater than or equal to the
  2060. // LHS's Case Value, and that Case Value is exactly one less than the
  2061. // Pivot's Value, then we can branch directly to the LHS's Target,
  2062. // rather than creating a leaf node for it.
  2063. if ((LHSR.second - LHSR.first) == 1 &&
  2064. LHSR.first->High == CR.GE &&
  2065. cast<ConstantInt>(C)->getValue() ==
  2066. (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
  2067. TrueBB = LHSR.first->BB;
  2068. } else {
  2069. TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2070. CurMF->insert(BBI, TrueBB);
  2071. WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
  2072. // Put SV in a virtual register to make it available from the new blocks.
  2073. ExportFromCurrentBlock(SV);
  2074. }
  2075. // Similar to the optimization above, if the Value being switched on is
  2076. // known to be less than the Constant CR.LT, and the current Case Value
  2077. // is CR.LT - 1, then we can branch directly to the target block for
  2078. // the current Case Value, rather than emitting a RHS leaf node for it.
  2079. if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
  2080. cast<ConstantInt>(RHSR.first->Low)->getValue() ==
  2081. (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
  2082. FalseBB = RHSR.first->BB;
  2083. } else {
  2084. FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2085. CurMF->insert(BBI, FalseBB);
  2086. WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
  2087. // Put SV in a virtual register to make it available from the new blocks.
  2088. ExportFromCurrentBlock(SV);
  2089. }
  2090. // Create a CaseBlock record representing a conditional branch to
  2091. // the LHS node if the value being switched on SV is less than C.
  2092. // Otherwise, branch to LHS.
  2093. CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
  2094. if (CR.CaseBB == SwitchBB)
  2095. visitSwitchCase(CB, SwitchBB);
  2096. else
  2097. SwitchCases.push_back(CB);
  2098. return true;
  2099. }
  2100. /// handleBitTestsSwitchCase - if current case range has few destination and
  2101. /// range span less, than machine word bitwidth, encode case range into series
  2102. /// of masks and emit bit tests with these masks.
  2103. bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
  2104. CaseRecVector& WorkList,
  2105. const Value* SV,
  2106. MachineBasicBlock* Default,
  2107. MachineBasicBlock* SwitchBB) {
  2108. const TargetLowering *TLI = TM.getTargetLowering();
  2109. EVT PTy = TLI->getPointerTy();
  2110. unsigned IntPtrBits = PTy.getSizeInBits();
  2111. Case& FrontCase = *CR.Range.first;
  2112. Case& BackCase = *(CR.Range.second-1);
  2113. // Get the MachineFunction which holds the current MBB. This is used when
  2114. // inserting any additional MBBs necessary to represent the switch.
  2115. MachineFunction *CurMF = FuncInfo.MF;
  2116. // If target does not have legal shift left, do not emit bit tests at all.
  2117. if (!TLI->isOperationLegal(ISD::SHL, PTy))
  2118. return false;
  2119. size_t numCmps = 0;
  2120. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  2121. I!=E; ++I) {
  2122. // Single case counts one, case range - two.
  2123. numCmps += (I->Low == I->High ? 1 : 2);
  2124. }
  2125. // Count unique destinations
  2126. SmallSet<MachineBasicBlock*, 4> Dests;
  2127. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  2128. Dests.insert(I->BB);
  2129. if (Dests.size() > 3)
  2130. // Don't bother the code below, if there are too much unique destinations
  2131. return false;
  2132. }
  2133. DEBUG(dbgs() << "Total number of unique destinations: "
  2134. << Dests.size() << '\n'
  2135. << "Total number of comparisons: " << numCmps << '\n');
  2136. // Compute span of values.
  2137. const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
  2138. const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
  2139. APInt cmpRange = maxValue - minValue;
  2140. DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
  2141. << "Low bound: " << minValue << '\n'
  2142. << "High bound: " << maxValue << '\n');
  2143. if (cmpRange.uge(IntPtrBits) ||
  2144. (!(Dests.size() == 1 && numCmps >= 3) &&
  2145. !(Dests.size() == 2 && numCmps >= 5) &&
  2146. !(Dests.size() >= 3 && numCmps >= 6)))
  2147. return false;
  2148. DEBUG(dbgs() << "Emitting bit tests\n");
  2149. APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
  2150. // Optimize the case where all the case values fit in a
  2151. // word without having to subtract minValue. In this case,
  2152. // we can optimize away the subtraction.
  2153. if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
  2154. cmpRange = maxValue;
  2155. } else {
  2156. lowBound = minValue;
  2157. }
  2158. CaseBitsVector CasesBits;
  2159. unsigned i, count = 0;
  2160. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  2161. MachineBasicBlock* Dest = I->BB;
  2162. for (i = 0; i < count; ++i)
  2163. if (Dest == CasesBits[i].BB)
  2164. break;
  2165. if (i == count) {
  2166. assert((count < 3) && "Too much destinations to test!");
  2167. CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
  2168. count++;
  2169. }
  2170. const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
  2171. const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
  2172. uint64_t lo = (lowValue - lowBound).getZExtValue();
  2173. uint64_t hi = (highValue - lowBound).getZExtValue();
  2174. CasesBits[i].ExtraWeight += I->ExtraWeight;
  2175. for (uint64_t j = lo; j <= hi; j++) {
  2176. CasesBits[i].Mask |= 1ULL << j;
  2177. CasesBits[i].Bits++;
  2178. }
  2179. }
  2180. std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
  2181. BitTestInfo BTC;
  2182. // Figure out which block is immediately after the current one.
  2183. MachineFunction::iterator BBI = CR.CaseBB;
  2184. ++BBI;
  2185. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  2186. DEBUG(dbgs() << "Cases:\n");
  2187. for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
  2188. DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
  2189. << ", Bits: " << CasesBits[i].Bits
  2190. << ", BB: " << CasesBits[i].BB << '\n');
  2191. MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  2192. CurMF->insert(BBI, CaseBB);
  2193. BTC.push_back(BitTestCase(CasesBits[i].Mask,
  2194. CaseBB,
  2195. CasesBits[i].BB, CasesBits[i].ExtraWeight));
  2196. // Put SV in a virtual register to make it available from the new blocks.
  2197. ExportFromCurrentBlock(SV);
  2198. }
  2199. BitTestBlock BTB(lowBound, cmpRange, SV,
  2200. -1U, MVT::Other, (CR.CaseBB == SwitchBB),
  2201. CR.CaseBB, Default, BTC);
  2202. if (CR.CaseBB == SwitchBB)
  2203. visitBitTestHeader(BTB, SwitchBB);
  2204. BitTestCases.push_back(BTB);
  2205. return true;
  2206. }
  2207. /// Clusterify - Transform simple list of Cases into list of CaseRange's
  2208. size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
  2209. const SwitchInst& SI) {
  2210. size_t numCmps = 0;
  2211. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2212. // Start with "simple" cases
  2213. for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
  2214. i != e; ++i) {
  2215. const BasicBlock *SuccBB = i.getCaseSuccessor();
  2216. MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
  2217. uint32_t ExtraWeight =
  2218. BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0;
  2219. Cases.push_back(Case(i.getCaseValue(), i.getCaseValue(),
  2220. SMBB, ExtraWeight));
  2221. }
  2222. std::sort(Cases.begin(), Cases.end(), CaseCmp());
  2223. // Merge case into clusters
  2224. if (Cases.size() >= 2)
  2225. // Must recompute end() each iteration because it may be
  2226. // invalidated by erase if we hold on to it
  2227. for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
  2228. J != Cases.end(); ) {
  2229. const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
  2230. const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
  2231. MachineBasicBlock* nextBB = J->BB;
  2232. MachineBasicBlock* currentBB = I->BB;
  2233. // If the two neighboring cases go to the same destination, merge them
  2234. // into a single case.
  2235. if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
  2236. I->High = J->High;
  2237. I->ExtraWeight += J->ExtraWeight;
  2238. J = Cases.erase(J);
  2239. } else {
  2240. I = J++;
  2241. }
  2242. }
  2243. for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
  2244. if (I->Low != I->High)
  2245. // A range counts double, since it requires two compares.
  2246. ++numCmps;
  2247. }
  2248. return numCmps;
  2249. }
  2250. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2251. MachineBasicBlock *Last) {
  2252. // Update JTCases.
  2253. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2254. if (JTCases[i].first.HeaderBB == First)
  2255. JTCases[i].first.HeaderBB = Last;
  2256. // Update BitTestCases.
  2257. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2258. if (BitTestCases[i].Parent == First)
  2259. BitTestCases[i].Parent = Last;
  2260. }
  2261. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  2262. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  2263. // Figure out which block is immediately after the current one.
  2264. MachineBasicBlock *NextBlock = 0;
  2265. MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
  2266. // If there is only the default destination, branch to it if it is not the
  2267. // next basic block. Otherwise, just fall through.
  2268. if (!SI.getNumCases()) {
  2269. // Update machine-CFG edges.
  2270. // If this is not a fall-through branch, emit the branch.
  2271. SwitchMBB->addSuccessor(Default);
  2272. if (Default != NextBlock)
  2273. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2274. MVT::Other, getControlRoot(),
  2275. DAG.getBasicBlock(Default)));
  2276. return;
  2277. }
  2278. // If there are any non-default case statements, create a vector of Cases
  2279. // representing each one, and sort the vector so that we can efficiently
  2280. // create a binary search tree from them.
  2281. CaseVector Cases;
  2282. size_t numCmps = Clusterify(Cases, SI);
  2283. DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
  2284. << ". Total compares: " << numCmps << '\n');
  2285. (void)numCmps;
  2286. // Get the Value to be switched on and default basic blocks, which will be
  2287. // inserted into CaseBlock records, representing basic blocks in the binary
  2288. // search tree.
  2289. const Value *SV = SI.getCondition();
  2290. // Push the initial CaseRec onto the worklist
  2291. CaseRecVector WorkList;
  2292. WorkList.push_back(CaseRec(SwitchMBB,0,0,
  2293. CaseRange(Cases.begin(),Cases.end())));
  2294. while (!WorkList.empty()) {
  2295. // Grab a record representing a case range to process off the worklist
  2296. CaseRec CR = WorkList.back();
  2297. WorkList.pop_back();
  2298. if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
  2299. continue;
  2300. // If the range has few cases (two or less) emit a series of specific
  2301. // tests.
  2302. if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
  2303. continue;
  2304. // If the switch has more than N blocks, and is at least 40% dense, and the
  2305. // target supports indirect branches, then emit a jump table rather than
  2306. // lowering the switch to a binary tree of conditional branches.
  2307. // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
  2308. if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
  2309. continue;
  2310. // Emit binary tree. We need to pick a pivot, and push left and right ranges
  2311. // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
  2312. handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
  2313. }
  2314. }
  2315. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2316. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2317. // Update machine-CFG edges with unique successors.
  2318. SmallSet<BasicBlock*, 32> Done;
  2319. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2320. BasicBlock *BB = I.getSuccessor(i);
  2321. bool Inserted = Done.insert(BB);
  2322. if (!Inserted)
  2323. continue;
  2324. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2325. addSuccessorWithWeight(IndirectBrMBB, Succ);
  2326. }
  2327. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2328. MVT::Other, getControlRoot(),
  2329. getValue(I.getAddress())));
  2330. }
  2331. void SelectionDAGBuilder::visitFSub(const User &I) {
  2332. // -0.0 - X --> fneg
  2333. Type *Ty = I.getType();
  2334. if (isa<Constant>(I.getOperand(0)) &&
  2335. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2336. SDValue Op2 = getValue(I.getOperand(1));
  2337. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2338. Op2.getValueType(), Op2));
  2339. return;
  2340. }
  2341. visitBinary(I, ISD::FSUB);
  2342. }
  2343. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  2344. SDValue Op1 = getValue(I.getOperand(0));
  2345. SDValue Op2 = getValue(I.getOperand(1));
  2346. setValue(&I, DAG.getNode(OpCode, getCurSDLoc(),
  2347. Op1.getValueType(), Op1, Op2));
  2348. }
  2349. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2350. SDValue Op1 = getValue(I.getOperand(0));
  2351. SDValue Op2 = getValue(I.getOperand(1));
  2352. EVT ShiftTy = TM.getTargetLowering()->getShiftAmountTy(Op2.getValueType());
  2353. // Coerce the shift amount to the right type if we can.
  2354. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2355. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2356. unsigned Op2Size = Op2.getValueType().getSizeInBits();
  2357. SDLoc DL = getCurSDLoc();
  2358. // If the operand is smaller than the shift count type, promote it.
  2359. if (ShiftSize > Op2Size)
  2360. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2361. // If the operand is larger than the shift count type but the shift
  2362. // count type has enough bits to represent any shift value, truncate
  2363. // it now. This is a common case and it exposes the truncate to
  2364. // optimization early.
  2365. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
  2366. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2367. // Otherwise we'll need to temporarily settle for some other convenient
  2368. // type. Type legalization will make adjustments once the shiftee is split.
  2369. else
  2370. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2371. }
  2372. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(),
  2373. Op1.getValueType(), Op1, Op2));
  2374. }
  2375. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2376. SDValue Op1 = getValue(I.getOperand(0));
  2377. SDValue Op2 = getValue(I.getOperand(1));
  2378. // Turn exact SDivs into multiplications.
  2379. // FIXME: This should be in DAGCombiner, but it doesn't have access to the
  2380. // exact bit.
  2381. if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
  2382. !isa<ConstantSDNode>(Op1) &&
  2383. isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
  2384. setValue(&I, TM.getTargetLowering()->BuildExactSDIV(Op1, Op2,
  2385. getCurSDLoc(), DAG));
  2386. else
  2387. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(),
  2388. Op1, Op2));
  2389. }
  2390. void SelectionDAGBuilder::visitICmp(const User &I) {
  2391. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2392. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2393. predicate = IC->getPredicate();
  2394. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2395. predicate = ICmpInst::Predicate(IC->getPredicate());
  2396. SDValue Op1 = getValue(I.getOperand(0));
  2397. SDValue Op2 = getValue(I.getOperand(1));
  2398. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2399. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2400. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2401. }
  2402. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2403. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2404. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2405. predicate = FC->getPredicate();
  2406. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2407. predicate = FCmpInst::Predicate(FC->getPredicate());
  2408. SDValue Op1 = getValue(I.getOperand(0));
  2409. SDValue Op2 = getValue(I.getOperand(1));
  2410. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2411. if (TM.Options.NoNaNsFPMath)
  2412. Condition = getFCmpCodeWithoutNaN(Condition);
  2413. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2414. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2415. }
  2416. void SelectionDAGBuilder::visitSelect(const User &I) {
  2417. SmallVector<EVT, 4> ValueVTs;
  2418. ComputeValueVTs(*TM.getTargetLowering(), I.getType(), ValueVTs);
  2419. unsigned NumValues = ValueVTs.size();
  2420. if (NumValues == 0) return;
  2421. SmallVector<SDValue, 4> Values(NumValues);
  2422. SDValue Cond = getValue(I.getOperand(0));
  2423. SDValue TrueVal = getValue(I.getOperand(1));
  2424. SDValue FalseVal = getValue(I.getOperand(2));
  2425. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2426. ISD::VSELECT : ISD::SELECT;
  2427. for (unsigned i = 0; i != NumValues; ++i)
  2428. Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
  2429. TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
  2430. Cond,
  2431. SDValue(TrueVal.getNode(),
  2432. TrueVal.getResNo() + i),
  2433. SDValue(FalseVal.getNode(),
  2434. FalseVal.getResNo() + i));
  2435. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2436. DAG.getVTList(&ValueVTs[0], NumValues),
  2437. &Values[0], NumValues));
  2438. }
  2439. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2440. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2441. SDValue N = getValue(I.getOperand(0));
  2442. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2443. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2444. }
  2445. void SelectionDAGBuilder::visitZExt(const User &I) {
  2446. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2447. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2448. SDValue N = getValue(I.getOperand(0));
  2449. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2450. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2451. }
  2452. void SelectionDAGBuilder::visitSExt(const User &I) {
  2453. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2454. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2455. SDValue N = getValue(I.getOperand(0));
  2456. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2457. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2458. }
  2459. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2460. // FPTrunc is never a no-op cast, no need to check
  2461. SDValue N = getValue(I.getOperand(0));
  2462. const TargetLowering *TLI = TM.getTargetLowering();
  2463. EVT DestVT = TLI->getValueType(I.getType());
  2464. setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurSDLoc(),
  2465. DestVT, N,
  2466. DAG.getTargetConstant(0, TLI->getPointerTy())));
  2467. }
  2468. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2469. // FPExt is never a no-op cast, no need to check
  2470. SDValue N = getValue(I.getOperand(0));
  2471. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2472. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2473. }
  2474. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2475. // FPToUI is never a no-op cast, no need to check
  2476. SDValue N = getValue(I.getOperand(0));
  2477. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2478. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2479. }
  2480. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2481. // FPToSI is never a no-op cast, no need to check
  2482. SDValue N = getValue(I.getOperand(0));
  2483. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2484. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2485. }
  2486. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2487. // UIToFP is never a no-op cast, no need to check
  2488. SDValue N = getValue(I.getOperand(0));
  2489. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2490. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2491. }
  2492. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2493. // SIToFP is never a no-op cast, no need to check
  2494. SDValue N = getValue(I.getOperand(0));
  2495. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2496. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2497. }
  2498. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2499. // What to do depends on the size of the integer and the size of the pointer.
  2500. // We can either truncate, zero extend, or no-op, accordingly.
  2501. SDValue N = getValue(I.getOperand(0));
  2502. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2503. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2504. }
  2505. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2506. // What to do depends on the size of the integer and the size of the pointer.
  2507. // We can either truncate, zero extend, or no-op, accordingly.
  2508. SDValue N = getValue(I.getOperand(0));
  2509. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2510. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  2511. }
  2512. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2513. SDValue N = getValue(I.getOperand(0));
  2514. EVT DestVT = TM.getTargetLowering()->getValueType(I.getType());
  2515. // BitCast assures us that source and destination are the same size so this is
  2516. // either a BITCAST or a no-op.
  2517. if (DestVT != N.getValueType())
  2518. setValue(&I, DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  2519. DestVT, N)); // convert types.
  2520. else
  2521. setValue(&I, N); // noop cast.
  2522. }
  2523. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2524. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2525. SDValue InVec = getValue(I.getOperand(0));
  2526. SDValue InVal = getValue(I.getOperand(1));
  2527. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)),
  2528. getCurSDLoc(), TLI.getVectorIdxTy());
  2529. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  2530. TM.getTargetLowering()->getValueType(I.getType()),
  2531. InVec, InVal, InIdx));
  2532. }
  2533. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2534. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2535. SDValue InVec = getValue(I.getOperand(0));
  2536. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)),
  2537. getCurSDLoc(), TLI.getVectorIdxTy());
  2538. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2539. TM.getTargetLowering()->getValueType(I.getType()),
  2540. InVec, InIdx));
  2541. }
  2542. // Utility for visitShuffleVector - Return true if every element in Mask,
  2543. // beginning from position Pos and ending in Pos+Size, falls within the
  2544. // specified sequential range [L, L+Pos). or is undef.
  2545. static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
  2546. unsigned Pos, unsigned Size, int Low) {
  2547. for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
  2548. if (Mask[i] >= 0 && Mask[i] != Low)
  2549. return false;
  2550. return true;
  2551. }
  2552. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2553. SDValue Src1 = getValue(I.getOperand(0));
  2554. SDValue Src2 = getValue(I.getOperand(1));
  2555. SmallVector<int, 8> Mask;
  2556. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  2557. unsigned MaskNumElts = Mask.size();
  2558. const TargetLowering *TLI = TM.getTargetLowering();
  2559. EVT VT = TLI->getValueType(I.getType());
  2560. EVT SrcVT = Src1.getValueType();
  2561. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2562. if (SrcNumElts == MaskNumElts) {
  2563. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2564. &Mask[0]));
  2565. return;
  2566. }
  2567. // Normalize the shuffle vector since mask and vector length don't match.
  2568. if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
  2569. // Mask is longer than the source vectors and is a multiple of the source
  2570. // vectors. We can use concatenate vector to make the mask and vectors
  2571. // lengths match.
  2572. if (SrcNumElts*2 == MaskNumElts) {
  2573. // First check for Src1 in low and Src2 in high
  2574. if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
  2575. isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
  2576. // The shuffle is concatenating two vectors together.
  2577. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
  2578. VT, Src1, Src2));
  2579. return;
  2580. }
  2581. // Then check for Src2 in low and Src1 in high
  2582. if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
  2583. isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
  2584. // The shuffle is concatenating two vectors together.
  2585. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurSDLoc(),
  2586. VT, Src2, Src1));
  2587. return;
  2588. }
  2589. }
  2590. // Pad both vectors with undefs to make them the same length as the mask.
  2591. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2592. bool Src1U = Src1.getOpcode() == ISD::UNDEF;
  2593. bool Src2U = Src2.getOpcode() == ISD::UNDEF;
  2594. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2595. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2596. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2597. MOps1[0] = Src1;
  2598. MOps2[0] = Src2;
  2599. Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2600. getCurSDLoc(), VT,
  2601. &MOps1[0], NumConcat);
  2602. Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2603. getCurSDLoc(), VT,
  2604. &MOps2[0], NumConcat);
  2605. // Readjust mask for new input vector length.
  2606. SmallVector<int, 8> MappedOps;
  2607. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2608. int Idx = Mask[i];
  2609. if (Idx >= (int)SrcNumElts)
  2610. Idx -= SrcNumElts - MaskNumElts;
  2611. MappedOps.push_back(Idx);
  2612. }
  2613. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2614. &MappedOps[0]));
  2615. return;
  2616. }
  2617. if (SrcNumElts > MaskNumElts) {
  2618. // Analyze the access pattern of the vector to see if we can extract
  2619. // two subvectors and do the shuffle. The analysis is done by calculating
  2620. // the range of elements the mask access on both vectors.
  2621. int MinRange[2] = { static_cast<int>(SrcNumElts),
  2622. static_cast<int>(SrcNumElts)};
  2623. int MaxRange[2] = {-1, -1};
  2624. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2625. int Idx = Mask[i];
  2626. unsigned Input = 0;
  2627. if (Idx < 0)
  2628. continue;
  2629. if (Idx >= (int)SrcNumElts) {
  2630. Input = 1;
  2631. Idx -= SrcNumElts;
  2632. }
  2633. if (Idx > MaxRange[Input])
  2634. MaxRange[Input] = Idx;
  2635. if (Idx < MinRange[Input])
  2636. MinRange[Input] = Idx;
  2637. }
  2638. // Check if the access is smaller than the vector size and can we find
  2639. // a reasonable extract index.
  2640. int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
  2641. // Extract.
  2642. int StartIdx[2]; // StartIdx to extract from
  2643. for (unsigned Input = 0; Input < 2; ++Input) {
  2644. if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
  2645. RangeUse[Input] = 0; // Unused
  2646. StartIdx[Input] = 0;
  2647. continue;
  2648. }
  2649. // Find a good start index that is a multiple of the mask length. Then
  2650. // see if the rest of the elements are in range.
  2651. StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
  2652. if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
  2653. StartIdx[Input] + MaskNumElts <= SrcNumElts)
  2654. RangeUse[Input] = 1; // Extract from a multiple of the mask length.
  2655. }
  2656. if (RangeUse[0] == 0 && RangeUse[1] == 0) {
  2657. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2658. return;
  2659. }
  2660. if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
  2661. // Extract appropriate subvector and generate a vector shuffle
  2662. for (unsigned Input = 0; Input < 2; ++Input) {
  2663. SDValue &Src = Input == 0 ? Src1 : Src2;
  2664. if (RangeUse[Input] == 0)
  2665. Src = DAG.getUNDEF(VT);
  2666. else
  2667. Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurSDLoc(), VT,
  2668. Src, DAG.getConstant(StartIdx[Input],
  2669. TLI->getVectorIdxTy()));
  2670. }
  2671. // Calculate new mask.
  2672. SmallVector<int, 8> MappedOps;
  2673. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2674. int Idx = Mask[i];
  2675. if (Idx >= 0) {
  2676. if (Idx < (int)SrcNumElts)
  2677. Idx -= StartIdx[0];
  2678. else
  2679. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  2680. }
  2681. MappedOps.push_back(Idx);
  2682. }
  2683. setValue(&I, DAG.getVectorShuffle(VT, getCurSDLoc(), Src1, Src2,
  2684. &MappedOps[0]));
  2685. return;
  2686. }
  2687. }
  2688. // We can't use either concat vectors or extract subvectors so fall back to
  2689. // replacing the shuffle with extract and build vector.
  2690. // to insert and build vector.
  2691. EVT EltVT = VT.getVectorElementType();
  2692. EVT IdxVT = TLI->getVectorIdxTy();
  2693. SmallVector<SDValue,8> Ops;
  2694. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2695. int Idx = Mask[i];
  2696. SDValue Res;
  2697. if (Idx < 0) {
  2698. Res = DAG.getUNDEF(EltVT);
  2699. } else {
  2700. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  2701. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  2702. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  2703. EltVT, Src, DAG.getConstant(Idx, IdxVT));
  2704. }
  2705. Ops.push_back(Res);
  2706. }
  2707. setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurSDLoc(),
  2708. VT, &Ops[0], Ops.size()));
  2709. }
  2710. void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
  2711. const Value *Op0 = I.getOperand(0);
  2712. const Value *Op1 = I.getOperand(1);
  2713. Type *AggTy = I.getType();
  2714. Type *ValTy = Op1->getType();
  2715. bool IntoUndef = isa<UndefValue>(Op0);
  2716. bool FromUndef = isa<UndefValue>(Op1);
  2717. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2718. const TargetLowering *TLI = TM.getTargetLowering();
  2719. SmallVector<EVT, 4> AggValueVTs;
  2720. ComputeValueVTs(*TLI, AggTy, AggValueVTs);
  2721. SmallVector<EVT, 4> ValValueVTs;
  2722. ComputeValueVTs(*TLI, ValTy, ValValueVTs);
  2723. unsigned NumAggValues = AggValueVTs.size();
  2724. unsigned NumValValues = ValValueVTs.size();
  2725. SmallVector<SDValue, 4> Values(NumAggValues);
  2726. SDValue Agg = getValue(Op0);
  2727. unsigned i = 0;
  2728. // Copy the beginning value(s) from the original aggregate.
  2729. for (; i != LinearIndex; ++i)
  2730. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2731. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2732. // Copy values from the inserted value(s).
  2733. if (NumValValues) {
  2734. SDValue Val = getValue(Op1);
  2735. for (; i != LinearIndex + NumValValues; ++i)
  2736. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2737. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2738. }
  2739. // Copy remaining value(s) from the original aggregate.
  2740. for (; i != NumAggValues; ++i)
  2741. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2742. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2743. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2744. DAG.getVTList(&AggValueVTs[0], NumAggValues),
  2745. &Values[0], NumAggValues));
  2746. }
  2747. void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
  2748. const Value *Op0 = I.getOperand(0);
  2749. Type *AggTy = Op0->getType();
  2750. Type *ValTy = I.getType();
  2751. bool OutOfUndef = isa<UndefValue>(Op0);
  2752. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
  2753. const TargetLowering *TLI = TM.getTargetLowering();
  2754. SmallVector<EVT, 4> ValValueVTs;
  2755. ComputeValueVTs(*TLI, ValTy, ValValueVTs);
  2756. unsigned NumValValues = ValValueVTs.size();
  2757. // Ignore a extractvalue that produces an empty object
  2758. if (!NumValValues) {
  2759. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  2760. return;
  2761. }
  2762. SmallVector<SDValue, 4> Values(NumValValues);
  2763. SDValue Agg = getValue(Op0);
  2764. // Copy out the selected value(s).
  2765. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2766. Values[i - LinearIndex] =
  2767. OutOfUndef ?
  2768. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2769. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2770. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2771. DAG.getVTList(&ValValueVTs[0], NumValValues),
  2772. &Values[0], NumValValues));
  2773. }
  2774. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  2775. Value *Op0 = I.getOperand(0);
  2776. // Note that the pointer operand may be a vector of pointers. Take the scalar
  2777. // element which holds a pointer.
  2778. Type *Ty = Op0->getType()->getScalarType();
  2779. unsigned AS = Ty->getPointerAddressSpace();
  2780. SDValue N = getValue(Op0);
  2781. for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
  2782. OI != E; ++OI) {
  2783. const Value *Idx = *OI;
  2784. if (StructType *StTy = dyn_cast<StructType>(Ty)) {
  2785. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  2786. if (Field) {
  2787. // N = N + Offset
  2788. uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
  2789. N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
  2790. DAG.getConstant(Offset, N.getValueType()));
  2791. }
  2792. Ty = StTy->getElementType(Field);
  2793. } else {
  2794. Ty = cast<SequentialType>(Ty)->getElementType();
  2795. // If this is a constant subscript, handle it quickly.
  2796. const TargetLowering *TLI = TM.getTargetLowering();
  2797. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
  2798. if (CI->isZero()) continue;
  2799. uint64_t Offs =
  2800. TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
  2801. SDValue OffsVal;
  2802. EVT PTy = TLI->getPointerTy(AS);
  2803. unsigned PtrBits = PTy.getSizeInBits();
  2804. if (PtrBits < 64)
  2805. OffsVal = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), PTy,
  2806. DAG.getConstant(Offs, MVT::i64));
  2807. else
  2808. OffsVal = DAG.getConstant(Offs, PTy);
  2809. N = DAG.getNode(ISD::ADD, getCurSDLoc(), N.getValueType(), N,
  2810. OffsVal);
  2811. continue;
  2812. }
  2813. // N = N + Idx * ElementSize;
  2814. APInt ElementSize = APInt(TLI->getPointerSizeInBits(AS),
  2815. TD->getTypeAllocSize(Ty));
  2816. SDValue IdxN = getValue(Idx);
  2817. // If the index is smaller or larger than intptr_t, truncate or extend
  2818. // it.
  2819. IdxN = DAG.getSExtOrTrunc(IdxN, getCurSDLoc(), N.getValueType());
  2820. // If this is a multiply by a power of two, turn it into a shl
  2821. // immediately. This is a very common case.
  2822. if (ElementSize != 1) {
  2823. if (ElementSize.isPowerOf2()) {
  2824. unsigned Amt = ElementSize.logBase2();
  2825. IdxN = DAG.getNode(ISD::SHL, getCurSDLoc(),
  2826. N.getValueType(), IdxN,
  2827. DAG.getConstant(Amt, IdxN.getValueType()));
  2828. } else {
  2829. SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
  2830. IdxN = DAG.getNode(ISD::MUL, getCurSDLoc(),
  2831. N.getValueType(), IdxN, Scale);
  2832. }
  2833. }
  2834. N = DAG.getNode(ISD::ADD, getCurSDLoc(),
  2835. N.getValueType(), N, IdxN);
  2836. }
  2837. }
  2838. setValue(&I, N);
  2839. }
  2840. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  2841. // If this is a fixed sized alloca in the entry block of the function,
  2842. // allocate it statically on the stack.
  2843. if (FuncInfo.StaticAllocaMap.count(&I))
  2844. return; // getValue will auto-populate this.
  2845. Type *Ty = I.getAllocatedType();
  2846. const TargetLowering *TLI = TM.getTargetLowering();
  2847. uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
  2848. unsigned Align =
  2849. std::max((unsigned)TLI->getDataLayout()->getPrefTypeAlignment(Ty),
  2850. I.getAlignment());
  2851. SDValue AllocSize = getValue(I.getArraySize());
  2852. EVT IntPtr = TLI->getPointerTy();
  2853. if (AllocSize.getValueType() != IntPtr)
  2854. AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurSDLoc(), IntPtr);
  2855. AllocSize = DAG.getNode(ISD::MUL, getCurSDLoc(), IntPtr,
  2856. AllocSize,
  2857. DAG.getConstant(TySize, IntPtr));
  2858. // Handle alignment. If the requested alignment is less than or equal to
  2859. // the stack alignment, ignore it. If the size is greater than or equal to
  2860. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2861. unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
  2862. if (Align <= StackAlign)
  2863. Align = 0;
  2864. // Round the size of the allocation up to the stack alignment size
  2865. // by add SA-1 to the size.
  2866. AllocSize = DAG.getNode(ISD::ADD, getCurSDLoc(),
  2867. AllocSize.getValueType(), AllocSize,
  2868. DAG.getIntPtrConstant(StackAlign-1));
  2869. // Mask out the low bits for alignment purposes.
  2870. AllocSize = DAG.getNode(ISD::AND, getCurSDLoc(),
  2871. AllocSize.getValueType(), AllocSize,
  2872. DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
  2873. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
  2874. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  2875. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurSDLoc(),
  2876. VTs, Ops, 3);
  2877. setValue(&I, DSA);
  2878. DAG.setRoot(DSA.getValue(1));
  2879. // Inform the Frame Information that we have just allocated a variable-sized
  2880. // object.
  2881. FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
  2882. }
  2883. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  2884. if (I.isAtomic())
  2885. return visitAtomicLoad(I);
  2886. const Value *SV = I.getOperand(0);
  2887. SDValue Ptr = getValue(SV);
  2888. Type *Ty = I.getType();
  2889. bool isVolatile = I.isVolatile();
  2890. bool isNonTemporal = I.getMetadata("nontemporal") != 0;
  2891. bool isInvariant = I.getMetadata("invariant.load") != 0;
  2892. unsigned Alignment = I.getAlignment();
  2893. const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
  2894. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  2895. SmallVector<EVT, 4> ValueVTs;
  2896. SmallVector<uint64_t, 4> Offsets;
  2897. ComputeValueVTs(*TM.getTargetLowering(), Ty, ValueVTs, &Offsets);
  2898. unsigned NumValues = ValueVTs.size();
  2899. if (NumValues == 0)
  2900. return;
  2901. SDValue Root;
  2902. bool ConstantMemory = false;
  2903. if (I.isVolatile() || NumValues > MaxParallelChains)
  2904. // Serialize volatile loads with other side effects.
  2905. Root = getRoot();
  2906. else if (AA->pointsToConstantMemory(
  2907. AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
  2908. // Do not serialize (non-volatile) loads of constant memory with anything.
  2909. Root = DAG.getEntryNode();
  2910. ConstantMemory = true;
  2911. } else {
  2912. // Do not serialize non-volatile loads against each other.
  2913. Root = DAG.getRoot();
  2914. }
  2915. SmallVector<SDValue, 4> Values(NumValues);
  2916. SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
  2917. NumValues));
  2918. EVT PtrVT = Ptr.getValueType();
  2919. unsigned ChainI = 0;
  2920. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  2921. // Serializing loads here may result in excessive register pressure, and
  2922. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  2923. // could recover a bit by hoisting nodes upward in the chain by recognizing
  2924. // they are side-effect free or do not alias. The optimizer should really
  2925. // avoid this case by converting large object/array copies to llvm.memcpy
  2926. // (MaxParallelChains should always remain as failsafe).
  2927. if (ChainI == MaxParallelChains) {
  2928. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  2929. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  2930. MVT::Other, &Chains[0], ChainI);
  2931. Root = Chain;
  2932. ChainI = 0;
  2933. }
  2934. SDValue A = DAG.getNode(ISD::ADD, getCurSDLoc(),
  2935. PtrVT, Ptr,
  2936. DAG.getConstant(Offsets[i], PtrVT));
  2937. SDValue L = DAG.getLoad(ValueVTs[i], getCurSDLoc(), Root,
  2938. A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
  2939. isNonTemporal, isInvariant, Alignment, TBAAInfo,
  2940. Ranges);
  2941. Values[i] = L;
  2942. Chains[ChainI] = L.getValue(1);
  2943. }
  2944. if (!ConstantMemory) {
  2945. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  2946. MVT::Other, &Chains[0], ChainI);
  2947. if (isVolatile)
  2948. DAG.setRoot(Chain);
  2949. else
  2950. PendingLoads.push_back(Chain);
  2951. }
  2952. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2953. DAG.getVTList(&ValueVTs[0], NumValues),
  2954. &Values[0], NumValues));
  2955. }
  2956. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  2957. if (I.isAtomic())
  2958. return visitAtomicStore(I);
  2959. const Value *SrcV = I.getOperand(0);
  2960. const Value *PtrV = I.getOperand(1);
  2961. SmallVector<EVT, 4> ValueVTs;
  2962. SmallVector<uint64_t, 4> Offsets;
  2963. ComputeValueVTs(*TM.getTargetLowering(), SrcV->getType(), ValueVTs, &Offsets);
  2964. unsigned NumValues = ValueVTs.size();
  2965. if (NumValues == 0)
  2966. return;
  2967. // Get the lowered operands. Note that we do this after
  2968. // checking if NumResults is zero, because with zero results
  2969. // the operands won't have values in the map.
  2970. SDValue Src = getValue(SrcV);
  2971. SDValue Ptr = getValue(PtrV);
  2972. SDValue Root = getRoot();
  2973. SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
  2974. NumValues));
  2975. EVT PtrVT = Ptr.getValueType();
  2976. bool isVolatile = I.isVolatile();
  2977. bool isNonTemporal = I.getMetadata("nontemporal") != 0;
  2978. unsigned Alignment = I.getAlignment();
  2979. const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
  2980. unsigned ChainI = 0;
  2981. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  2982. // See visitLoad comments.
  2983. if (ChainI == MaxParallelChains) {
  2984. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  2985. MVT::Other, &Chains[0], ChainI);
  2986. Root = Chain;
  2987. ChainI = 0;
  2988. }
  2989. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT, Ptr,
  2990. DAG.getConstant(Offsets[i], PtrVT));
  2991. SDValue St = DAG.getStore(Root, getCurSDLoc(),
  2992. SDValue(Src.getNode(), Src.getResNo() + i),
  2993. Add, MachinePointerInfo(PtrV, Offsets[i]),
  2994. isVolatile, isNonTemporal, Alignment, TBAAInfo);
  2995. Chains[ChainI] = St;
  2996. }
  2997. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  2998. MVT::Other, &Chains[0], ChainI);
  2999. DAG.setRoot(StoreNode);
  3000. }
  3001. static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
  3002. SynchronizationScope Scope,
  3003. bool Before, SDLoc dl,
  3004. SelectionDAG &DAG,
  3005. const TargetLowering &TLI) {
  3006. // Fence, if necessary
  3007. if (Before) {
  3008. if (Order == AcquireRelease || Order == SequentiallyConsistent)
  3009. Order = Release;
  3010. else if (Order == Acquire || Order == Monotonic)
  3011. return Chain;
  3012. } else {
  3013. if (Order == AcquireRelease)
  3014. Order = Acquire;
  3015. else if (Order == Release || Order == Monotonic)
  3016. return Chain;
  3017. }
  3018. SDValue Ops[3];
  3019. Ops[0] = Chain;
  3020. Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
  3021. Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
  3022. return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
  3023. }
  3024. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3025. SDLoc dl = getCurSDLoc();
  3026. AtomicOrdering Order = I.getOrdering();
  3027. SynchronizationScope Scope = I.getSynchScope();
  3028. SDValue InChain = getRoot();
  3029. const TargetLowering *TLI = TM.getTargetLowering();
  3030. if (TLI->getInsertFencesForAtomic())
  3031. InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
  3032. DAG, *TLI);
  3033. SDValue L =
  3034. DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
  3035. getValue(I.getCompareOperand()).getSimpleValueType(),
  3036. InChain,
  3037. getValue(I.getPointerOperand()),
  3038. getValue(I.getCompareOperand()),
  3039. getValue(I.getNewValOperand()),
  3040. MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
  3041. TLI->getInsertFencesForAtomic() ? Monotonic : Order,
  3042. Scope);
  3043. SDValue OutChain = L.getValue(1);
  3044. if (TLI->getInsertFencesForAtomic())
  3045. OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
  3046. DAG, *TLI);
  3047. setValue(&I, L);
  3048. DAG.setRoot(OutChain);
  3049. }
  3050. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3051. SDLoc dl = getCurSDLoc();
  3052. ISD::NodeType NT;
  3053. switch (I.getOperation()) {
  3054. default: llvm_unreachable("Unknown atomicrmw operation");
  3055. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3056. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3057. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3058. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3059. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3060. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3061. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3062. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3063. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3064. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3065. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3066. }
  3067. AtomicOrdering Order = I.getOrdering();
  3068. SynchronizationScope Scope = I.getSynchScope();
  3069. SDValue InChain = getRoot();
  3070. const TargetLowering *TLI = TM.getTargetLowering();
  3071. if (TLI->getInsertFencesForAtomic())
  3072. InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
  3073. DAG, *TLI);
  3074. SDValue L =
  3075. DAG.getAtomic(NT, dl,
  3076. getValue(I.getValOperand()).getSimpleValueType(),
  3077. InChain,
  3078. getValue(I.getPointerOperand()),
  3079. getValue(I.getValOperand()),
  3080. I.getPointerOperand(), 0 /* Alignment */,
  3081. TLI->getInsertFencesForAtomic() ? Monotonic : Order,
  3082. Scope);
  3083. SDValue OutChain = L.getValue(1);
  3084. if (TLI->getInsertFencesForAtomic())
  3085. OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
  3086. DAG, *TLI);
  3087. setValue(&I, L);
  3088. DAG.setRoot(OutChain);
  3089. }
  3090. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3091. SDLoc dl = getCurSDLoc();
  3092. const TargetLowering *TLI = TM.getTargetLowering();
  3093. SDValue Ops[3];
  3094. Ops[0] = getRoot();
  3095. Ops[1] = DAG.getConstant(I.getOrdering(), TLI->getPointerTy());
  3096. Ops[2] = DAG.getConstant(I.getSynchScope(), TLI->getPointerTy());
  3097. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
  3098. }
  3099. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3100. SDLoc dl = getCurSDLoc();
  3101. AtomicOrdering Order = I.getOrdering();
  3102. SynchronizationScope Scope = I.getSynchScope();
  3103. SDValue InChain = getRoot();
  3104. const TargetLowering *TLI = TM.getTargetLowering();
  3105. EVT VT = TLI->getValueType(I.getType());
  3106. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3107. report_fatal_error("Cannot generate unaligned atomic load");
  3108. SDValue L =
  3109. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  3110. getValue(I.getPointerOperand()),
  3111. I.getPointerOperand(), I.getAlignment(),
  3112. TLI->getInsertFencesForAtomic() ? Monotonic : Order,
  3113. Scope);
  3114. SDValue OutChain = L.getValue(1);
  3115. if (TLI->getInsertFencesForAtomic())
  3116. OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
  3117. DAG, *TLI);
  3118. setValue(&I, L);
  3119. DAG.setRoot(OutChain);
  3120. }
  3121. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  3122. SDLoc dl = getCurSDLoc();
  3123. AtomicOrdering Order = I.getOrdering();
  3124. SynchronizationScope Scope = I.getSynchScope();
  3125. SDValue InChain = getRoot();
  3126. const TargetLowering *TLI = TM.getTargetLowering();
  3127. EVT VT = TLI->getValueType(I.getValueOperand()->getType());
  3128. if (I.getAlignment() < VT.getSizeInBits() / 8)
  3129. report_fatal_error("Cannot generate unaligned atomic store");
  3130. if (TLI->getInsertFencesForAtomic())
  3131. InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
  3132. DAG, *TLI);
  3133. SDValue OutChain =
  3134. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
  3135. InChain,
  3136. getValue(I.getPointerOperand()),
  3137. getValue(I.getValueOperand()),
  3138. I.getPointerOperand(), I.getAlignment(),
  3139. TLI->getInsertFencesForAtomic() ? Monotonic : Order,
  3140. Scope);
  3141. if (TLI->getInsertFencesForAtomic())
  3142. OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
  3143. DAG, *TLI);
  3144. DAG.setRoot(OutChain);
  3145. }
  3146. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  3147. /// node.
  3148. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  3149. unsigned Intrinsic) {
  3150. bool HasChain = !I.doesNotAccessMemory();
  3151. bool OnlyLoad = HasChain && I.onlyReadsMemory();
  3152. // Build the operand list.
  3153. SmallVector<SDValue, 8> Ops;
  3154. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  3155. if (OnlyLoad) {
  3156. // We don't need to serialize loads against other loads.
  3157. Ops.push_back(DAG.getRoot());
  3158. } else {
  3159. Ops.push_back(getRoot());
  3160. }
  3161. }
  3162. // Info is set by getTgtMemInstrinsic
  3163. TargetLowering::IntrinsicInfo Info;
  3164. const TargetLowering *TLI = TM.getTargetLowering();
  3165. bool IsTgtIntrinsic = TLI->getTgtMemIntrinsic(Info, I, Intrinsic);
  3166. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  3167. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  3168. Info.opc == ISD::INTRINSIC_W_CHAIN)
  3169. Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI->getPointerTy()));
  3170. // Add all operands of the call to the operand list.
  3171. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  3172. SDValue Op = getValue(I.getArgOperand(i));
  3173. Ops.push_back(Op);
  3174. }
  3175. SmallVector<EVT, 4> ValueVTs;
  3176. ComputeValueVTs(*TLI, I.getType(), ValueVTs);
  3177. if (HasChain)
  3178. ValueVTs.push_back(MVT::Other);
  3179. SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
  3180. // Create the node.
  3181. SDValue Result;
  3182. if (IsTgtIntrinsic) {
  3183. // This is target intrinsic that touches memory
  3184. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(),
  3185. VTs, &Ops[0], Ops.size(),
  3186. Info.memVT,
  3187. MachinePointerInfo(Info.ptrVal, Info.offset),
  3188. Info.align, Info.vol,
  3189. Info.readMem, Info.writeMem);
  3190. } else if (!HasChain) {
  3191. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(),
  3192. VTs, &Ops[0], Ops.size());
  3193. } else if (!I.getType()->isVoidTy()) {
  3194. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(),
  3195. VTs, &Ops[0], Ops.size());
  3196. } else {
  3197. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(),
  3198. VTs, &Ops[0], Ops.size());
  3199. }
  3200. if (HasChain) {
  3201. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  3202. if (OnlyLoad)
  3203. PendingLoads.push_back(Chain);
  3204. else
  3205. DAG.setRoot(Chain);
  3206. }
  3207. if (!I.getType()->isVoidTy()) {
  3208. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  3209. EVT VT = TLI->getValueType(PTy);
  3210. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  3211. }
  3212. setValue(&I, Result);
  3213. }
  3214. }
  3215. /// GetSignificand - Get the significand and build it into a floating-point
  3216. /// number with exponent of 1:
  3217. ///
  3218. /// Op = (Op & 0x007fffff) | 0x3f800000;
  3219. ///
  3220. /// where Op is the hexadecimal representation of floating point value.
  3221. static SDValue
  3222. GetSignificand(SelectionDAG &DAG, SDValue Op, SDLoc dl) {
  3223. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3224. DAG.getConstant(0x007fffff, MVT::i32));
  3225. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  3226. DAG.getConstant(0x3f800000, MVT::i32));
  3227. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  3228. }
  3229. /// GetExponent - Get the exponent:
  3230. ///
  3231. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  3232. ///
  3233. /// where Op is the hexadecimal representation of floating point value.
  3234. static SDValue
  3235. GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
  3236. SDLoc dl) {
  3237. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  3238. DAG.getConstant(0x7f800000, MVT::i32));
  3239. SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
  3240. DAG.getConstant(23, TLI.getPointerTy()));
  3241. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  3242. DAG.getConstant(127, MVT::i32));
  3243. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  3244. }
  3245. /// getF32Constant - Get 32-bit floating point constant.
  3246. static SDValue
  3247. getF32Constant(SelectionDAG &DAG, unsigned Flt) {
  3248. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle, APInt(32, Flt)),
  3249. MVT::f32);
  3250. }
  3251. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  3252. /// limited-precision mode.
  3253. static SDValue expandExp(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3254. const TargetLowering &TLI) {
  3255. if (Op.getValueType() == MVT::f32 &&
  3256. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3257. // Put the exponent in the right bit position for later addition to the
  3258. // final result:
  3259. //
  3260. // #define LOG2OFe 1.4426950f
  3261. // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
  3262. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3263. getF32Constant(DAG, 0x3fb8aa3b));
  3264. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3265. // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
  3266. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3267. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3268. // IntegerPartOfX <<= 23;
  3269. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3270. DAG.getConstant(23, TLI.getPointerTy()));
  3271. SDValue TwoToFracPartOfX;
  3272. if (LimitFloatPrecision <= 6) {
  3273. // For floating-point precision of 6:
  3274. //
  3275. // TwoToFractionalPartOfX =
  3276. // 0.997535578f +
  3277. // (0.735607626f + 0.252464424f * x) * x;
  3278. //
  3279. // error 0.0144103317, which is 6 bits
  3280. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3281. getF32Constant(DAG, 0x3e814304));
  3282. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3283. getF32Constant(DAG, 0x3f3c50c8));
  3284. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3285. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3286. getF32Constant(DAG, 0x3f7f5e7e));
  3287. } else if (LimitFloatPrecision <= 12) {
  3288. // For floating-point precision of 12:
  3289. //
  3290. // TwoToFractionalPartOfX =
  3291. // 0.999892986f +
  3292. // (0.696457318f +
  3293. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3294. //
  3295. // 0.000107046256 error, which is 13 to 14 bits
  3296. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3297. getF32Constant(DAG, 0x3da235e3));
  3298. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3299. getF32Constant(DAG, 0x3e65b8f3));
  3300. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3301. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3302. getF32Constant(DAG, 0x3f324b07));
  3303. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3304. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3305. getF32Constant(DAG, 0x3f7ff8fd));
  3306. } else { // LimitFloatPrecision <= 18
  3307. // For floating-point precision of 18:
  3308. //
  3309. // TwoToFractionalPartOfX =
  3310. // 0.999999982f +
  3311. // (0.693148872f +
  3312. // (0.240227044f +
  3313. // (0.554906021e-1f +
  3314. // (0.961591928e-2f +
  3315. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3316. //
  3317. // error 2.47208000*10^(-7), which is better than 18 bits
  3318. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3319. getF32Constant(DAG, 0x3924b03e));
  3320. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3321. getF32Constant(DAG, 0x3ab24b87));
  3322. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3323. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3324. getF32Constant(DAG, 0x3c1d8c17));
  3325. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3326. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3327. getF32Constant(DAG, 0x3d634a1d));
  3328. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3329. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3330. getF32Constant(DAG, 0x3e75fe14));
  3331. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3332. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3333. getF32Constant(DAG, 0x3f317234));
  3334. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3335. TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3336. getF32Constant(DAG, 0x3f800000));
  3337. }
  3338. // Add the exponent into the result in integer domain.
  3339. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
  3340. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3341. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3342. t13, IntegerPartOfX));
  3343. }
  3344. // No special expansion.
  3345. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  3346. }
  3347. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  3348. /// limited-precision mode.
  3349. static SDValue expandLog(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3350. const TargetLowering &TLI) {
  3351. if (Op.getValueType() == MVT::f32 &&
  3352. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3353. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3354. // Scale the exponent by log(2) [0.69314718f].
  3355. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3356. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3357. getF32Constant(DAG, 0x3f317218));
  3358. // Get the significand and build it into a floating-point number with
  3359. // exponent of 1.
  3360. SDValue X = GetSignificand(DAG, Op1, dl);
  3361. SDValue LogOfMantissa;
  3362. if (LimitFloatPrecision <= 6) {
  3363. // For floating-point precision of 6:
  3364. //
  3365. // LogofMantissa =
  3366. // -1.1609546f +
  3367. // (1.4034025f - 0.23903021f * x) * x;
  3368. //
  3369. // error 0.0034276066, which is better than 8 bits
  3370. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3371. getF32Constant(DAG, 0xbe74c456));
  3372. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3373. getF32Constant(DAG, 0x3fb3a2b1));
  3374. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3375. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3376. getF32Constant(DAG, 0x3f949a29));
  3377. } else if (LimitFloatPrecision <= 12) {
  3378. // For floating-point precision of 12:
  3379. //
  3380. // LogOfMantissa =
  3381. // -1.7417939f +
  3382. // (2.8212026f +
  3383. // (-1.4699568f +
  3384. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  3385. //
  3386. // error 0.000061011436, which is 14 bits
  3387. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3388. getF32Constant(DAG, 0xbd67b6d6));
  3389. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3390. getF32Constant(DAG, 0x3ee4f4b8));
  3391. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3392. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3393. getF32Constant(DAG, 0x3fbc278b));
  3394. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3395. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3396. getF32Constant(DAG, 0x40348e95));
  3397. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3398. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3399. getF32Constant(DAG, 0x3fdef31a));
  3400. } else { // LimitFloatPrecision <= 18
  3401. // For floating-point precision of 18:
  3402. //
  3403. // LogOfMantissa =
  3404. // -2.1072184f +
  3405. // (4.2372794f +
  3406. // (-3.7029485f +
  3407. // (2.2781945f +
  3408. // (-0.87823314f +
  3409. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  3410. //
  3411. // error 0.0000023660568, which is better than 18 bits
  3412. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3413. getF32Constant(DAG, 0xbc91e5ac));
  3414. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3415. getF32Constant(DAG, 0x3e4350aa));
  3416. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3417. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3418. getF32Constant(DAG, 0x3f60d3e3));
  3419. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3420. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3421. getF32Constant(DAG, 0x4011cdf0));
  3422. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3423. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3424. getF32Constant(DAG, 0x406cfd1c));
  3425. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3426. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3427. getF32Constant(DAG, 0x408797cb));
  3428. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3429. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3430. getF32Constant(DAG, 0x4006dcab));
  3431. }
  3432. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  3433. }
  3434. // No special expansion.
  3435. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  3436. }
  3437. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3438. /// limited-precision mode.
  3439. static SDValue expandLog2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3440. const TargetLowering &TLI) {
  3441. if (Op.getValueType() == MVT::f32 &&
  3442. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3443. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3444. // Get the exponent.
  3445. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3446. // Get the significand and build it into a floating-point number with
  3447. // exponent of 1.
  3448. SDValue X = GetSignificand(DAG, Op1, dl);
  3449. // Different possible minimax approximations of significand in
  3450. // floating-point for various degrees of accuracy over [1,2].
  3451. SDValue Log2ofMantissa;
  3452. if (LimitFloatPrecision <= 6) {
  3453. // For floating-point precision of 6:
  3454. //
  3455. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  3456. //
  3457. // error 0.0049451742, which is more than 7 bits
  3458. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3459. getF32Constant(DAG, 0xbeb08fe0));
  3460. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3461. getF32Constant(DAG, 0x40019463));
  3462. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3463. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3464. getF32Constant(DAG, 0x3fd6633d));
  3465. } else if (LimitFloatPrecision <= 12) {
  3466. // For floating-point precision of 12:
  3467. //
  3468. // Log2ofMantissa =
  3469. // -2.51285454f +
  3470. // (4.07009056f +
  3471. // (-2.12067489f +
  3472. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  3473. //
  3474. // error 0.0000876136000, which is better than 13 bits
  3475. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3476. getF32Constant(DAG, 0xbda7262e));
  3477. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3478. getF32Constant(DAG, 0x3f25280b));
  3479. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3480. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3481. getF32Constant(DAG, 0x4007b923));
  3482. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3483. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3484. getF32Constant(DAG, 0x40823e2f));
  3485. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3486. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3487. getF32Constant(DAG, 0x4020d29c));
  3488. } else { // LimitFloatPrecision <= 18
  3489. // For floating-point precision of 18:
  3490. //
  3491. // Log2ofMantissa =
  3492. // -3.0400495f +
  3493. // (6.1129976f +
  3494. // (-5.3420409f +
  3495. // (3.2865683f +
  3496. // (-1.2669343f +
  3497. // (0.27515199f -
  3498. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3499. //
  3500. // error 0.0000018516, which is better than 18 bits
  3501. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3502. getF32Constant(DAG, 0xbcd2769e));
  3503. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3504. getF32Constant(DAG, 0x3e8ce0b9));
  3505. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3506. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3507. getF32Constant(DAG, 0x3fa22ae7));
  3508. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3509. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3510. getF32Constant(DAG, 0x40525723));
  3511. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3512. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3513. getF32Constant(DAG, 0x40aaf200));
  3514. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3515. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3516. getF32Constant(DAG, 0x40c39dad));
  3517. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3518. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3519. getF32Constant(DAG, 0x4042902c));
  3520. }
  3521. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  3522. }
  3523. // No special expansion.
  3524. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  3525. }
  3526. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  3527. /// limited-precision mode.
  3528. static SDValue expandLog10(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3529. const TargetLowering &TLI) {
  3530. if (Op.getValueType() == MVT::f32 &&
  3531. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3532. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3533. // Scale the exponent by log10(2) [0.30102999f].
  3534. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3535. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3536. getF32Constant(DAG, 0x3e9a209a));
  3537. // Get the significand and build it into a floating-point number with
  3538. // exponent of 1.
  3539. SDValue X = GetSignificand(DAG, Op1, dl);
  3540. SDValue Log10ofMantissa;
  3541. if (LimitFloatPrecision <= 6) {
  3542. // For floating-point precision of 6:
  3543. //
  3544. // Log10ofMantissa =
  3545. // -0.50419619f +
  3546. // (0.60948995f - 0.10380950f * x) * x;
  3547. //
  3548. // error 0.0014886165, which is 6 bits
  3549. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3550. getF32Constant(DAG, 0xbdd49a13));
  3551. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3552. getF32Constant(DAG, 0x3f1c0789));
  3553. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3554. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3555. getF32Constant(DAG, 0x3f011300));
  3556. } else if (LimitFloatPrecision <= 12) {
  3557. // For floating-point precision of 12:
  3558. //
  3559. // Log10ofMantissa =
  3560. // -0.64831180f +
  3561. // (0.91751397f +
  3562. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  3563. //
  3564. // error 0.00019228036, which is better than 12 bits
  3565. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3566. getF32Constant(DAG, 0x3d431f31));
  3567. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3568. getF32Constant(DAG, 0x3ea21fb2));
  3569. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3570. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3571. getF32Constant(DAG, 0x3f6ae232));
  3572. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3573. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3574. getF32Constant(DAG, 0x3f25f7c3));
  3575. } else { // LimitFloatPrecision <= 18
  3576. // For floating-point precision of 18:
  3577. //
  3578. // Log10ofMantissa =
  3579. // -0.84299375f +
  3580. // (1.5327582f +
  3581. // (-1.0688956f +
  3582. // (0.49102474f +
  3583. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  3584. //
  3585. // error 0.0000037995730, which is better than 18 bits
  3586. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3587. getF32Constant(DAG, 0x3c5d51ce));
  3588. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3589. getF32Constant(DAG, 0x3e00685a));
  3590. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3591. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3592. getF32Constant(DAG, 0x3efb6798));
  3593. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3594. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3595. getF32Constant(DAG, 0x3f88d192));
  3596. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3597. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3598. getF32Constant(DAG, 0x3fc4316c));
  3599. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3600. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  3601. getF32Constant(DAG, 0x3f57ce70));
  3602. }
  3603. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  3604. }
  3605. // No special expansion.
  3606. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  3607. }
  3608. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  3609. /// limited-precision mode.
  3610. static SDValue expandExp2(SDLoc dl, SDValue Op, SelectionDAG &DAG,
  3611. const TargetLowering &TLI) {
  3612. if (Op.getValueType() == MVT::f32 &&
  3613. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3614. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
  3615. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3616. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3617. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
  3618. // IntegerPartOfX <<= 23;
  3619. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3620. DAG.getConstant(23, TLI.getPointerTy()));
  3621. SDValue TwoToFractionalPartOfX;
  3622. if (LimitFloatPrecision <= 6) {
  3623. // For floating-point precision of 6:
  3624. //
  3625. // TwoToFractionalPartOfX =
  3626. // 0.997535578f +
  3627. // (0.735607626f + 0.252464424f * x) * x;
  3628. //
  3629. // error 0.0144103317, which is 6 bits
  3630. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3631. getF32Constant(DAG, 0x3e814304));
  3632. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3633. getF32Constant(DAG, 0x3f3c50c8));
  3634. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3635. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3636. getF32Constant(DAG, 0x3f7f5e7e));
  3637. } else if (LimitFloatPrecision <= 12) {
  3638. // For floating-point precision of 12:
  3639. //
  3640. // TwoToFractionalPartOfX =
  3641. // 0.999892986f +
  3642. // (0.696457318f +
  3643. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3644. //
  3645. // error 0.000107046256, which is 13 to 14 bits
  3646. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3647. getF32Constant(DAG, 0x3da235e3));
  3648. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3649. getF32Constant(DAG, 0x3e65b8f3));
  3650. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3651. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3652. getF32Constant(DAG, 0x3f324b07));
  3653. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3654. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3655. getF32Constant(DAG, 0x3f7ff8fd));
  3656. } else { // LimitFloatPrecision <= 18
  3657. // For floating-point precision of 18:
  3658. //
  3659. // TwoToFractionalPartOfX =
  3660. // 0.999999982f +
  3661. // (0.693148872f +
  3662. // (0.240227044f +
  3663. // (0.554906021e-1f +
  3664. // (0.961591928e-2f +
  3665. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3666. // error 2.47208000*10^(-7), which is better than 18 bits
  3667. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3668. getF32Constant(DAG, 0x3924b03e));
  3669. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3670. getF32Constant(DAG, 0x3ab24b87));
  3671. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3672. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3673. getF32Constant(DAG, 0x3c1d8c17));
  3674. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3675. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3676. getF32Constant(DAG, 0x3d634a1d));
  3677. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3678. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3679. getF32Constant(DAG, 0x3e75fe14));
  3680. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3681. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3682. getF32Constant(DAG, 0x3f317234));
  3683. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3684. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3685. getF32Constant(DAG, 0x3f800000));
  3686. }
  3687. // Add the exponent into the result in integer domain.
  3688. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
  3689. TwoToFractionalPartOfX);
  3690. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3691. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3692. t13, IntegerPartOfX));
  3693. }
  3694. // No special expansion.
  3695. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  3696. }
  3697. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  3698. /// limited-precision mode with x == 10.0f.
  3699. static SDValue expandPow(SDLoc dl, SDValue LHS, SDValue RHS,
  3700. SelectionDAG &DAG, const TargetLowering &TLI) {
  3701. bool IsExp10 = false;
  3702. if (LHS.getValueType() == MVT::f32 && LHS.getValueType() == MVT::f32 &&
  3703. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3704. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  3705. APFloat Ten(10.0f);
  3706. IsExp10 = LHSC->isExactlyValue(Ten);
  3707. }
  3708. }
  3709. if (IsExp10) {
  3710. // Put the exponent in the right bit position for later addition to the
  3711. // final result:
  3712. //
  3713. // #define LOG2OF10 3.3219281f
  3714. // IntegerPartOfX = (int32_t)(x * LOG2OF10);
  3715. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  3716. getF32Constant(DAG, 0x40549a78));
  3717. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3718. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3719. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3720. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3721. // IntegerPartOfX <<= 23;
  3722. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3723. DAG.getConstant(23, TLI.getPointerTy()));
  3724. SDValue TwoToFractionalPartOfX;
  3725. if (LimitFloatPrecision <= 6) {
  3726. // For floating-point precision of 6:
  3727. //
  3728. // twoToFractionalPartOfX =
  3729. // 0.997535578f +
  3730. // (0.735607626f + 0.252464424f * x) * x;
  3731. //
  3732. // error 0.0144103317, which is 6 bits
  3733. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3734. getF32Constant(DAG, 0x3e814304));
  3735. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3736. getF32Constant(DAG, 0x3f3c50c8));
  3737. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3738. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3739. getF32Constant(DAG, 0x3f7f5e7e));
  3740. } else if (LimitFloatPrecision <= 12) {
  3741. // For floating-point precision of 12:
  3742. //
  3743. // TwoToFractionalPartOfX =
  3744. // 0.999892986f +
  3745. // (0.696457318f +
  3746. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3747. //
  3748. // error 0.000107046256, which is 13 to 14 bits
  3749. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3750. getF32Constant(DAG, 0x3da235e3));
  3751. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3752. getF32Constant(DAG, 0x3e65b8f3));
  3753. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3754. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3755. getF32Constant(DAG, 0x3f324b07));
  3756. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3757. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3758. getF32Constant(DAG, 0x3f7ff8fd));
  3759. } else { // LimitFloatPrecision <= 18
  3760. // For floating-point precision of 18:
  3761. //
  3762. // TwoToFractionalPartOfX =
  3763. // 0.999999982f +
  3764. // (0.693148872f +
  3765. // (0.240227044f +
  3766. // (0.554906021e-1f +
  3767. // (0.961591928e-2f +
  3768. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3769. // error 2.47208000*10^(-7), which is better than 18 bits
  3770. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3771. getF32Constant(DAG, 0x3924b03e));
  3772. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3773. getF32Constant(DAG, 0x3ab24b87));
  3774. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3775. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3776. getF32Constant(DAG, 0x3c1d8c17));
  3777. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3778. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3779. getF32Constant(DAG, 0x3d634a1d));
  3780. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3781. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3782. getF32Constant(DAG, 0x3e75fe14));
  3783. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3784. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3785. getF32Constant(DAG, 0x3f317234));
  3786. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3787. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3788. getF32Constant(DAG, 0x3f800000));
  3789. }
  3790. SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
  3791. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  3792. DAG.getNode(ISD::ADD, dl, MVT::i32,
  3793. t13, IntegerPartOfX));
  3794. }
  3795. // No special expansion.
  3796. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  3797. }
  3798. /// ExpandPowI - Expand a llvm.powi intrinsic.
  3799. static SDValue ExpandPowI(SDLoc DL, SDValue LHS, SDValue RHS,
  3800. SelectionDAG &DAG) {
  3801. // If RHS is a constant, we can expand this out to a multiplication tree,
  3802. // otherwise we end up lowering to a call to __powidf2 (for example). When
  3803. // optimizing for size, we only want to do this if the expansion would produce
  3804. // a small number of multiplies, otherwise we do the full expansion.
  3805. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  3806. // Get the exponent as a positive value.
  3807. unsigned Val = RHSC->getSExtValue();
  3808. if ((int)Val < 0) Val = -Val;
  3809. // powi(x, 0) -> 1.0
  3810. if (Val == 0)
  3811. return DAG.getConstantFP(1.0, LHS.getValueType());
  3812. const Function *F = DAG.getMachineFunction().getFunction();
  3813. if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
  3814. Attribute::OptimizeForSize) ||
  3815. // If optimizing for size, don't insert too many multiplies. This
  3816. // inserts up to 5 multiplies.
  3817. CountPopulation_32(Val)+Log2_32(Val) < 7) {
  3818. // We use the simple binary decomposition method to generate the multiply
  3819. // sequence. There are more optimal ways to do this (for example,
  3820. // powi(x,15) generates one more multiply than it should), but this has
  3821. // the benefit of being both really simple and much better than a libcall.
  3822. SDValue Res; // Logically starts equal to 1.0
  3823. SDValue CurSquare = LHS;
  3824. while (Val) {
  3825. if (Val & 1) {
  3826. if (Res.getNode())
  3827. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  3828. else
  3829. Res = CurSquare; // 1.0*CurSquare.
  3830. }
  3831. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  3832. CurSquare, CurSquare);
  3833. Val >>= 1;
  3834. }
  3835. // If the original was negative, invert the result, producing 1/(x*x*x).
  3836. if (RHSC->getSExtValue() < 0)
  3837. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  3838. DAG.getConstantFP(1.0, LHS.getValueType()), Res);
  3839. return Res;
  3840. }
  3841. }
  3842. // Otherwise, expand to a libcall.
  3843. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  3844. }
  3845. // getTruncatedArgReg - Find underlying register used for an truncated
  3846. // argument.
  3847. static unsigned getTruncatedArgReg(const SDValue &N) {
  3848. if (N.getOpcode() != ISD::TRUNCATE)
  3849. return 0;
  3850. const SDValue &Ext = N.getOperand(0);
  3851. if (Ext.getOpcode() == ISD::AssertZext ||
  3852. Ext.getOpcode() == ISD::AssertSext) {
  3853. const SDValue &CFR = Ext.getOperand(0);
  3854. if (CFR.getOpcode() == ISD::CopyFromReg)
  3855. return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
  3856. if (CFR.getOpcode() == ISD::TRUNCATE)
  3857. return getTruncatedArgReg(CFR);
  3858. }
  3859. return 0;
  3860. }
  3861. /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
  3862. /// argument, create the corresponding DBG_VALUE machine instruction for it now.
  3863. /// At the end of instruction selection, they will be inserted to the entry BB.
  3864. bool
  3865. SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
  3866. int64_t Offset,
  3867. const SDValue &N) {
  3868. const Argument *Arg = dyn_cast<Argument>(V);
  3869. if (!Arg)
  3870. return false;
  3871. MachineFunction &MF = DAG.getMachineFunction();
  3872. const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
  3873. // Ignore inlined function arguments here.
  3874. DIVariable DV(Variable);
  3875. if (DV.isInlinedFnArgument(MF.getFunction()))
  3876. return false;
  3877. Optional<MachineOperand> Op;
  3878. // Some arguments' frame index is recorded during argument lowering.
  3879. if (int FI = FuncInfo.getArgumentFrameIndex(Arg))
  3880. Op = MachineOperand::CreateFI(FI);
  3881. if (!Op && N.getNode()) {
  3882. unsigned Reg;
  3883. if (N.getOpcode() == ISD::CopyFromReg)
  3884. Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
  3885. else
  3886. Reg = getTruncatedArgReg(N);
  3887. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  3888. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  3889. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  3890. if (PR)
  3891. Reg = PR;
  3892. }
  3893. if (Reg)
  3894. Op = MachineOperand::CreateReg(Reg, false);
  3895. }
  3896. if (!Op) {
  3897. // Check if ValueMap has reg number.
  3898. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  3899. if (VMI != FuncInfo.ValueMap.end())
  3900. Op = MachineOperand::CreateReg(VMI->second, false);
  3901. }
  3902. if (!Op && N.getNode())
  3903. // Check if frame index is available.
  3904. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  3905. if (FrameIndexSDNode *FINode =
  3906. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  3907. Op = MachineOperand::CreateFI(FINode->getIndex());
  3908. if (!Op)
  3909. return false;
  3910. // FIXME: This does not handle register-indirect values at offset 0.
  3911. bool IsIndirect = Offset != 0;
  3912. if (Op->isReg())
  3913. FuncInfo.ArgDbgValues.push_back(BuildMI(MF, getCurDebugLoc(),
  3914. TII->get(TargetOpcode::DBG_VALUE),
  3915. IsIndirect,
  3916. Op->getReg(), Offset, Variable));
  3917. else
  3918. FuncInfo.ArgDbgValues.push_back(
  3919. BuildMI(MF, getCurDebugLoc(), TII->get(TargetOpcode::DBG_VALUE))
  3920. .addOperand(*Op).addImm(Offset).addMetadata(Variable));
  3921. return true;
  3922. }
  3923. // VisualStudio defines setjmp as _setjmp
  3924. #if defined(_MSC_VER) && defined(setjmp) && \
  3925. !defined(setjmp_undefined_for_msvc)
  3926. # pragma push_macro("setjmp")
  3927. # undef setjmp
  3928. # define setjmp_undefined_for_msvc
  3929. #endif
  3930. /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
  3931. /// we want to emit this as a call to a named external function, return the name
  3932. /// otherwise lower it and return null.
  3933. const char *
  3934. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  3935. const TargetLowering *TLI = TM.getTargetLowering();
  3936. SDLoc sdl = getCurSDLoc();
  3937. DebugLoc dl = getCurDebugLoc();
  3938. SDValue Res;
  3939. switch (Intrinsic) {
  3940. default:
  3941. // By default, turn this into a target intrinsic node.
  3942. visitTargetIntrinsic(I, Intrinsic);
  3943. return 0;
  3944. case Intrinsic::vastart: visitVAStart(I); return 0;
  3945. case Intrinsic::vaend: visitVAEnd(I); return 0;
  3946. case Intrinsic::vacopy: visitVACopy(I); return 0;
  3947. case Intrinsic::returnaddress:
  3948. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl, TLI->getPointerTy(),
  3949. getValue(I.getArgOperand(0))));
  3950. return 0;
  3951. case Intrinsic::frameaddress:
  3952. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl, TLI->getPointerTy(),
  3953. getValue(I.getArgOperand(0))));
  3954. return 0;
  3955. case Intrinsic::setjmp:
  3956. return &"_setjmp"[!TLI->usesUnderscoreSetJmp()];
  3957. case Intrinsic::longjmp:
  3958. return &"_longjmp"[!TLI->usesUnderscoreLongJmp()];
  3959. case Intrinsic::memcpy: {
  3960. // Assert for address < 256 since we support only user defined address
  3961. // spaces.
  3962. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  3963. < 256 &&
  3964. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  3965. < 256 &&
  3966. "Unknown address space");
  3967. SDValue Op1 = getValue(I.getArgOperand(0));
  3968. SDValue Op2 = getValue(I.getArgOperand(1));
  3969. SDValue Op3 = getValue(I.getArgOperand(2));
  3970. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  3971. if (!Align)
  3972. Align = 1; // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  3973. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  3974. DAG.setRoot(DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol, false,
  3975. MachinePointerInfo(I.getArgOperand(0)),
  3976. MachinePointerInfo(I.getArgOperand(1))));
  3977. return 0;
  3978. }
  3979. case Intrinsic::memset: {
  3980. // Assert for address < 256 since we support only user defined address
  3981. // spaces.
  3982. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  3983. < 256 &&
  3984. "Unknown address space");
  3985. SDValue Op1 = getValue(I.getArgOperand(0));
  3986. SDValue Op2 = getValue(I.getArgOperand(1));
  3987. SDValue Op3 = getValue(I.getArgOperand(2));
  3988. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  3989. if (!Align)
  3990. Align = 1; // @llvm.memset defines 0 and 1 to both mean no alignment.
  3991. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  3992. DAG.setRoot(DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  3993. MachinePointerInfo(I.getArgOperand(0))));
  3994. return 0;
  3995. }
  3996. case Intrinsic::memmove: {
  3997. // Assert for address < 256 since we support only user defined address
  3998. // spaces.
  3999. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  4000. < 256 &&
  4001. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  4002. < 256 &&
  4003. "Unknown address space");
  4004. SDValue Op1 = getValue(I.getArgOperand(0));
  4005. SDValue Op2 = getValue(I.getArgOperand(1));
  4006. SDValue Op3 = getValue(I.getArgOperand(2));
  4007. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  4008. if (!Align)
  4009. Align = 1; // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4010. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  4011. DAG.setRoot(DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4012. MachinePointerInfo(I.getArgOperand(0)),
  4013. MachinePointerInfo(I.getArgOperand(1))));
  4014. return 0;
  4015. }
  4016. case Intrinsic::dbg_declare: {
  4017. const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  4018. MDNode *Variable = DI.getVariable();
  4019. const Value *Address = DI.getAddress();
  4020. DIVariable DIVar(Variable);
  4021. assert((!DIVar || DIVar.isVariable()) &&
  4022. "Variable in DbgDeclareInst should be either null or a DIVariable.");
  4023. if (!Address || !DIVar) {
  4024. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4025. return 0;
  4026. }
  4027. // Check if address has undef value.
  4028. if (isa<UndefValue>(Address) ||
  4029. (Address->use_empty() && !isa<Argument>(Address))) {
  4030. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4031. return 0;
  4032. }
  4033. SDValue &N = NodeMap[Address];
  4034. if (!N.getNode() && isa<Argument>(Address))
  4035. // Check unused arguments map.
  4036. N = UnusedArgNodeMap[Address];
  4037. SDDbgValue *SDV;
  4038. if (N.getNode()) {
  4039. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4040. Address = BCI->getOperand(0);
  4041. // Parameters are handled specially.
  4042. bool isParameter =
  4043. (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
  4044. isa<Argument>(Address));
  4045. const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
  4046. if (isParameter && !AI) {
  4047. FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4048. if (FINode)
  4049. // Byval parameter. We have a frame index at this point.
  4050. SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
  4051. 0, dl, SDNodeOrder);
  4052. else {
  4053. // Address is an argument, so try to emit its dbg value using
  4054. // virtual register info from the FuncInfo.ValueMap.
  4055. EmitFuncArgumentDbgValue(Address, Variable, 0, N);
  4056. return 0;
  4057. }
  4058. } else if (AI)
  4059. SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
  4060. 0, dl, SDNodeOrder);
  4061. else {
  4062. // Can't do anything with other non-AI cases yet.
  4063. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4064. DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
  4065. DEBUG(Address->dump());
  4066. return 0;
  4067. }
  4068. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  4069. } else {
  4070. // If Address is an argument then try to emit its dbg value using
  4071. // virtual register info from the FuncInfo.ValueMap.
  4072. if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
  4073. // If variable is pinned by a alloca in dominating bb then
  4074. // use StaticAllocaMap.
  4075. if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
  4076. if (AI->getParent() != DI.getParent()) {
  4077. DenseMap<const AllocaInst*, int>::iterator SI =
  4078. FuncInfo.StaticAllocaMap.find(AI);
  4079. if (SI != FuncInfo.StaticAllocaMap.end()) {
  4080. SDV = DAG.getDbgValue(Variable, SI->second,
  4081. 0, dl, SDNodeOrder);
  4082. DAG.AddDbgValue(SDV, 0, false);
  4083. return 0;
  4084. }
  4085. }
  4086. }
  4087. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4088. }
  4089. }
  4090. return 0;
  4091. }
  4092. case Intrinsic::dbg_value: {
  4093. const DbgValueInst &DI = cast<DbgValueInst>(I);
  4094. DIVariable DIVar(DI.getVariable());
  4095. assert((!DIVar || DIVar.isVariable()) &&
  4096. "Variable in DbgValueInst should be either null or a DIVariable.");
  4097. if (!DIVar)
  4098. return 0;
  4099. MDNode *Variable = DI.getVariable();
  4100. uint64_t Offset = DI.getOffset();
  4101. const Value *V = DI.getValue();
  4102. if (!V)
  4103. return 0;
  4104. SDDbgValue *SDV;
  4105. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
  4106. SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
  4107. DAG.AddDbgValue(SDV, 0, false);
  4108. } else {
  4109. // Do not use getValue() in here; we don't want to generate code at
  4110. // this point if it hasn't been done yet.
  4111. SDValue N = NodeMap[V];
  4112. if (!N.getNode() && isa<Argument>(V))
  4113. // Check unused arguments map.
  4114. N = UnusedArgNodeMap[V];
  4115. if (N.getNode()) {
  4116. if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
  4117. SDV = DAG.getDbgValue(Variable, N.getNode(),
  4118. N.getResNo(), Offset, dl, SDNodeOrder);
  4119. DAG.AddDbgValue(SDV, N.getNode(), false);
  4120. }
  4121. } else if (!V->use_empty() ) {
  4122. // Do not call getValue(V) yet, as we don't want to generate code.
  4123. // Remember it for later.
  4124. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  4125. DanglingDebugInfoMap[V] = DDI;
  4126. } else {
  4127. // We may expand this to cover more cases. One case where we have no
  4128. // data available is an unreferenced parameter.
  4129. DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4130. }
  4131. }
  4132. // Build a debug info table entry.
  4133. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
  4134. V = BCI->getOperand(0);
  4135. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  4136. // Don't handle byval struct arguments or VLAs, for example.
  4137. if (!AI) {
  4138. DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
  4139. DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
  4140. return 0;
  4141. }
  4142. DenseMap<const AllocaInst*, int>::iterator SI =
  4143. FuncInfo.StaticAllocaMap.find(AI);
  4144. if (SI == FuncInfo.StaticAllocaMap.end())
  4145. return 0; // VLAs.
  4146. int FI = SI->second;
  4147. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4148. if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
  4149. MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
  4150. return 0;
  4151. }
  4152. case Intrinsic::eh_typeid_for: {
  4153. // Find the type id for the given typeinfo.
  4154. GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
  4155. unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
  4156. Res = DAG.getConstant(TypeID, MVT::i32);
  4157. setValue(&I, Res);
  4158. return 0;
  4159. }
  4160. case Intrinsic::eh_return_i32:
  4161. case Intrinsic::eh_return_i64:
  4162. DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
  4163. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  4164. MVT::Other,
  4165. getControlRoot(),
  4166. getValue(I.getArgOperand(0)),
  4167. getValue(I.getArgOperand(1))));
  4168. return 0;
  4169. case Intrinsic::eh_unwind_init:
  4170. DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
  4171. return 0;
  4172. case Intrinsic::eh_dwarf_cfa: {
  4173. SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), sdl,
  4174. TLI->getPointerTy());
  4175. SDValue Offset = DAG.getNode(ISD::ADD, sdl,
  4176. CfaArg.getValueType(),
  4177. DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, sdl,
  4178. CfaArg.getValueType()),
  4179. CfaArg);
  4180. SDValue FA = DAG.getNode(ISD::FRAMEADDR, sdl,
  4181. TLI->getPointerTy(),
  4182. DAG.getConstant(0, TLI->getPointerTy()));
  4183. setValue(&I, DAG.getNode(ISD::ADD, sdl, FA.getValueType(),
  4184. FA, Offset));
  4185. return 0;
  4186. }
  4187. case Intrinsic::eh_sjlj_callsite: {
  4188. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4189. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  4190. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  4191. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  4192. MMI.setCurrentCallSite(CI->getZExtValue());
  4193. return 0;
  4194. }
  4195. case Intrinsic::eh_sjlj_functioncontext: {
  4196. // Get and store the index of the function context.
  4197. MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
  4198. AllocaInst *FnCtx =
  4199. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  4200. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  4201. MFI->setFunctionContextIndex(FI);
  4202. return 0;
  4203. }
  4204. case Intrinsic::eh_sjlj_setjmp: {
  4205. SDValue Ops[2];
  4206. Ops[0] = getRoot();
  4207. Ops[1] = getValue(I.getArgOperand(0));
  4208. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  4209. DAG.getVTList(MVT::i32, MVT::Other),
  4210. Ops, 2);
  4211. setValue(&I, Op.getValue(0));
  4212. DAG.setRoot(Op.getValue(1));
  4213. return 0;
  4214. }
  4215. case Intrinsic::eh_sjlj_longjmp: {
  4216. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  4217. getRoot(), getValue(I.getArgOperand(0))));
  4218. return 0;
  4219. }
  4220. case Intrinsic::x86_mmx_pslli_w:
  4221. case Intrinsic::x86_mmx_pslli_d:
  4222. case Intrinsic::x86_mmx_pslli_q:
  4223. case Intrinsic::x86_mmx_psrli_w:
  4224. case Intrinsic::x86_mmx_psrli_d:
  4225. case Intrinsic::x86_mmx_psrli_q:
  4226. case Intrinsic::x86_mmx_psrai_w:
  4227. case Intrinsic::x86_mmx_psrai_d: {
  4228. SDValue ShAmt = getValue(I.getArgOperand(1));
  4229. if (isa<ConstantSDNode>(ShAmt)) {
  4230. visitTargetIntrinsic(I, Intrinsic);
  4231. return 0;
  4232. }
  4233. unsigned NewIntrinsic = 0;
  4234. EVT ShAmtVT = MVT::v2i32;
  4235. switch (Intrinsic) {
  4236. case Intrinsic::x86_mmx_pslli_w:
  4237. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  4238. break;
  4239. case Intrinsic::x86_mmx_pslli_d:
  4240. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  4241. break;
  4242. case Intrinsic::x86_mmx_pslli_q:
  4243. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  4244. break;
  4245. case Intrinsic::x86_mmx_psrli_w:
  4246. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  4247. break;
  4248. case Intrinsic::x86_mmx_psrli_d:
  4249. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  4250. break;
  4251. case Intrinsic::x86_mmx_psrli_q:
  4252. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  4253. break;
  4254. case Intrinsic::x86_mmx_psrai_w:
  4255. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  4256. break;
  4257. case Intrinsic::x86_mmx_psrai_d:
  4258. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  4259. break;
  4260. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4261. }
  4262. // The vector shift intrinsics with scalars uses 32b shift amounts but
  4263. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  4264. // to be zero.
  4265. // We must do this early because v2i32 is not a legal type.
  4266. SDValue ShOps[2];
  4267. ShOps[0] = ShAmt;
  4268. ShOps[1] = DAG.getConstant(0, MVT::i32);
  4269. ShAmt = DAG.getNode(ISD::BUILD_VECTOR, sdl, ShAmtVT, &ShOps[0], 2);
  4270. EVT DestVT = TLI->getValueType(I.getType());
  4271. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  4272. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  4273. DAG.getConstant(NewIntrinsic, MVT::i32),
  4274. getValue(I.getArgOperand(0)), ShAmt);
  4275. setValue(&I, Res);
  4276. return 0;
  4277. }
  4278. case Intrinsic::x86_avx_vinsertf128_pd_256:
  4279. case Intrinsic::x86_avx_vinsertf128_ps_256:
  4280. case Intrinsic::x86_avx_vinsertf128_si_256:
  4281. case Intrinsic::x86_avx2_vinserti128: {
  4282. EVT DestVT = TLI->getValueType(I.getType());
  4283. EVT ElVT = TLI->getValueType(I.getArgOperand(1)->getType());
  4284. uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
  4285. ElVT.getVectorNumElements();
  4286. Res = DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, DestVT,
  4287. getValue(I.getArgOperand(0)),
  4288. getValue(I.getArgOperand(1)),
  4289. DAG.getConstant(Idx, TLI->getVectorIdxTy()));
  4290. setValue(&I, Res);
  4291. return 0;
  4292. }
  4293. case Intrinsic::x86_avx_vextractf128_pd_256:
  4294. case Intrinsic::x86_avx_vextractf128_ps_256:
  4295. case Intrinsic::x86_avx_vextractf128_si_256:
  4296. case Intrinsic::x86_avx2_vextracti128: {
  4297. EVT DestVT = TLI->getValueType(I.getType());
  4298. uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
  4299. DestVT.getVectorNumElements();
  4300. Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, DestVT,
  4301. getValue(I.getArgOperand(0)),
  4302. DAG.getConstant(Idx, TLI->getVectorIdxTy()));
  4303. setValue(&I, Res);
  4304. return 0;
  4305. }
  4306. case Intrinsic::convertff:
  4307. case Intrinsic::convertfsi:
  4308. case Intrinsic::convertfui:
  4309. case Intrinsic::convertsif:
  4310. case Intrinsic::convertuif:
  4311. case Intrinsic::convertss:
  4312. case Intrinsic::convertsu:
  4313. case Intrinsic::convertus:
  4314. case Intrinsic::convertuu: {
  4315. ISD::CvtCode Code = ISD::CVT_INVALID;
  4316. switch (Intrinsic) {
  4317. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4318. case Intrinsic::convertff: Code = ISD::CVT_FF; break;
  4319. case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
  4320. case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
  4321. case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
  4322. case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
  4323. case Intrinsic::convertss: Code = ISD::CVT_SS; break;
  4324. case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
  4325. case Intrinsic::convertus: Code = ISD::CVT_US; break;
  4326. case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
  4327. }
  4328. EVT DestVT = TLI->getValueType(I.getType());
  4329. const Value *Op1 = I.getArgOperand(0);
  4330. Res = DAG.getConvertRndSat(DestVT, sdl, getValue(Op1),
  4331. DAG.getValueType(DestVT),
  4332. DAG.getValueType(getValue(Op1).getValueType()),
  4333. getValue(I.getArgOperand(1)),
  4334. getValue(I.getArgOperand(2)),
  4335. Code);
  4336. setValue(&I, Res);
  4337. return 0;
  4338. }
  4339. case Intrinsic::powi:
  4340. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  4341. getValue(I.getArgOperand(1)), DAG));
  4342. return 0;
  4343. case Intrinsic::log:
  4344. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4345. return 0;
  4346. case Intrinsic::log2:
  4347. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4348. return 0;
  4349. case Intrinsic::log10:
  4350. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4351. return 0;
  4352. case Intrinsic::exp:
  4353. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4354. return 0;
  4355. case Intrinsic::exp2:
  4356. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, *TLI));
  4357. return 0;
  4358. case Intrinsic::pow:
  4359. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  4360. getValue(I.getArgOperand(1)), DAG, *TLI));
  4361. return 0;
  4362. case Intrinsic::sqrt:
  4363. case Intrinsic::fabs:
  4364. case Intrinsic::sin:
  4365. case Intrinsic::cos:
  4366. case Intrinsic::floor:
  4367. case Intrinsic::ceil:
  4368. case Intrinsic::trunc:
  4369. case Intrinsic::rint:
  4370. case Intrinsic::nearbyint:
  4371. case Intrinsic::round: {
  4372. unsigned Opcode;
  4373. switch (Intrinsic) {
  4374. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4375. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  4376. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  4377. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  4378. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  4379. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  4380. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  4381. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  4382. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  4383. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  4384. case Intrinsic::round: Opcode = ISD::FROUND; break;
  4385. }
  4386. setValue(&I, DAG.getNode(Opcode, sdl,
  4387. getValue(I.getArgOperand(0)).getValueType(),
  4388. getValue(I.getArgOperand(0))));
  4389. return 0;
  4390. }
  4391. case Intrinsic::copysign:
  4392. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  4393. getValue(I.getArgOperand(0)).getValueType(),
  4394. getValue(I.getArgOperand(0)),
  4395. getValue(I.getArgOperand(1))));
  4396. return 0;
  4397. case Intrinsic::fma:
  4398. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4399. getValue(I.getArgOperand(0)).getValueType(),
  4400. getValue(I.getArgOperand(0)),
  4401. getValue(I.getArgOperand(1)),
  4402. getValue(I.getArgOperand(2))));
  4403. return 0;
  4404. case Intrinsic::fmuladd: {
  4405. EVT VT = TLI->getValueType(I.getType());
  4406. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  4407. TLI->isFMAFasterThanFMulAndFAdd(VT)) {
  4408. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  4409. getValue(I.getArgOperand(0)).getValueType(),
  4410. getValue(I.getArgOperand(0)),
  4411. getValue(I.getArgOperand(1)),
  4412. getValue(I.getArgOperand(2))));
  4413. } else {
  4414. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  4415. getValue(I.getArgOperand(0)).getValueType(),
  4416. getValue(I.getArgOperand(0)),
  4417. getValue(I.getArgOperand(1)));
  4418. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  4419. getValue(I.getArgOperand(0)).getValueType(),
  4420. Mul,
  4421. getValue(I.getArgOperand(2)));
  4422. setValue(&I, Add);
  4423. }
  4424. return 0;
  4425. }
  4426. case Intrinsic::convert_to_fp16:
  4427. setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, sdl,
  4428. MVT::i16, getValue(I.getArgOperand(0))));
  4429. return 0;
  4430. case Intrinsic::convert_from_fp16:
  4431. setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, sdl,
  4432. MVT::f32, getValue(I.getArgOperand(0))));
  4433. return 0;
  4434. case Intrinsic::pcmarker: {
  4435. SDValue Tmp = getValue(I.getArgOperand(0));
  4436. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  4437. return 0;
  4438. }
  4439. case Intrinsic::readcyclecounter: {
  4440. SDValue Op = getRoot();
  4441. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  4442. DAG.getVTList(MVT::i64, MVT::Other),
  4443. &Op, 1);
  4444. setValue(&I, Res);
  4445. DAG.setRoot(Res.getValue(1));
  4446. return 0;
  4447. }
  4448. case Intrinsic::bswap:
  4449. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  4450. getValue(I.getArgOperand(0)).getValueType(),
  4451. getValue(I.getArgOperand(0))));
  4452. return 0;
  4453. case Intrinsic::cttz: {
  4454. SDValue Arg = getValue(I.getArgOperand(0));
  4455. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4456. EVT Ty = Arg.getValueType();
  4457. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  4458. sdl, Ty, Arg));
  4459. return 0;
  4460. }
  4461. case Intrinsic::ctlz: {
  4462. SDValue Arg = getValue(I.getArgOperand(0));
  4463. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  4464. EVT Ty = Arg.getValueType();
  4465. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  4466. sdl, Ty, Arg));
  4467. return 0;
  4468. }
  4469. case Intrinsic::ctpop: {
  4470. SDValue Arg = getValue(I.getArgOperand(0));
  4471. EVT Ty = Arg.getValueType();
  4472. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  4473. return 0;
  4474. }
  4475. case Intrinsic::stacksave: {
  4476. SDValue Op = getRoot();
  4477. Res = DAG.getNode(ISD::STACKSAVE, sdl,
  4478. DAG.getVTList(TLI->getPointerTy(), MVT::Other), &Op, 1);
  4479. setValue(&I, Res);
  4480. DAG.setRoot(Res.getValue(1));
  4481. return 0;
  4482. }
  4483. case Intrinsic::stackrestore: {
  4484. Res = getValue(I.getArgOperand(0));
  4485. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  4486. return 0;
  4487. }
  4488. case Intrinsic::stackprotector: {
  4489. // Emit code into the DAG to store the stack guard onto the stack.
  4490. MachineFunction &MF = DAG.getMachineFunction();
  4491. MachineFrameInfo *MFI = MF.getFrameInfo();
  4492. EVT PtrTy = TLI->getPointerTy();
  4493. SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
  4494. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  4495. int FI = FuncInfo.StaticAllocaMap[Slot];
  4496. MFI->setStackProtectorIndex(FI);
  4497. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  4498. // Store the stack protector onto the stack.
  4499. Res = DAG.getStore(getRoot(), sdl, Src, FIN,
  4500. MachinePointerInfo::getFixedStack(FI),
  4501. true, false, 0);
  4502. setValue(&I, Res);
  4503. DAG.setRoot(Res);
  4504. return 0;
  4505. }
  4506. case Intrinsic::objectsize: {
  4507. // If we don't know by now, we're never going to know.
  4508. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  4509. assert(CI && "Non-constant type in __builtin_object_size?");
  4510. SDValue Arg = getValue(I.getCalledValue());
  4511. EVT Ty = Arg.getValueType();
  4512. if (CI->isZero())
  4513. Res = DAG.getConstant(-1ULL, Ty);
  4514. else
  4515. Res = DAG.getConstant(0, Ty);
  4516. setValue(&I, Res);
  4517. return 0;
  4518. }
  4519. case Intrinsic::annotation:
  4520. case Intrinsic::ptr_annotation:
  4521. // Drop the intrinsic, but forward the value
  4522. setValue(&I, getValue(I.getOperand(0)));
  4523. return 0;
  4524. case Intrinsic::var_annotation:
  4525. // Discard annotate attributes
  4526. return 0;
  4527. case Intrinsic::init_trampoline: {
  4528. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  4529. SDValue Ops[6];
  4530. Ops[0] = getRoot();
  4531. Ops[1] = getValue(I.getArgOperand(0));
  4532. Ops[2] = getValue(I.getArgOperand(1));
  4533. Ops[3] = getValue(I.getArgOperand(2));
  4534. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  4535. Ops[5] = DAG.getSrcValue(F);
  4536. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops, 6);
  4537. DAG.setRoot(Res);
  4538. return 0;
  4539. }
  4540. case Intrinsic::adjust_trampoline: {
  4541. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  4542. TLI->getPointerTy(),
  4543. getValue(I.getArgOperand(0))));
  4544. return 0;
  4545. }
  4546. case Intrinsic::gcroot:
  4547. if (GFI) {
  4548. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  4549. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  4550. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  4551. GFI->addStackRoot(FI->getIndex(), TypeMap);
  4552. }
  4553. return 0;
  4554. case Intrinsic::gcread:
  4555. case Intrinsic::gcwrite:
  4556. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  4557. case Intrinsic::flt_rounds:
  4558. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  4559. return 0;
  4560. case Intrinsic::expect: {
  4561. // Just replace __builtin_expect(exp, c) with EXP.
  4562. setValue(&I, getValue(I.getArgOperand(0)));
  4563. return 0;
  4564. }
  4565. case Intrinsic::debugtrap:
  4566. case Intrinsic::trap: {
  4567. StringRef TrapFuncName = TM.Options.getTrapFunctionName();
  4568. if (TrapFuncName.empty()) {
  4569. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  4570. ISD::TRAP : ISD::DEBUGTRAP;
  4571. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  4572. return 0;
  4573. }
  4574. TargetLowering::ArgListTy Args;
  4575. TargetLowering::
  4576. CallLoweringInfo CLI(getRoot(), I.getType(),
  4577. false, false, false, false, 0, CallingConv::C,
  4578. /*isTailCall=*/false,
  4579. /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
  4580. DAG.getExternalSymbol(TrapFuncName.data(),
  4581. TLI->getPointerTy()),
  4582. Args, DAG, sdl);
  4583. std::pair<SDValue, SDValue> Result = TLI->LowerCallTo(CLI);
  4584. DAG.setRoot(Result.second);
  4585. return 0;
  4586. }
  4587. case Intrinsic::uadd_with_overflow:
  4588. case Intrinsic::sadd_with_overflow:
  4589. case Intrinsic::usub_with_overflow:
  4590. case Intrinsic::ssub_with_overflow:
  4591. case Intrinsic::umul_with_overflow:
  4592. case Intrinsic::smul_with_overflow: {
  4593. ISD::NodeType Op;
  4594. switch (Intrinsic) {
  4595. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  4596. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  4597. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  4598. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  4599. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  4600. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  4601. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  4602. }
  4603. SDValue Op1 = getValue(I.getArgOperand(0));
  4604. SDValue Op2 = getValue(I.getArgOperand(1));
  4605. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  4606. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  4607. return 0;
  4608. }
  4609. case Intrinsic::prefetch: {
  4610. SDValue Ops[5];
  4611. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  4612. Ops[0] = getRoot();
  4613. Ops[1] = getValue(I.getArgOperand(0));
  4614. Ops[2] = getValue(I.getArgOperand(1));
  4615. Ops[3] = getValue(I.getArgOperand(2));
  4616. Ops[4] = getValue(I.getArgOperand(3));
  4617. DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  4618. DAG.getVTList(MVT::Other),
  4619. &Ops[0], 5,
  4620. EVT::getIntegerVT(*Context, 8),
  4621. MachinePointerInfo(I.getArgOperand(0)),
  4622. 0, /* align */
  4623. false, /* volatile */
  4624. rw==0, /* read */
  4625. rw==1)); /* write */
  4626. return 0;
  4627. }
  4628. case Intrinsic::lifetime_start:
  4629. case Intrinsic::lifetime_end: {
  4630. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  4631. // Stack coloring is not enabled in O0, discard region information.
  4632. if (TM.getOptLevel() == CodeGenOpt::None)
  4633. return 0;
  4634. SmallVector<Value *, 4> Allocas;
  4635. GetUnderlyingObjects(I.getArgOperand(1), Allocas, TD);
  4636. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  4637. E = Allocas.end(); Object != E; ++Object) {
  4638. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  4639. // Could not find an Alloca.
  4640. if (!LifetimeObject)
  4641. continue;
  4642. int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
  4643. SDValue Ops[2];
  4644. Ops[0] = getRoot();
  4645. Ops[1] = DAG.getFrameIndex(FI, TLI->getPointerTy(), true);
  4646. unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
  4647. Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops, 2);
  4648. DAG.setRoot(Res);
  4649. }
  4650. return 0;
  4651. }
  4652. case Intrinsic::invariant_start:
  4653. // Discard region information.
  4654. setValue(&I, DAG.getUNDEF(TLI->getPointerTy()));
  4655. return 0;
  4656. case Intrinsic::invariant_end:
  4657. // Discard region information.
  4658. return 0;
  4659. case Intrinsic::stackprotectorcheck: {
  4660. // Do not actually emit anything for this basic block. Instead we initialize
  4661. // the stack protector descriptor and export the guard variable so we can
  4662. // access it in FinishBasicBlock.
  4663. const BasicBlock *BB = I.getParent();
  4664. SPDescriptor.initialize(BB, FuncInfo.MBBMap[BB], I);
  4665. ExportFromCurrentBlock(SPDescriptor.getGuard());
  4666. // Flush our exports since we are going to process a terminator.
  4667. (void)getControlRoot();
  4668. return 0;
  4669. }
  4670. case Intrinsic::donothing:
  4671. // ignore
  4672. return 0;
  4673. case Intrinsic::experimental_stackmap: {
  4674. visitStackmap(I);
  4675. return 0;
  4676. }
  4677. case Intrinsic::experimental_patchpoint_void:
  4678. case Intrinsic::experimental_patchpoint_i64: {
  4679. visitPatchpoint(I);
  4680. return 0;
  4681. }
  4682. }
  4683. }
  4684. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  4685. bool isTailCall,
  4686. MachineBasicBlock *LandingPad) {
  4687. PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
  4688. FunctionType *FTy = cast<FunctionType>(PT->getElementType());
  4689. Type *RetTy = FTy->getReturnType();
  4690. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4691. MCSymbol *BeginLabel = 0;
  4692. TargetLowering::ArgListTy Args;
  4693. TargetLowering::ArgListEntry Entry;
  4694. Args.reserve(CS.arg_size());
  4695. // Check whether the function can return without sret-demotion.
  4696. SmallVector<ISD::OutputArg, 4> Outs;
  4697. const TargetLowering *TLI = TM.getTargetLowering();
  4698. GetReturnInfo(RetTy, CS.getAttributes(), Outs, *TLI);
  4699. bool CanLowerReturn = TLI->CanLowerReturn(CS.getCallingConv(),
  4700. DAG.getMachineFunction(),
  4701. FTy->isVarArg(), Outs,
  4702. FTy->getContext());
  4703. SDValue DemoteStackSlot;
  4704. int DemoteStackIdx = -100;
  4705. if (!CanLowerReturn) {
  4706. uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(
  4707. FTy->getReturnType());
  4708. unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(
  4709. FTy->getReturnType());
  4710. MachineFunction &MF = DAG.getMachineFunction();
  4711. DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  4712. Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
  4713. DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI->getPointerTy());
  4714. Entry.Node = DemoteStackSlot;
  4715. Entry.Ty = StackSlotPtrType;
  4716. Entry.isSExt = false;
  4717. Entry.isZExt = false;
  4718. Entry.isInReg = false;
  4719. Entry.isSRet = true;
  4720. Entry.isNest = false;
  4721. Entry.isByVal = false;
  4722. Entry.isReturned = false;
  4723. Entry.Alignment = Align;
  4724. Args.push_back(Entry);
  4725. RetTy = Type::getVoidTy(FTy->getContext());
  4726. }
  4727. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  4728. i != e; ++i) {
  4729. const Value *V = *i;
  4730. // Skip empty types
  4731. if (V->getType()->isEmptyTy())
  4732. continue;
  4733. SDValue ArgNode = getValue(V);
  4734. Entry.Node = ArgNode; Entry.Ty = V->getType();
  4735. // Skip the first return-type Attribute to get to params.
  4736. Entry.setAttributes(&CS, i - CS.arg_begin() + 1);
  4737. Args.push_back(Entry);
  4738. }
  4739. if (LandingPad) {
  4740. // Insert a label before the invoke call to mark the try range. This can be
  4741. // used to detect deletion of the invoke via the MachineModuleInfo.
  4742. BeginLabel = MMI.getContext().CreateTempSymbol();
  4743. // For SjLj, keep track of which landing pads go with which invokes
  4744. // so as to maintain the ordering of pads in the LSDA.
  4745. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  4746. if (CallSiteIndex) {
  4747. MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  4748. LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
  4749. // Now that the call site is handled, stop tracking it.
  4750. MMI.setCurrentCallSite(0);
  4751. }
  4752. // Both PendingLoads and PendingExports must be flushed here;
  4753. // this call might not return.
  4754. (void)getRoot();
  4755. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  4756. }
  4757. // Check if target-independent constraints permit a tail call here.
  4758. // Target-dependent constraints are checked within TLI->LowerCallTo.
  4759. if (isTailCall && !isInTailCallPosition(CS, *TLI))
  4760. isTailCall = false;
  4761. TargetLowering::
  4762. CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
  4763. getCurSDLoc(), CS);
  4764. std::pair<SDValue,SDValue> Result = TLI->LowerCallTo(CLI);
  4765. assert((isTailCall || Result.second.getNode()) &&
  4766. "Non-null chain expected with non-tail call!");
  4767. assert((Result.second.getNode() || !Result.first.getNode()) &&
  4768. "Null value expected with tail call!");
  4769. if (Result.first.getNode()) {
  4770. setValue(CS.getInstruction(), Result.first);
  4771. } else if (!CanLowerReturn && Result.second.getNode()) {
  4772. // The instruction result is the result of loading from the
  4773. // hidden sret parameter.
  4774. SmallVector<EVT, 1> PVTs;
  4775. Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
  4776. ComputeValueVTs(*TLI, PtrRetTy, PVTs);
  4777. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  4778. EVT PtrVT = PVTs[0];
  4779. SmallVector<EVT, 4> RetTys;
  4780. SmallVector<uint64_t, 4> Offsets;
  4781. RetTy = FTy->getReturnType();
  4782. ComputeValueVTs(*TLI, RetTy, RetTys, &Offsets);
  4783. unsigned NumValues = RetTys.size();
  4784. SmallVector<SDValue, 4> Values(NumValues);
  4785. SmallVector<SDValue, 4> Chains(NumValues);
  4786. for (unsigned i = 0; i < NumValues; ++i) {
  4787. SDValue Add = DAG.getNode(ISD::ADD, getCurSDLoc(), PtrVT,
  4788. DemoteStackSlot,
  4789. DAG.getConstant(Offsets[i], PtrVT));
  4790. SDValue L = DAG.getLoad(RetTys[i], getCurSDLoc(), Result.second, Add,
  4791. MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
  4792. false, false, false, 1);
  4793. Values[i] = L;
  4794. Chains[i] = L.getValue(1);
  4795. }
  4796. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  4797. MVT::Other, &Chains[0], NumValues);
  4798. PendingLoads.push_back(Chain);
  4799. setValue(CS.getInstruction(),
  4800. DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  4801. DAG.getVTList(&RetTys[0], RetTys.size()),
  4802. &Values[0], Values.size()));
  4803. }
  4804. if (!Result.second.getNode()) {
  4805. // As a special case, a null chain means that a tail call has been emitted
  4806. // and the DAG root is already updated.
  4807. HasTailCall = true;
  4808. // Since there's no actual continuation from this block, nothing can be
  4809. // relying on us setting vregs for them.
  4810. PendingExports.clear();
  4811. } else {
  4812. DAG.setRoot(Result.second);
  4813. }
  4814. if (LandingPad) {
  4815. // Insert a label at the end of the invoke call to mark the try range. This
  4816. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  4817. MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
  4818. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  4819. // Inform MachineModuleInfo of range.
  4820. MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
  4821. }
  4822. }
  4823. /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
  4824. /// value is equal or not-equal to zero.
  4825. static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
  4826. for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
  4827. UI != E; ++UI) {
  4828. if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
  4829. if (IC->isEquality())
  4830. if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  4831. if (C->isNullValue())
  4832. continue;
  4833. // Unknown instruction.
  4834. return false;
  4835. }
  4836. return true;
  4837. }
  4838. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  4839. Type *LoadTy,
  4840. SelectionDAGBuilder &Builder) {
  4841. // Check to see if this load can be trivially constant folded, e.g. if the
  4842. // input is from a string literal.
  4843. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  4844. // Cast pointer to the type we really want to load.
  4845. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  4846. PointerType::getUnqual(LoadTy));
  4847. if (const Constant *LoadCst =
  4848. ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
  4849. Builder.TD))
  4850. return Builder.getValue(LoadCst);
  4851. }
  4852. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  4853. // still constant memory, the input chain can be the entry node.
  4854. SDValue Root;
  4855. bool ConstantMemory = false;
  4856. // Do not serialize (non-volatile) loads of constant memory with anything.
  4857. if (Builder.AA->pointsToConstantMemory(PtrVal)) {
  4858. Root = Builder.DAG.getEntryNode();
  4859. ConstantMemory = true;
  4860. } else {
  4861. // Do not serialize non-volatile loads against each other.
  4862. Root = Builder.DAG.getRoot();
  4863. }
  4864. SDValue Ptr = Builder.getValue(PtrVal);
  4865. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  4866. Ptr, MachinePointerInfo(PtrVal),
  4867. false /*volatile*/,
  4868. false /*nontemporal*/,
  4869. false /*isinvariant*/, 1 /* align=1 */);
  4870. if (!ConstantMemory)
  4871. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  4872. return LoadVal;
  4873. }
  4874. /// processIntegerCallValue - Record the value for an instruction that
  4875. /// produces an integer result, converting the type where necessary.
  4876. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  4877. SDValue Value,
  4878. bool IsSigned) {
  4879. EVT VT = TM.getTargetLowering()->getValueType(I.getType(), true);
  4880. if (IsSigned)
  4881. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  4882. else
  4883. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  4884. setValue(&I, Value);
  4885. }
  4886. /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
  4887. /// If so, return true and lower it, otherwise return false and it will be
  4888. /// lowered like a normal call.
  4889. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  4890. // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
  4891. if (I.getNumArgOperands() != 3)
  4892. return false;
  4893. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  4894. if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
  4895. !I.getArgOperand(2)->getType()->isIntegerTy() ||
  4896. !I.getType()->isIntegerTy())
  4897. return false;
  4898. const Value *Size = I.getArgOperand(2);
  4899. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  4900. if (CSize && CSize->getZExtValue() == 0) {
  4901. EVT CallVT = TM.getTargetLowering()->getValueType(I.getType(), true);
  4902. setValue(&I, DAG.getConstant(0, CallVT));
  4903. return true;
  4904. }
  4905. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  4906. std::pair<SDValue, SDValue> Res =
  4907. TSI.EmitTargetCodeForMemcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  4908. getValue(LHS), getValue(RHS), getValue(Size),
  4909. MachinePointerInfo(LHS),
  4910. MachinePointerInfo(RHS));
  4911. if (Res.first.getNode()) {
  4912. processIntegerCallValue(I, Res.first, true);
  4913. PendingLoads.push_back(Res.second);
  4914. return true;
  4915. }
  4916. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  4917. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  4918. if (CSize && IsOnlyUsedInZeroEqualityComparison(&I)) {
  4919. bool ActuallyDoIt = true;
  4920. MVT LoadVT;
  4921. Type *LoadTy;
  4922. switch (CSize->getZExtValue()) {
  4923. default:
  4924. LoadVT = MVT::Other;
  4925. LoadTy = 0;
  4926. ActuallyDoIt = false;
  4927. break;
  4928. case 2:
  4929. LoadVT = MVT::i16;
  4930. LoadTy = Type::getInt16Ty(CSize->getContext());
  4931. break;
  4932. case 4:
  4933. LoadVT = MVT::i32;
  4934. LoadTy = Type::getInt32Ty(CSize->getContext());
  4935. break;
  4936. case 8:
  4937. LoadVT = MVT::i64;
  4938. LoadTy = Type::getInt64Ty(CSize->getContext());
  4939. break;
  4940. /*
  4941. case 16:
  4942. LoadVT = MVT::v4i32;
  4943. LoadTy = Type::getInt32Ty(CSize->getContext());
  4944. LoadTy = VectorType::get(LoadTy, 4);
  4945. break;
  4946. */
  4947. }
  4948. // This turns into unaligned loads. We only do this if the target natively
  4949. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  4950. // we'll only produce a small number of byte loads.
  4951. // Require that we can find a legal MVT, and only do this if the target
  4952. // supports unaligned loads of that type. Expanding into byte loads would
  4953. // bloat the code.
  4954. const TargetLowering *TLI = TM.getTargetLowering();
  4955. if (ActuallyDoIt && CSize->getZExtValue() > 4) {
  4956. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  4957. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  4958. if (!TLI->isTypeLegal(LoadVT) ||!TLI->allowsUnalignedMemoryAccesses(LoadVT))
  4959. ActuallyDoIt = false;
  4960. }
  4961. if (ActuallyDoIt) {
  4962. SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
  4963. SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
  4964. SDValue Res = DAG.getSetCC(getCurSDLoc(), MVT::i1, LHSVal, RHSVal,
  4965. ISD::SETNE);
  4966. processIntegerCallValue(I, Res, false);
  4967. return true;
  4968. }
  4969. }
  4970. return false;
  4971. }
  4972. /// visitMemChrCall -- See if we can lower a memchr call into an optimized
  4973. /// form. If so, return true and lower it, otherwise return false and it
  4974. /// will be lowered like a normal call.
  4975. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  4976. // Verify that the prototype makes sense. void *memchr(void *, int, size_t)
  4977. if (I.getNumArgOperands() != 3)
  4978. return false;
  4979. const Value *Src = I.getArgOperand(0);
  4980. const Value *Char = I.getArgOperand(1);
  4981. const Value *Length = I.getArgOperand(2);
  4982. if (!Src->getType()->isPointerTy() ||
  4983. !Char->getType()->isIntegerTy() ||
  4984. !Length->getType()->isIntegerTy() ||
  4985. !I.getType()->isPointerTy())
  4986. return false;
  4987. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  4988. std::pair<SDValue, SDValue> Res =
  4989. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  4990. getValue(Src), getValue(Char), getValue(Length),
  4991. MachinePointerInfo(Src));
  4992. if (Res.first.getNode()) {
  4993. setValue(&I, Res.first);
  4994. PendingLoads.push_back(Res.second);
  4995. return true;
  4996. }
  4997. return false;
  4998. }
  4999. /// visitStrCpyCall -- See if we can lower a strcpy or stpcpy call into an
  5000. /// optimized form. If so, return true and lower it, otherwise return false
  5001. /// and it will be lowered like a normal call.
  5002. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  5003. // Verify that the prototype makes sense. char *strcpy(char *, char *)
  5004. if (I.getNumArgOperands() != 2)
  5005. return false;
  5006. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5007. if (!Arg0->getType()->isPointerTy() ||
  5008. !Arg1->getType()->isPointerTy() ||
  5009. !I.getType()->isPointerTy())
  5010. return false;
  5011. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5012. std::pair<SDValue, SDValue> Res =
  5013. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  5014. getValue(Arg0), getValue(Arg1),
  5015. MachinePointerInfo(Arg0),
  5016. MachinePointerInfo(Arg1), isStpcpy);
  5017. if (Res.first.getNode()) {
  5018. setValue(&I, Res.first);
  5019. DAG.setRoot(Res.second);
  5020. return true;
  5021. }
  5022. return false;
  5023. }
  5024. /// visitStrCmpCall - See if we can lower a call to strcmp in an optimized form.
  5025. /// If so, return true and lower it, otherwise return false and it will be
  5026. /// lowered like a normal call.
  5027. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  5028. // Verify that the prototype makes sense. int strcmp(void*,void*)
  5029. if (I.getNumArgOperands() != 2)
  5030. return false;
  5031. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5032. if (!Arg0->getType()->isPointerTy() ||
  5033. !Arg1->getType()->isPointerTy() ||
  5034. !I.getType()->isIntegerTy())
  5035. return false;
  5036. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5037. std::pair<SDValue, SDValue> Res =
  5038. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  5039. getValue(Arg0), getValue(Arg1),
  5040. MachinePointerInfo(Arg0),
  5041. MachinePointerInfo(Arg1));
  5042. if (Res.first.getNode()) {
  5043. processIntegerCallValue(I, Res.first, true);
  5044. PendingLoads.push_back(Res.second);
  5045. return true;
  5046. }
  5047. return false;
  5048. }
  5049. /// visitStrLenCall -- See if we can lower a strlen call into an optimized
  5050. /// form. If so, return true and lower it, otherwise return false and it
  5051. /// will be lowered like a normal call.
  5052. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  5053. // Verify that the prototype makes sense. size_t strlen(char *)
  5054. if (I.getNumArgOperands() != 1)
  5055. return false;
  5056. const Value *Arg0 = I.getArgOperand(0);
  5057. if (!Arg0->getType()->isPointerTy() || !I.getType()->isIntegerTy())
  5058. return false;
  5059. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5060. std::pair<SDValue, SDValue> Res =
  5061. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5062. getValue(Arg0), MachinePointerInfo(Arg0));
  5063. if (Res.first.getNode()) {
  5064. processIntegerCallValue(I, Res.first, false);
  5065. PendingLoads.push_back(Res.second);
  5066. return true;
  5067. }
  5068. return false;
  5069. }
  5070. /// visitStrNLenCall -- See if we can lower a strnlen call into an optimized
  5071. /// form. If so, return true and lower it, otherwise return false and it
  5072. /// will be lowered like a normal call.
  5073. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  5074. // Verify that the prototype makes sense. size_t strnlen(char *, size_t)
  5075. if (I.getNumArgOperands() != 2)
  5076. return false;
  5077. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  5078. if (!Arg0->getType()->isPointerTy() ||
  5079. !Arg1->getType()->isIntegerTy() ||
  5080. !I.getType()->isIntegerTy())
  5081. return false;
  5082. const TargetSelectionDAGInfo &TSI = DAG.getSelectionDAGInfo();
  5083. std::pair<SDValue, SDValue> Res =
  5084. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  5085. getValue(Arg0), getValue(Arg1),
  5086. MachinePointerInfo(Arg0));
  5087. if (Res.first.getNode()) {
  5088. processIntegerCallValue(I, Res.first, false);
  5089. PendingLoads.push_back(Res.second);
  5090. return true;
  5091. }
  5092. return false;
  5093. }
  5094. /// visitUnaryFloatCall - If a call instruction is a unary floating-point
  5095. /// operation (as expected), translate it to an SDNode with the specified opcode
  5096. /// and return true.
  5097. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  5098. unsigned Opcode) {
  5099. // Sanity check that it really is a unary floating-point call.
  5100. if (I.getNumArgOperands() != 1 ||
  5101. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  5102. I.getType() != I.getArgOperand(0)->getType() ||
  5103. !I.onlyReadsMemory())
  5104. return false;
  5105. SDValue Tmp = getValue(I.getArgOperand(0));
  5106. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  5107. return true;
  5108. }
  5109. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  5110. // Handle inline assembly differently.
  5111. if (isa<InlineAsm>(I.getCalledValue())) {
  5112. visitInlineAsm(&I);
  5113. return;
  5114. }
  5115. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5116. ComputeUsesVAFloatArgument(I, &MMI);
  5117. const char *RenameFn = 0;
  5118. if (Function *F = I.getCalledFunction()) {
  5119. if (F->isDeclaration()) {
  5120. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  5121. if (unsigned IID = II->getIntrinsicID(F)) {
  5122. RenameFn = visitIntrinsicCall(I, IID);
  5123. if (!RenameFn)
  5124. return;
  5125. }
  5126. }
  5127. if (unsigned IID = F->getIntrinsicID()) {
  5128. RenameFn = visitIntrinsicCall(I, IID);
  5129. if (!RenameFn)
  5130. return;
  5131. }
  5132. }
  5133. // Check for well-known libc/libm calls. If the function is internal, it
  5134. // can't be a library call.
  5135. LibFunc::Func Func;
  5136. if (!F->hasLocalLinkage() && F->hasName() &&
  5137. LibInfo->getLibFunc(F->getName(), Func) &&
  5138. LibInfo->hasOptimizedCodeGen(Func)) {
  5139. switch (Func) {
  5140. default: break;
  5141. case LibFunc::copysign:
  5142. case LibFunc::copysignf:
  5143. case LibFunc::copysignl:
  5144. if (I.getNumArgOperands() == 2 && // Basic sanity checks.
  5145. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  5146. I.getType() == I.getArgOperand(0)->getType() &&
  5147. I.getType() == I.getArgOperand(1)->getType() &&
  5148. I.onlyReadsMemory()) {
  5149. SDValue LHS = getValue(I.getArgOperand(0));
  5150. SDValue RHS = getValue(I.getArgOperand(1));
  5151. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  5152. LHS.getValueType(), LHS, RHS));
  5153. return;
  5154. }
  5155. break;
  5156. case LibFunc::fabs:
  5157. case LibFunc::fabsf:
  5158. case LibFunc::fabsl:
  5159. if (visitUnaryFloatCall(I, ISD::FABS))
  5160. return;
  5161. break;
  5162. case LibFunc::sin:
  5163. case LibFunc::sinf:
  5164. case LibFunc::sinl:
  5165. if (visitUnaryFloatCall(I, ISD::FSIN))
  5166. return;
  5167. break;
  5168. case LibFunc::cos:
  5169. case LibFunc::cosf:
  5170. case LibFunc::cosl:
  5171. if (visitUnaryFloatCall(I, ISD::FCOS))
  5172. return;
  5173. break;
  5174. case LibFunc::sqrt:
  5175. case LibFunc::sqrtf:
  5176. case LibFunc::sqrtl:
  5177. case LibFunc::sqrt_finite:
  5178. case LibFunc::sqrtf_finite:
  5179. case LibFunc::sqrtl_finite:
  5180. if (visitUnaryFloatCall(I, ISD::FSQRT))
  5181. return;
  5182. break;
  5183. case LibFunc::floor:
  5184. case LibFunc::floorf:
  5185. case LibFunc::floorl:
  5186. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  5187. return;
  5188. break;
  5189. case LibFunc::nearbyint:
  5190. case LibFunc::nearbyintf:
  5191. case LibFunc::nearbyintl:
  5192. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  5193. return;
  5194. break;
  5195. case LibFunc::ceil:
  5196. case LibFunc::ceilf:
  5197. case LibFunc::ceill:
  5198. if (visitUnaryFloatCall(I, ISD::FCEIL))
  5199. return;
  5200. break;
  5201. case LibFunc::rint:
  5202. case LibFunc::rintf:
  5203. case LibFunc::rintl:
  5204. if (visitUnaryFloatCall(I, ISD::FRINT))
  5205. return;
  5206. break;
  5207. case LibFunc::round:
  5208. case LibFunc::roundf:
  5209. case LibFunc::roundl:
  5210. if (visitUnaryFloatCall(I, ISD::FROUND))
  5211. return;
  5212. break;
  5213. case LibFunc::trunc:
  5214. case LibFunc::truncf:
  5215. case LibFunc::truncl:
  5216. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  5217. return;
  5218. break;
  5219. case LibFunc::log2:
  5220. case LibFunc::log2f:
  5221. case LibFunc::log2l:
  5222. if (visitUnaryFloatCall(I, ISD::FLOG2))
  5223. return;
  5224. break;
  5225. case LibFunc::exp2:
  5226. case LibFunc::exp2f:
  5227. case LibFunc::exp2l:
  5228. if (visitUnaryFloatCall(I, ISD::FEXP2))
  5229. return;
  5230. break;
  5231. case LibFunc::memcmp:
  5232. if (visitMemCmpCall(I))
  5233. return;
  5234. break;
  5235. case LibFunc::memchr:
  5236. if (visitMemChrCall(I))
  5237. return;
  5238. break;
  5239. case LibFunc::strcpy:
  5240. if (visitStrCpyCall(I, false))
  5241. return;
  5242. break;
  5243. case LibFunc::stpcpy:
  5244. if (visitStrCpyCall(I, true))
  5245. return;
  5246. break;
  5247. case LibFunc::strcmp:
  5248. if (visitStrCmpCall(I))
  5249. return;
  5250. break;
  5251. case LibFunc::strlen:
  5252. if (visitStrLenCall(I))
  5253. return;
  5254. break;
  5255. case LibFunc::strnlen:
  5256. if (visitStrNLenCall(I))
  5257. return;
  5258. break;
  5259. }
  5260. }
  5261. }
  5262. SDValue Callee;
  5263. if (!RenameFn)
  5264. Callee = getValue(I.getCalledValue());
  5265. else
  5266. Callee = DAG.getExternalSymbol(RenameFn,
  5267. TM.getTargetLowering()->getPointerTy());
  5268. // Check if we can potentially perform a tail call. More detailed checking is
  5269. // be done within LowerCallTo, after more information about the call is known.
  5270. LowerCallTo(&I, Callee, I.isTailCall());
  5271. }
  5272. namespace {
  5273. /// AsmOperandInfo - This contains information for each constraint that we are
  5274. /// lowering.
  5275. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  5276. public:
  5277. /// CallOperand - If this is the result output operand or a clobber
  5278. /// this is null, otherwise it is the incoming operand to the CallInst.
  5279. /// This gets modified as the asm is processed.
  5280. SDValue CallOperand;
  5281. /// AssignedRegs - If this is a register or register class operand, this
  5282. /// contains the set of register corresponding to the operand.
  5283. RegsForValue AssignedRegs;
  5284. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  5285. : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
  5286. }
  5287. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  5288. /// corresponds to. If there is no Value* for this operand, it returns
  5289. /// MVT::Other.
  5290. EVT getCallOperandValEVT(LLVMContext &Context,
  5291. const TargetLowering &TLI,
  5292. const DataLayout *TD) const {
  5293. if (CallOperandVal == 0) return MVT::Other;
  5294. if (isa<BasicBlock>(CallOperandVal))
  5295. return TLI.getPointerTy();
  5296. llvm::Type *OpTy = CallOperandVal->getType();
  5297. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  5298. // If this is an indirect operand, the operand is a pointer to the
  5299. // accessed type.
  5300. if (isIndirect) {
  5301. llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  5302. if (!PtrTy)
  5303. report_fatal_error("Indirect operand for inline asm not a pointer!");
  5304. OpTy = PtrTy->getElementType();
  5305. }
  5306. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  5307. if (StructType *STy = dyn_cast<StructType>(OpTy))
  5308. if (STy->getNumElements() == 1)
  5309. OpTy = STy->getElementType(0);
  5310. // If OpTy is not a single value, it may be a struct/union that we
  5311. // can tile with integers.
  5312. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  5313. unsigned BitSize = TD->getTypeSizeInBits(OpTy);
  5314. switch (BitSize) {
  5315. default: break;
  5316. case 1:
  5317. case 8:
  5318. case 16:
  5319. case 32:
  5320. case 64:
  5321. case 128:
  5322. OpTy = IntegerType::get(Context, BitSize);
  5323. break;
  5324. }
  5325. }
  5326. return TLI.getValueType(OpTy, true);
  5327. }
  5328. };
  5329. typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
  5330. } // end anonymous namespace
  5331. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  5332. /// specified operand. We prefer to assign virtual registers, to allow the
  5333. /// register allocator to handle the assignment process. However, if the asm
  5334. /// uses features that we can't model on machineinstrs, we have SDISel do the
  5335. /// allocation. This produces generally horrible, but correct, code.
  5336. ///
  5337. /// OpInfo describes the operand.
  5338. ///
  5339. static void GetRegistersForValue(SelectionDAG &DAG,
  5340. const TargetLowering &TLI,
  5341. SDLoc DL,
  5342. SDISelAsmOperandInfo &OpInfo) {
  5343. LLVMContext &Context = *DAG.getContext();
  5344. MachineFunction &MF = DAG.getMachineFunction();
  5345. SmallVector<unsigned, 4> Regs;
  5346. // If this is a constraint for a single physreg, or a constraint for a
  5347. // register class, find it.
  5348. std::pair<unsigned, const TargetRegisterClass*> PhysReg =
  5349. TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  5350. OpInfo.ConstraintVT);
  5351. unsigned NumRegs = 1;
  5352. if (OpInfo.ConstraintVT != MVT::Other) {
  5353. // If this is a FP input in an integer register (or visa versa) insert a bit
  5354. // cast of the input value. More generally, handle any case where the input
  5355. // value disagrees with the register class we plan to stick this in.
  5356. if (OpInfo.Type == InlineAsm::isInput &&
  5357. PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
  5358. // Try to convert to the first EVT that the reg class contains. If the
  5359. // types are identical size, use a bitcast to convert (e.g. two differing
  5360. // vector types).
  5361. MVT RegVT = *PhysReg.second->vt_begin();
  5362. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  5363. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5364. RegVT, OpInfo.CallOperand);
  5365. OpInfo.ConstraintVT = RegVT;
  5366. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  5367. // If the input is a FP value and we want it in FP registers, do a
  5368. // bitcast to the corresponding integer type. This turns an f64 value
  5369. // into i64, which can be passed with two i32 values on a 32-bit
  5370. // machine.
  5371. RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  5372. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  5373. RegVT, OpInfo.CallOperand);
  5374. OpInfo.ConstraintVT = RegVT;
  5375. }
  5376. }
  5377. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  5378. }
  5379. MVT RegVT;
  5380. EVT ValueVT = OpInfo.ConstraintVT;
  5381. // If this is a constraint for a specific physical register, like {r17},
  5382. // assign it now.
  5383. if (unsigned AssignedReg = PhysReg.first) {
  5384. const TargetRegisterClass *RC = PhysReg.second;
  5385. if (OpInfo.ConstraintVT == MVT::Other)
  5386. ValueVT = *RC->vt_begin();
  5387. // Get the actual register value type. This is important, because the user
  5388. // may have asked for (e.g.) the AX register in i32 type. We need to
  5389. // remember that AX is actually i16 to get the right extension.
  5390. RegVT = *RC->vt_begin();
  5391. // This is a explicit reference to a physical register.
  5392. Regs.push_back(AssignedReg);
  5393. // If this is an expanded reference, add the rest of the regs to Regs.
  5394. if (NumRegs != 1) {
  5395. TargetRegisterClass::iterator I = RC->begin();
  5396. for (; *I != AssignedReg; ++I)
  5397. assert(I != RC->end() && "Didn't find reg!");
  5398. // Already added the first reg.
  5399. --NumRegs; ++I;
  5400. for (; NumRegs; --NumRegs, ++I) {
  5401. assert(I != RC->end() && "Ran out of registers to allocate!");
  5402. Regs.push_back(*I);
  5403. }
  5404. }
  5405. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5406. return;
  5407. }
  5408. // Otherwise, if this was a reference to an LLVM register class, create vregs
  5409. // for this reference.
  5410. if (const TargetRegisterClass *RC = PhysReg.second) {
  5411. RegVT = *RC->vt_begin();
  5412. if (OpInfo.ConstraintVT == MVT::Other)
  5413. ValueVT = RegVT;
  5414. // Create the appropriate number of virtual registers.
  5415. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  5416. for (; NumRegs; --NumRegs)
  5417. Regs.push_back(RegInfo.createVirtualRegister(RC));
  5418. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  5419. return;
  5420. }
  5421. // Otherwise, we couldn't allocate enough registers for this.
  5422. }
  5423. /// visitInlineAsm - Handle a call to an InlineAsm object.
  5424. ///
  5425. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  5426. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  5427. /// ConstraintOperands - Information about all of the constraints.
  5428. SDISelAsmOperandInfoVector ConstraintOperands;
  5429. const TargetLowering *TLI = TM.getTargetLowering();
  5430. TargetLowering::AsmOperandInfoVector
  5431. TargetConstraints = TLI->ParseConstraints(CS);
  5432. bool hasMemory = false;
  5433. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  5434. unsigned ResNo = 0; // ResNo - The result number of the next output.
  5435. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  5436. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  5437. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  5438. MVT OpVT = MVT::Other;
  5439. // Compute the value type for each operand.
  5440. switch (OpInfo.Type) {
  5441. case InlineAsm::isOutput:
  5442. // Indirect outputs just consume an argument.
  5443. if (OpInfo.isIndirect) {
  5444. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  5445. break;
  5446. }
  5447. // The return value of the call is this value. As such, there is no
  5448. // corresponding argument.
  5449. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5450. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  5451. OpVT = TLI->getSimpleValueType(STy->getElementType(ResNo));
  5452. } else {
  5453. assert(ResNo == 0 && "Asm only has one result!");
  5454. OpVT = TLI->getSimpleValueType(CS.getType());
  5455. }
  5456. ++ResNo;
  5457. break;
  5458. case InlineAsm::isInput:
  5459. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  5460. break;
  5461. case InlineAsm::isClobber:
  5462. // Nothing to do.
  5463. break;
  5464. }
  5465. // If this is an input or an indirect output, process the call argument.
  5466. // BasicBlocks are labels, currently appearing only in asm's.
  5467. if (OpInfo.CallOperandVal) {
  5468. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  5469. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  5470. } else {
  5471. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  5472. }
  5473. OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), *TLI, TD).
  5474. getSimpleVT();
  5475. }
  5476. OpInfo.ConstraintVT = OpVT;
  5477. // Indirect operand accesses access memory.
  5478. if (OpInfo.isIndirect)
  5479. hasMemory = true;
  5480. else {
  5481. for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
  5482. TargetLowering::ConstraintType
  5483. CType = TLI->getConstraintType(OpInfo.Codes[j]);
  5484. if (CType == TargetLowering::C_Memory) {
  5485. hasMemory = true;
  5486. break;
  5487. }
  5488. }
  5489. }
  5490. }
  5491. SDValue Chain, Flag;
  5492. // We won't need to flush pending loads if this asm doesn't touch
  5493. // memory and is nonvolatile.
  5494. if (hasMemory || IA->hasSideEffects())
  5495. Chain = getRoot();
  5496. else
  5497. Chain = DAG.getRoot();
  5498. // Second pass over the constraints: compute which constraint option to use
  5499. // and assign registers to constraints that want a specific physreg.
  5500. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5501. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5502. // If this is an output operand with a matching input operand, look up the
  5503. // matching input. If their types mismatch, e.g. one is an integer, the
  5504. // other is floating point, or their sizes are different, flag it as an
  5505. // error.
  5506. if (OpInfo.hasMatchingInput()) {
  5507. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  5508. if (OpInfo.ConstraintVT != Input.ConstraintVT) {
  5509. std::pair<unsigned, const TargetRegisterClass*> MatchRC =
  5510. TLI->getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  5511. OpInfo.ConstraintVT);
  5512. std::pair<unsigned, const TargetRegisterClass*> InputRC =
  5513. TLI->getRegForInlineAsmConstraint(Input.ConstraintCode,
  5514. Input.ConstraintVT);
  5515. if ((OpInfo.ConstraintVT.isInteger() !=
  5516. Input.ConstraintVT.isInteger()) ||
  5517. (MatchRC.second != InputRC.second)) {
  5518. report_fatal_error("Unsupported asm: input constraint"
  5519. " with a matching output constraint of"
  5520. " incompatible type!");
  5521. }
  5522. Input.ConstraintVT = OpInfo.ConstraintVT;
  5523. }
  5524. }
  5525. // Compute the constraint code and ConstraintType to use.
  5526. TLI->ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  5527. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5528. OpInfo.Type == InlineAsm::isClobber)
  5529. continue;
  5530. // If this is a memory input, and if the operand is not indirect, do what we
  5531. // need to to provide an address for the memory input.
  5532. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5533. !OpInfo.isIndirect) {
  5534. assert((OpInfo.isMultipleAlternative ||
  5535. (OpInfo.Type == InlineAsm::isInput)) &&
  5536. "Can only indirectify direct input operands!");
  5537. // Memory operands really want the address of the value. If we don't have
  5538. // an indirect input, put it in the constpool if we can, otherwise spill
  5539. // it to a stack slot.
  5540. // TODO: This isn't quite right. We need to handle these according to
  5541. // the addressing mode that the constraint wants. Also, this may take
  5542. // an additional register for the computation and we don't want that
  5543. // either.
  5544. // If the operand is a float, integer, or vector constant, spill to a
  5545. // constant pool entry to get its address.
  5546. const Value *OpVal = OpInfo.CallOperandVal;
  5547. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  5548. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  5549. OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
  5550. TLI->getPointerTy());
  5551. } else {
  5552. // Otherwise, create a stack slot and emit a store to it before the
  5553. // asm.
  5554. Type *Ty = OpVal->getType();
  5555. uint64_t TySize = TLI->getDataLayout()->getTypeAllocSize(Ty);
  5556. unsigned Align = TLI->getDataLayout()->getPrefTypeAlignment(Ty);
  5557. MachineFunction &MF = DAG.getMachineFunction();
  5558. int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  5559. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI->getPointerTy());
  5560. Chain = DAG.getStore(Chain, getCurSDLoc(),
  5561. OpInfo.CallOperand, StackSlot,
  5562. MachinePointerInfo::getFixedStack(SSFI),
  5563. false, false, 0);
  5564. OpInfo.CallOperand = StackSlot;
  5565. }
  5566. // There is no longer a Value* corresponding to this operand.
  5567. OpInfo.CallOperandVal = 0;
  5568. // It is now an indirect operand.
  5569. OpInfo.isIndirect = true;
  5570. }
  5571. // If this constraint is for a specific register, allocate it before
  5572. // anything else.
  5573. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  5574. GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
  5575. }
  5576. // Second pass - Loop over all of the operands, assigning virtual or physregs
  5577. // to register class operands.
  5578. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5579. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5580. // C_Register operands have already been allocated, Other/Memory don't need
  5581. // to be.
  5582. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  5583. GetRegistersForValue(DAG, *TLI, getCurSDLoc(), OpInfo);
  5584. }
  5585. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  5586. std::vector<SDValue> AsmNodeOperands;
  5587. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  5588. AsmNodeOperands.push_back(
  5589. DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
  5590. TLI->getPointerTy()));
  5591. // If we have a !srcloc metadata node associated with it, we want to attach
  5592. // this to the ultimately generated inline asm machineinstr. To do this, we
  5593. // pass in the third operand as this (potentially null) inline asm MDNode.
  5594. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  5595. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  5596. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  5597. // bits as operand 3.
  5598. unsigned ExtraInfo = 0;
  5599. if (IA->hasSideEffects())
  5600. ExtraInfo |= InlineAsm::Extra_HasSideEffects;
  5601. if (IA->isAlignStack())
  5602. ExtraInfo |= InlineAsm::Extra_IsAlignStack;
  5603. // Set the asm dialect.
  5604. ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  5605. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  5606. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  5607. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  5608. // Compute the constraint code and ConstraintType to use.
  5609. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  5610. // Ideally, we would only check against memory constraints. However, the
  5611. // meaning of an other constraint can be target-specific and we can't easily
  5612. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  5613. // for other constriants as well.
  5614. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  5615. OpInfo.ConstraintType == TargetLowering::C_Other) {
  5616. if (OpInfo.Type == InlineAsm::isInput)
  5617. ExtraInfo |= InlineAsm::Extra_MayLoad;
  5618. else if (OpInfo.Type == InlineAsm::isOutput)
  5619. ExtraInfo |= InlineAsm::Extra_MayStore;
  5620. else if (OpInfo.Type == InlineAsm::isClobber)
  5621. ExtraInfo |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  5622. }
  5623. }
  5624. AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
  5625. TLI->getPointerTy()));
  5626. // Loop over all of the inputs, copying the operand values into the
  5627. // appropriate registers and processing the output regs.
  5628. RegsForValue RetValRegs;
  5629. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  5630. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  5631. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5632. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5633. switch (OpInfo.Type) {
  5634. case InlineAsm::isOutput: {
  5635. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  5636. OpInfo.ConstraintType != TargetLowering::C_Register) {
  5637. // Memory output, or 'other' output (e.g. 'X' constraint).
  5638. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  5639. // Add information to the INLINEASM node to know about this output.
  5640. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5641. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
  5642. TLI->getPointerTy()));
  5643. AsmNodeOperands.push_back(OpInfo.CallOperand);
  5644. break;
  5645. }
  5646. // Otherwise, this is a register or register class output.
  5647. // Copy the output from the appropriate register. Find a register that
  5648. // we can use.
  5649. if (OpInfo.AssignedRegs.Regs.empty()) {
  5650. LLVMContext &Ctx = *DAG.getContext();
  5651. Ctx.emitError(CS.getInstruction(),
  5652. "couldn't allocate output register for constraint '" +
  5653. Twine(OpInfo.ConstraintCode) + "'");
  5654. return;
  5655. }
  5656. // If this is an indirect operand, store through the pointer after the
  5657. // asm.
  5658. if (OpInfo.isIndirect) {
  5659. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  5660. OpInfo.CallOperandVal));
  5661. } else {
  5662. // This is the result value of the call.
  5663. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5664. // Concatenate this output onto the outputs list.
  5665. RetValRegs.append(OpInfo.AssignedRegs);
  5666. }
  5667. // Add information to the INLINEASM node to know that this register is
  5668. // set.
  5669. OpInfo.AssignedRegs
  5670. .AddInlineAsmOperands(OpInfo.isEarlyClobber
  5671. ? InlineAsm::Kind_RegDefEarlyClobber
  5672. : InlineAsm::Kind_RegDef,
  5673. false, 0, DAG, AsmNodeOperands);
  5674. break;
  5675. }
  5676. case InlineAsm::isInput: {
  5677. SDValue InOperandVal = OpInfo.CallOperand;
  5678. if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
  5679. // If this is required to match an output register we have already set,
  5680. // just use its register.
  5681. unsigned OperandNo = OpInfo.getMatchedOperand();
  5682. // Scan until we find the definition we already emitted of this operand.
  5683. // When we find it, create a RegsForValue operand.
  5684. unsigned CurOp = InlineAsm::Op_FirstOperand;
  5685. for (; OperandNo; --OperandNo) {
  5686. // Advance to the next operand.
  5687. unsigned OpFlag =
  5688. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5689. assert((InlineAsm::isRegDefKind(OpFlag) ||
  5690. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  5691. InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
  5692. CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
  5693. }
  5694. unsigned OpFlag =
  5695. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5696. if (InlineAsm::isRegDefKind(OpFlag) ||
  5697. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  5698. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  5699. if (OpInfo.isIndirect) {
  5700. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  5701. LLVMContext &Ctx = *DAG.getContext();
  5702. Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
  5703. " don't know how to handle tied "
  5704. "indirect register inputs");
  5705. return;
  5706. }
  5707. RegsForValue MatchedRegs;
  5708. MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
  5709. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  5710. MatchedRegs.RegVTs.push_back(RegVT);
  5711. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  5712. for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
  5713. i != e; ++i) {
  5714. if (const TargetRegisterClass *RC = TLI->getRegClassFor(RegVT))
  5715. MatchedRegs.Regs.push_back(RegInfo.createVirtualRegister(RC));
  5716. else {
  5717. LLVMContext &Ctx = *DAG.getContext();
  5718. Ctx.emitError(CS.getInstruction(),
  5719. "inline asm error: This value"
  5720. " type register class is not natively supported!");
  5721. return;
  5722. }
  5723. }
  5724. // Use the produced MatchedRegs object to
  5725. MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
  5726. Chain, &Flag, CS.getInstruction());
  5727. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  5728. true, OpInfo.getMatchedOperand(),
  5729. DAG, AsmNodeOperands);
  5730. break;
  5731. }
  5732. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  5733. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  5734. "Unexpected number of operands");
  5735. // Add information to the INLINEASM node to know about this input.
  5736. // See InlineAsm.h isUseOperandTiedToDef.
  5737. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  5738. OpInfo.getMatchedOperand());
  5739. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
  5740. TLI->getPointerTy()));
  5741. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  5742. break;
  5743. }
  5744. // Treat indirect 'X' constraint as memory.
  5745. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  5746. OpInfo.isIndirect)
  5747. OpInfo.ConstraintType = TargetLowering::C_Memory;
  5748. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  5749. std::vector<SDValue> Ops;
  5750. TLI->LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  5751. Ops, DAG);
  5752. if (Ops.empty()) {
  5753. LLVMContext &Ctx = *DAG.getContext();
  5754. Ctx.emitError(CS.getInstruction(),
  5755. "invalid operand for inline asm constraint '" +
  5756. Twine(OpInfo.ConstraintCode) + "'");
  5757. return;
  5758. }
  5759. // Add information to the INLINEASM node to know about this input.
  5760. unsigned ResOpType =
  5761. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  5762. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5763. TLI->getPointerTy()));
  5764. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  5765. break;
  5766. }
  5767. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  5768. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  5769. assert(InOperandVal.getValueType() == TLI->getPointerTy() &&
  5770. "Memory operands expect pointer values");
  5771. // Add information to the INLINEASM node to know about this input.
  5772. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5773. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5774. TLI->getPointerTy()));
  5775. AsmNodeOperands.push_back(InOperandVal);
  5776. break;
  5777. }
  5778. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  5779. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  5780. "Unknown constraint type!");
  5781. // TODO: Support this.
  5782. if (OpInfo.isIndirect) {
  5783. LLVMContext &Ctx = *DAG.getContext();
  5784. Ctx.emitError(CS.getInstruction(),
  5785. "Don't know how to handle indirect register inputs yet "
  5786. "for constraint '" +
  5787. Twine(OpInfo.ConstraintCode) + "'");
  5788. return;
  5789. }
  5790. // Copy the input into the appropriate registers.
  5791. if (OpInfo.AssignedRegs.Regs.empty()) {
  5792. LLVMContext &Ctx = *DAG.getContext();
  5793. Ctx.emitError(CS.getInstruction(),
  5794. "couldn't allocate input reg for constraint '" +
  5795. Twine(OpInfo.ConstraintCode) + "'");
  5796. return;
  5797. }
  5798. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurSDLoc(),
  5799. Chain, &Flag, CS.getInstruction());
  5800. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  5801. DAG, AsmNodeOperands);
  5802. break;
  5803. }
  5804. case InlineAsm::isClobber: {
  5805. // Add the clobbered value to the operand list, so that the register
  5806. // allocator is aware that the physreg got clobbered.
  5807. if (!OpInfo.AssignedRegs.Regs.empty())
  5808. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  5809. false, 0, DAG,
  5810. AsmNodeOperands);
  5811. break;
  5812. }
  5813. }
  5814. }
  5815. // Finish up input operands. Set the input chain and add the flag last.
  5816. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  5817. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  5818. Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
  5819. DAG.getVTList(MVT::Other, MVT::Glue),
  5820. &AsmNodeOperands[0], AsmNodeOperands.size());
  5821. Flag = Chain.getValue(1);
  5822. // If this asm returns a register value, copy the result from that register
  5823. // and set it as the value of the call.
  5824. if (!RetValRegs.Regs.empty()) {
  5825. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  5826. Chain, &Flag, CS.getInstruction());
  5827. // FIXME: Why don't we do this for inline asms with MRVs?
  5828. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  5829. EVT ResultType = TLI->getValueType(CS.getType());
  5830. // If any of the results of the inline asm is a vector, it may have the
  5831. // wrong width/num elts. This can happen for register classes that can
  5832. // contain multiple different value types. The preg or vreg allocated may
  5833. // not have the same VT as was expected. Convert it to the right type
  5834. // with bit_convert.
  5835. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  5836. Val = DAG.getNode(ISD::BITCAST, getCurSDLoc(),
  5837. ResultType, Val);
  5838. } else if (ResultType != Val.getValueType() &&
  5839. ResultType.isInteger() && Val.getValueType().isInteger()) {
  5840. // If a result value was tied to an input value, the computed result may
  5841. // have a wider width than the expected result. Extract the relevant
  5842. // portion.
  5843. Val = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultType, Val);
  5844. }
  5845. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  5846. }
  5847. setValue(CS.getInstruction(), Val);
  5848. // Don't need to use this as a chain in this case.
  5849. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  5850. return;
  5851. }
  5852. std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
  5853. // Process indirect outputs, first output all of the flagged copies out of
  5854. // physregs.
  5855. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  5856. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  5857. const Value *Ptr = IndirectStoresToEmit[i].second;
  5858. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
  5859. Chain, &Flag, IA);
  5860. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  5861. }
  5862. // Emit the non-flagged stores from the physregs.
  5863. SmallVector<SDValue, 8> OutChains;
  5864. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  5865. SDValue Val = DAG.getStore(Chain, getCurSDLoc(),
  5866. StoresToEmit[i].first,
  5867. getValue(StoresToEmit[i].second),
  5868. MachinePointerInfo(StoresToEmit[i].second),
  5869. false, false, 0);
  5870. OutChains.push_back(Val);
  5871. }
  5872. if (!OutChains.empty())
  5873. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  5874. &OutChains[0], OutChains.size());
  5875. DAG.setRoot(Chain);
  5876. }
  5877. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  5878. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  5879. MVT::Other, getRoot(),
  5880. getValue(I.getArgOperand(0)),
  5881. DAG.getSrcValue(I.getArgOperand(0))));
  5882. }
  5883. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  5884. const TargetLowering *TLI = TM.getTargetLowering();
  5885. const DataLayout &TD = *TLI->getDataLayout();
  5886. SDValue V = DAG.getVAArg(TLI->getValueType(I.getType()), getCurSDLoc(),
  5887. getRoot(), getValue(I.getOperand(0)),
  5888. DAG.getSrcValue(I.getOperand(0)),
  5889. TD.getABITypeAlignment(I.getType()));
  5890. setValue(&I, V);
  5891. DAG.setRoot(V.getValue(1));
  5892. }
  5893. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  5894. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  5895. MVT::Other, getRoot(),
  5896. getValue(I.getArgOperand(0)),
  5897. DAG.getSrcValue(I.getArgOperand(0))));
  5898. }
  5899. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  5900. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  5901. MVT::Other, getRoot(),
  5902. getValue(I.getArgOperand(0)),
  5903. getValue(I.getArgOperand(1)),
  5904. DAG.getSrcValue(I.getArgOperand(0)),
  5905. DAG.getSrcValue(I.getArgOperand(1))));
  5906. }
  5907. /// \brief Lower an argument list according to the target calling convention.
  5908. ///
  5909. /// \return A tuple of <return-value, token-chain>
  5910. ///
  5911. /// This is a helper for lowering intrinsics that follow a target calling
  5912. /// convention or require stack pointer adjustment. Only a subset of the
  5913. /// intrinsic's operands need to participate in the calling convention.
  5914. std::pair<SDValue, SDValue>
  5915. SelectionDAGBuilder::LowerCallOperands(const CallInst &CI, unsigned ArgIdx,
  5916. unsigned NumArgs, SDValue Callee) {
  5917. TargetLowering::ArgListTy Args;
  5918. Args.reserve(NumArgs);
  5919. // Populate the argument list.
  5920. // Attributes for args start at offset 1, after the return attribute.
  5921. ImmutableCallSite CS(&CI);
  5922. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs, AttrI = ArgIdx + 1;
  5923. ArgI != ArgE; ++ArgI) {
  5924. const Value *V = CI.getOperand(ArgI);
  5925. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  5926. TargetLowering::ArgListEntry Entry;
  5927. Entry.Node = getValue(V);
  5928. Entry.Ty = V->getType();
  5929. Entry.setAttributes(&CS, AttrI);
  5930. Args.push_back(Entry);
  5931. }
  5932. TargetLowering::CallLoweringInfo CLI(getRoot(), CI.getType(),
  5933. /*retSExt*/ false, /*retZExt*/ false, /*isVarArg*/ false, /*isInReg*/ false,
  5934. NumArgs, CI.getCallingConv(), /*isTailCall*/ false, /*doesNotReturn*/ false,
  5935. /*isReturnValueUsed*/ CI.use_empty(), Callee, Args, DAG, getCurSDLoc());
  5936. const TargetLowering *TLI = TM.getTargetLowering();
  5937. return TLI->LowerCallTo(CLI);
  5938. }
  5939. /// \brief Lower llvm.experimental.stackmap directly to its target opcode.
  5940. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  5941. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  5942. // [live variables...])
  5943. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  5944. SDValue Callee = getValue(CI.getCalledValue());
  5945. // Lower into a call sequence with no args and no return value.
  5946. std::pair<SDValue, SDValue> Result = LowerCallOperands(CI, 0, 0, Callee);
  5947. // Set the root to the target-lowered call chain.
  5948. SDValue Chain = Result.second;
  5949. DAG.setRoot(Chain);
  5950. /// Get a call instruction from the call sequence chain.
  5951. /// Tail calls are not allowed.
  5952. SDNode *CallEnd = Chain.getNode();
  5953. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  5954. "Expected a callseq node.");
  5955. SDNode *Call = CallEnd->getOperand(0).getNode();
  5956. bool hasGlue = Call->getGluedNode();
  5957. assert(Call->getNumOperands() == hasGlue ? 2 : 1 &&
  5958. "Unexpected extra stackmap call arguments.");
  5959. // Replace the target specific call node with the stackmap intrinsic.
  5960. SmallVector<SDValue, 8> Ops;
  5961. // Add the <id> and <numShadowBytes> constants.
  5962. for (unsigned i = 0; i < 2; ++i) {
  5963. SDValue tmp = getValue(CI.getOperand(i));
  5964. Ops.push_back(DAG.getTargetConstant(
  5965. cast<ConstantSDNode>(tmp)->getZExtValue(), MVT::i32));
  5966. }
  5967. // Push live variables for the stack map.
  5968. for (unsigned i = 2, e = CI.getNumArgOperands(); i != e; ++i)
  5969. Ops.push_back(getValue(CI.getArgOperand(i)));
  5970. // Push the chain (this is originally the first operand of the call, but
  5971. // becomes now the last or second to last operand).
  5972. Ops.push_back(*(Call->op_begin()));
  5973. // Push the glue flag (last operand).
  5974. if (hasGlue)
  5975. Ops.push_back(*(Call->op_end()-1));
  5976. // Replace the target specific call node with STACKMAP in-place. This way we
  5977. // don't have to call ReplaceAllUsesWith and STACKMAP will take the call's
  5978. // place in the chain.
  5979. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5980. DAG.SelectNodeTo(Call, TargetOpcode::STACKMAP, NodeTys, &Ops[0], Ops.size());
  5981. }
  5982. /// \brief Lower llvm.experimental.patchpoint directly to its target opcode.
  5983. void SelectionDAGBuilder::visitPatchpoint(const CallInst &CI) {
  5984. // void|i64 @llvm.experimental.patchpoint.void|i64(i32 <id>,
  5985. // i32 <numNopBytes>,
  5986. // i8* <target>, i32 <numArgs>,
  5987. // [Args...], [live variables...])
  5988. SDValue Callee = getValue(CI.getOperand(2)); // <target>
  5989. // Get the real number of arguments participating in the call <numArgs>
  5990. unsigned NumArgs =
  5991. cast<ConstantSDNode>(getValue(CI.getArgOperand(3)))->getZExtValue();
  5992. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  5993. assert(CI.getNumArgOperands() >= NumArgs + 4 &&
  5994. "Not enough arguments provided to the patchpoint intrinsic");
  5995. std::pair<SDValue, SDValue> Result =
  5996. LowerCallOperands(CI, 4, NumArgs, Callee);
  5997. // Set the root to the target-lowered call chain.
  5998. SDValue Chain = Result.second;
  5999. DAG.setRoot(Chain);
  6000. SDNode *CallEnd = Chain.getNode();
  6001. if (!CI.getType()->isVoidTy()) {
  6002. setValue(&CI, Result.first);
  6003. if (CallEnd->getOpcode() == ISD::CopyFromReg)
  6004. CallEnd = CallEnd->getOperand(0).getNode();
  6005. }
  6006. /// Get a call instruction from the call sequence chain.
  6007. /// Tail calls are not allowed.
  6008. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  6009. "Expected a callseq node.");
  6010. SDNode *Call = CallEnd->getOperand(0).getNode();
  6011. bool hasGlue = Call->getGluedNode();
  6012. // Replace the target specific call node with the patchable intrinsic.
  6013. SmallVector<SDValue, 8> Ops;
  6014. // Add the <id> and <numNopBytes> constants.
  6015. for (unsigned i = 0; i < 2; ++i) {
  6016. SDValue tmp = getValue(CI.getOperand(i));
  6017. Ops.push_back(DAG.getTargetConstant(
  6018. cast<ConstantSDNode>(tmp)->getZExtValue(), MVT::i32));
  6019. }
  6020. // Assume that the Callee is a constant address.
  6021. Ops.push_back(
  6022. DAG.getIntPtrConstant(cast<ConstantSDNode>(Callee)->getZExtValue()));
  6023. // Adjust <numArgs> to account for any stack arguments.
  6024. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  6025. unsigned NumCallArgs = Call->getNumOperands() - (hasGlue ? 4 : 3);
  6026. Ops.push_back(DAG.getTargetConstant(NumCallArgs, MVT::i32));
  6027. // Push the arguments from the call instruction.
  6028. SDNode::op_iterator e = hasGlue ? Call->op_end()-2 : Call->op_end()-1;
  6029. for (SDNode::op_iterator i = Call->op_begin()+2; i != e; ++i)
  6030. Ops.push_back(*i);
  6031. // Push live variables for the stack map.
  6032. for (unsigned i = NumArgs + 4, e = CI.getNumArgOperands(); i != e; ++i) {
  6033. SDValue OpVal = getValue(CI.getArgOperand(i));
  6034. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  6035. Ops.push_back(
  6036. DAG.getTargetConstant(StackMaps::ConstantOp, MVT::i64));
  6037. Ops.push_back(
  6038. DAG.getTargetConstant(C->getSExtValue(), MVT::i64));
  6039. } else
  6040. Ops.push_back(OpVal);
  6041. }
  6042. // Push the register mask info.
  6043. if (hasGlue)
  6044. Ops.push_back(*(Call->op_end()-2));
  6045. else
  6046. Ops.push_back(*(Call->op_end()-1));
  6047. // Push the chain (this is originally the first operand of the call, but
  6048. // becomes now the last or second to last operand).
  6049. Ops.push_back(*(Call->op_begin()));
  6050. // Push the glue flag (last operand).
  6051. if (hasGlue)
  6052. Ops.push_back(*(Call->op_end()-1));
  6053. // Replace the target specific call node with PATCHPOINT in-place. This
  6054. // way we don't have to call ReplaceAllUsesWith and PATCHPOINT will
  6055. // take the call's place in the chain.
  6056. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6057. DAG.SelectNodeTo(Call, TargetOpcode::PATCHPOINT, NodeTys, &Ops[0],
  6058. Ops.size());
  6059. }
  6060. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  6061. /// implementation, which just calls LowerCall.
  6062. /// FIXME: When all targets are
  6063. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  6064. std::pair<SDValue, SDValue>
  6065. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  6066. // Handle the incoming return values from the call.
  6067. CLI.Ins.clear();
  6068. SmallVector<EVT, 4> RetTys;
  6069. ComputeValueVTs(*this, CLI.RetTy, RetTys);
  6070. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6071. EVT VT = RetTys[I];
  6072. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6073. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6074. for (unsigned i = 0; i != NumRegs; ++i) {
  6075. ISD::InputArg MyFlags;
  6076. MyFlags.VT = RegisterVT;
  6077. MyFlags.ArgVT = VT;
  6078. MyFlags.Used = CLI.IsReturnValueUsed;
  6079. if (CLI.RetSExt)
  6080. MyFlags.Flags.setSExt();
  6081. if (CLI.RetZExt)
  6082. MyFlags.Flags.setZExt();
  6083. if (CLI.IsInReg)
  6084. MyFlags.Flags.setInReg();
  6085. CLI.Ins.push_back(MyFlags);
  6086. }
  6087. }
  6088. // Handle all of the outgoing arguments.
  6089. CLI.Outs.clear();
  6090. CLI.OutVals.clear();
  6091. ArgListTy &Args = CLI.Args;
  6092. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  6093. SmallVector<EVT, 4> ValueVTs;
  6094. ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
  6095. for (unsigned Value = 0, NumValues = ValueVTs.size();
  6096. Value != NumValues; ++Value) {
  6097. EVT VT = ValueVTs[Value];
  6098. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  6099. SDValue Op = SDValue(Args[i].Node.getNode(),
  6100. Args[i].Node.getResNo() + Value);
  6101. ISD::ArgFlagsTy Flags;
  6102. unsigned OriginalAlignment =
  6103. getDataLayout()->getABITypeAlignment(ArgTy);
  6104. if (Args[i].isZExt)
  6105. Flags.setZExt();
  6106. if (Args[i].isSExt)
  6107. Flags.setSExt();
  6108. if (Args[i].isInReg)
  6109. Flags.setInReg();
  6110. if (Args[i].isSRet)
  6111. Flags.setSRet();
  6112. if (Args[i].isByVal) {
  6113. Flags.setByVal();
  6114. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  6115. Type *ElementTy = Ty->getElementType();
  6116. Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
  6117. // For ByVal, alignment should come from FE. BE will guess if this
  6118. // info is not there but there are cases it cannot get right.
  6119. unsigned FrameAlign;
  6120. if (Args[i].Alignment)
  6121. FrameAlign = Args[i].Alignment;
  6122. else
  6123. FrameAlign = getByValTypeAlignment(ElementTy);
  6124. Flags.setByValAlign(FrameAlign);
  6125. }
  6126. if (Args[i].isNest)
  6127. Flags.setNest();
  6128. Flags.setOrigAlign(OriginalAlignment);
  6129. MVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6130. unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
  6131. SmallVector<SDValue, 4> Parts(NumParts);
  6132. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  6133. if (Args[i].isSExt)
  6134. ExtendKind = ISD::SIGN_EXTEND;
  6135. else if (Args[i].isZExt)
  6136. ExtendKind = ISD::ZERO_EXTEND;
  6137. // Conservatively only handle 'returned' on non-vectors for now
  6138. if (Args[i].isReturned && !Op.getValueType().isVector()) {
  6139. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  6140. "unexpected use of 'returned'");
  6141. // Before passing 'returned' to the target lowering code, ensure that
  6142. // either the register MVT and the actual EVT are the same size or that
  6143. // the return value and argument are extended in the same way; in these
  6144. // cases it's safe to pass the argument register value unchanged as the
  6145. // return register value (although it's at the target's option whether
  6146. // to do so)
  6147. // TODO: allow code generation to take advantage of partially preserved
  6148. // registers rather than clobbering the entire register when the
  6149. // parameter extension method is not compatible with the return
  6150. // extension method
  6151. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  6152. (ExtendKind != ISD::ANY_EXTEND &&
  6153. CLI.RetSExt == Args[i].isSExt && CLI.RetZExt == Args[i].isZExt))
  6154. Flags.setReturned();
  6155. }
  6156. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
  6157. PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
  6158. for (unsigned j = 0; j != NumParts; ++j) {
  6159. // if it isn't first piece, alignment must be 1
  6160. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  6161. i < CLI.NumFixedArgs,
  6162. i, j*Parts[j].getValueType().getStoreSize());
  6163. if (NumParts > 1 && j == 0)
  6164. MyFlags.Flags.setSplit();
  6165. else if (j != 0)
  6166. MyFlags.Flags.setOrigAlign(1);
  6167. CLI.Outs.push_back(MyFlags);
  6168. CLI.OutVals.push_back(Parts[j]);
  6169. }
  6170. }
  6171. }
  6172. SmallVector<SDValue, 4> InVals;
  6173. CLI.Chain = LowerCall(CLI, InVals);
  6174. // Verify that the target's LowerCall behaved as expected.
  6175. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  6176. "LowerCall didn't return a valid chain!");
  6177. assert((!CLI.IsTailCall || InVals.empty()) &&
  6178. "LowerCall emitted a return value for a tail call!");
  6179. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  6180. "LowerCall didn't emit the correct number of values!");
  6181. // For a tail call, the return value is merely live-out and there aren't
  6182. // any nodes in the DAG representing it. Return a special value to
  6183. // indicate that a tail call has been emitted and no more Instructions
  6184. // should be processed in the current block.
  6185. if (CLI.IsTailCall) {
  6186. CLI.DAG.setRoot(CLI.Chain);
  6187. return std::make_pair(SDValue(), SDValue());
  6188. }
  6189. DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  6190. assert(InVals[i].getNode() &&
  6191. "LowerCall emitted a null value!");
  6192. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  6193. "LowerCall emitted a value with the wrong type!");
  6194. });
  6195. // Collect the legal value parts into potentially illegal values
  6196. // that correspond to the original function's return values.
  6197. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6198. if (CLI.RetSExt)
  6199. AssertOp = ISD::AssertSext;
  6200. else if (CLI.RetZExt)
  6201. AssertOp = ISD::AssertZext;
  6202. SmallVector<SDValue, 4> ReturnValues;
  6203. unsigned CurReg = 0;
  6204. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  6205. EVT VT = RetTys[I];
  6206. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
  6207. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
  6208. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  6209. NumRegs, RegisterVT, VT, NULL,
  6210. AssertOp));
  6211. CurReg += NumRegs;
  6212. }
  6213. // For a function returning void, there is no return value. We can't create
  6214. // such a node, so we just return a null return value in that case. In
  6215. // that case, nothing will actually look at the value.
  6216. if (ReturnValues.empty())
  6217. return std::make_pair(SDValue(), CLI.Chain);
  6218. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  6219. CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
  6220. &ReturnValues[0], ReturnValues.size());
  6221. return std::make_pair(Res, CLI.Chain);
  6222. }
  6223. void TargetLowering::LowerOperationWrapper(SDNode *N,
  6224. SmallVectorImpl<SDValue> &Results,
  6225. SelectionDAG &DAG) const {
  6226. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  6227. if (Res.getNode())
  6228. Results.push_back(Res);
  6229. }
  6230. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  6231. llvm_unreachable("LowerOperation not implemented for this target!");
  6232. }
  6233. void
  6234. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  6235. SDValue Op = getNonRegisterValue(V);
  6236. assert((Op.getOpcode() != ISD::CopyFromReg ||
  6237. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  6238. "Copy from a reg to the same reg!");
  6239. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  6240. const TargetLowering *TLI = TM.getTargetLowering();
  6241. RegsForValue RFV(V->getContext(), *TLI, Reg, V->getType());
  6242. SDValue Chain = DAG.getEntryNode();
  6243. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, 0, V);
  6244. PendingExports.push_back(Chain);
  6245. }
  6246. #include "llvm/CodeGen/SelectionDAGISel.h"
  6247. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  6248. /// entry block, return true. This includes arguments used by switches, since
  6249. /// the switch may expand into multiple basic blocks.
  6250. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  6251. // With FastISel active, we may be splitting blocks, so force creation
  6252. // of virtual registers for all non-dead arguments.
  6253. if (FastISel)
  6254. return A->use_empty();
  6255. const BasicBlock *Entry = A->getParent()->begin();
  6256. for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
  6257. UI != E; ++UI) {
  6258. const User *U = *UI;
  6259. if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
  6260. return false; // Use not in entry block.
  6261. }
  6262. return true;
  6263. }
  6264. void SelectionDAGISel::LowerArguments(const Function &F) {
  6265. SelectionDAG &DAG = SDB->DAG;
  6266. SDLoc dl = SDB->getCurSDLoc();
  6267. const TargetLowering *TLI = getTargetLowering();
  6268. const DataLayout *TD = TLI->getDataLayout();
  6269. SmallVector<ISD::InputArg, 16> Ins;
  6270. if (!FuncInfo->CanLowerReturn) {
  6271. // Put in an sret pointer parameter before all the other parameters.
  6272. SmallVector<EVT, 1> ValueVTs;
  6273. ComputeValueVTs(*getTargetLowering(),
  6274. PointerType::getUnqual(F.getReturnType()), ValueVTs);
  6275. // NOTE: Assuming that a pointer will never break down to more than one VT
  6276. // or one register.
  6277. ISD::ArgFlagsTy Flags;
  6278. Flags.setSRet();
  6279. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  6280. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true, 0, 0);
  6281. Ins.push_back(RetArg);
  6282. }
  6283. // Set up the incoming argument description vector.
  6284. unsigned Idx = 1;
  6285. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
  6286. I != E; ++I, ++Idx) {
  6287. SmallVector<EVT, 4> ValueVTs;
  6288. ComputeValueVTs(*TLI, I->getType(), ValueVTs);
  6289. bool isArgValueUsed = !I->use_empty();
  6290. unsigned PartBase = 0;
  6291. for (unsigned Value = 0, NumValues = ValueVTs.size();
  6292. Value != NumValues; ++Value) {
  6293. EVT VT = ValueVTs[Value];
  6294. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  6295. ISD::ArgFlagsTy Flags;
  6296. unsigned OriginalAlignment =
  6297. TD->getABITypeAlignment(ArgTy);
  6298. if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  6299. Flags.setZExt();
  6300. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  6301. Flags.setSExt();
  6302. if (F.getAttributes().hasAttribute(Idx, Attribute::InReg))
  6303. Flags.setInReg();
  6304. if (F.getAttributes().hasAttribute(Idx, Attribute::StructRet))
  6305. Flags.setSRet();
  6306. if (F.getAttributes().hasAttribute(Idx, Attribute::ByVal)) {
  6307. Flags.setByVal();
  6308. PointerType *Ty = cast<PointerType>(I->getType());
  6309. Type *ElementTy = Ty->getElementType();
  6310. Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
  6311. // For ByVal, alignment should be passed from FE. BE will guess if
  6312. // this info is not there but there are cases it cannot get right.
  6313. unsigned FrameAlign;
  6314. if (F.getParamAlignment(Idx))
  6315. FrameAlign = F.getParamAlignment(Idx);
  6316. else
  6317. FrameAlign = TLI->getByValTypeAlignment(ElementTy);
  6318. Flags.setByValAlign(FrameAlign);
  6319. }
  6320. if (F.getAttributes().hasAttribute(Idx, Attribute::Nest))
  6321. Flags.setNest();
  6322. Flags.setOrigAlign(OriginalAlignment);
  6323. MVT RegisterVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6324. unsigned NumRegs = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  6325. for (unsigned i = 0; i != NumRegs; ++i) {
  6326. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  6327. Idx-1, PartBase+i*RegisterVT.getStoreSize());
  6328. if (NumRegs > 1 && i == 0)
  6329. MyFlags.Flags.setSplit();
  6330. // if it isn't first piece, alignment must be 1
  6331. else if (i > 0)
  6332. MyFlags.Flags.setOrigAlign(1);
  6333. Ins.push_back(MyFlags);
  6334. }
  6335. PartBase += VT.getStoreSize();
  6336. }
  6337. }
  6338. // Call the target to set up the argument values.
  6339. SmallVector<SDValue, 8> InVals;
  6340. SDValue NewRoot = TLI->LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
  6341. F.isVarArg(), Ins,
  6342. dl, DAG, InVals);
  6343. // Verify that the target's LowerFormalArguments behaved as expected.
  6344. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  6345. "LowerFormalArguments didn't return a valid chain!");
  6346. assert(InVals.size() == Ins.size() &&
  6347. "LowerFormalArguments didn't emit the correct number of values!");
  6348. DEBUG({
  6349. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  6350. assert(InVals[i].getNode() &&
  6351. "LowerFormalArguments emitted a null value!");
  6352. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  6353. "LowerFormalArguments emitted a value with the wrong type!");
  6354. }
  6355. });
  6356. // Update the DAG with the new chain value resulting from argument lowering.
  6357. DAG.setRoot(NewRoot);
  6358. // Set up the argument values.
  6359. unsigned i = 0;
  6360. Idx = 1;
  6361. if (!FuncInfo->CanLowerReturn) {
  6362. // Create a virtual register for the sret pointer, and put in a copy
  6363. // from the sret argument into it.
  6364. SmallVector<EVT, 1> ValueVTs;
  6365. ComputeValueVTs(*TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
  6366. MVT VT = ValueVTs[0].getSimpleVT();
  6367. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6368. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6369. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  6370. RegVT, VT, NULL, AssertOp);
  6371. MachineFunction& MF = SDB->DAG.getMachineFunction();
  6372. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  6373. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  6374. FuncInfo->DemoteRegister = SRetReg;
  6375. NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(),
  6376. SRetReg, ArgValue);
  6377. DAG.setRoot(NewRoot);
  6378. // i indexes lowered arguments. Bump it past the hidden sret argument.
  6379. // Idx indexes LLVM arguments. Don't touch it.
  6380. ++i;
  6381. }
  6382. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
  6383. ++I, ++Idx) {
  6384. SmallVector<SDValue, 4> ArgValues;
  6385. SmallVector<EVT, 4> ValueVTs;
  6386. ComputeValueVTs(*TLI, I->getType(), ValueVTs);
  6387. unsigned NumValues = ValueVTs.size();
  6388. // If this argument is unused then remember its value. It is used to generate
  6389. // debugging information.
  6390. if (I->use_empty() && NumValues) {
  6391. SDB->setUnusedArgValue(I, InVals[i]);
  6392. // Also remember any frame index for use in FastISel.
  6393. if (FrameIndexSDNode *FI =
  6394. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  6395. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6396. }
  6397. for (unsigned Val = 0; Val != NumValues; ++Val) {
  6398. EVT VT = ValueVTs[Val];
  6399. MVT PartVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  6400. unsigned NumParts = TLI->getNumRegisters(*CurDAG->getContext(), VT);
  6401. if (!I->use_empty()) {
  6402. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  6403. if (F.getAttributes().hasAttribute(Idx, Attribute::SExt))
  6404. AssertOp = ISD::AssertSext;
  6405. else if (F.getAttributes().hasAttribute(Idx, Attribute::ZExt))
  6406. AssertOp = ISD::AssertZext;
  6407. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
  6408. NumParts, PartVT, VT,
  6409. NULL, AssertOp));
  6410. }
  6411. i += NumParts;
  6412. }
  6413. // We don't need to do anything else for unused arguments.
  6414. if (ArgValues.empty())
  6415. continue;
  6416. // Note down frame index.
  6417. if (FrameIndexSDNode *FI =
  6418. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  6419. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6420. SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
  6421. SDB->getCurSDLoc());
  6422. SDB->setValue(I, Res);
  6423. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  6424. if (LoadSDNode *LNode =
  6425. dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
  6426. if (FrameIndexSDNode *FI =
  6427. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  6428. FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
  6429. }
  6430. // If this argument is live outside of the entry block, insert a copy from
  6431. // wherever we got it to the vreg that other BB's will reference it as.
  6432. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  6433. // If we can, though, try to skip creating an unnecessary vreg.
  6434. // FIXME: This isn't very clean... it would be nice to make this more
  6435. // general. It's also subtly incompatible with the hacks FastISel
  6436. // uses with vregs.
  6437. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  6438. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  6439. FuncInfo->ValueMap[I] = Reg;
  6440. continue;
  6441. }
  6442. }
  6443. if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
  6444. FuncInfo->InitializeRegForValue(I);
  6445. SDB->CopyToExportRegsIfNeeded(I);
  6446. }
  6447. }
  6448. assert(i == InVals.size() && "Argument register count mismatch!");
  6449. // Finally, if the target has anything special to do, allow it to do so.
  6450. // FIXME: this should insert code into the DAG!
  6451. EmitFunctionEntryCode();
  6452. }
  6453. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  6454. /// ensure constants are generated when needed. Remember the virtual registers
  6455. /// that need to be added to the Machine PHI nodes as input. We cannot just
  6456. /// directly add them, because expansion might result in multiple MBB's for one
  6457. /// BB. As such, the start of the BB might correspond to a different MBB than
  6458. /// the end.
  6459. ///
  6460. void
  6461. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  6462. const TerminatorInst *TI = LLVMBB->getTerminator();
  6463. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  6464. // Check successor nodes' PHI nodes that expect a constant to be available
  6465. // from this block.
  6466. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  6467. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  6468. if (!isa<PHINode>(SuccBB->begin())) continue;
  6469. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  6470. // If this terminator has multiple identical successors (common for
  6471. // switches), only handle each succ once.
  6472. if (!SuccsHandled.insert(SuccMBB)) continue;
  6473. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  6474. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  6475. // nodes and Machine PHI nodes, but the incoming operands have not been
  6476. // emitted yet.
  6477. for (BasicBlock::const_iterator I = SuccBB->begin();
  6478. const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  6479. // Ignore dead phi's.
  6480. if (PN->use_empty()) continue;
  6481. // Skip empty types
  6482. if (PN->getType()->isEmptyTy())
  6483. continue;
  6484. unsigned Reg;
  6485. const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  6486. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  6487. unsigned &RegOut = ConstantsOut[C];
  6488. if (RegOut == 0) {
  6489. RegOut = FuncInfo.CreateRegs(C->getType());
  6490. CopyValueToVirtualRegister(C, RegOut);
  6491. }
  6492. Reg = RegOut;
  6493. } else {
  6494. DenseMap<const Value *, unsigned>::iterator I =
  6495. FuncInfo.ValueMap.find(PHIOp);
  6496. if (I != FuncInfo.ValueMap.end())
  6497. Reg = I->second;
  6498. else {
  6499. assert(isa<AllocaInst>(PHIOp) &&
  6500. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  6501. "Didn't codegen value into a register!??");
  6502. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  6503. CopyValueToVirtualRegister(PHIOp, Reg);
  6504. }
  6505. }
  6506. // Remember that this register needs to added to the machine PHI node as
  6507. // the input for this MBB.
  6508. SmallVector<EVT, 4> ValueVTs;
  6509. const TargetLowering *TLI = TM.getTargetLowering();
  6510. ComputeValueVTs(*TLI, PN->getType(), ValueVTs);
  6511. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  6512. EVT VT = ValueVTs[vti];
  6513. unsigned NumRegisters = TLI->getNumRegisters(*DAG.getContext(), VT);
  6514. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  6515. FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
  6516. Reg += NumRegisters;
  6517. }
  6518. }
  6519. }
  6520. ConstantsOut.clear();
  6521. }
  6522. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  6523. /// is 0.
  6524. MachineBasicBlock *
  6525. SelectionDAGBuilder::StackProtectorDescriptor::
  6526. AddSuccessorMBB(const BasicBlock *BB,
  6527. MachineBasicBlock *ParentMBB,
  6528. MachineBasicBlock *SuccMBB) {
  6529. // If SuccBB has not been created yet, create it.
  6530. if (!SuccMBB) {
  6531. MachineFunction *MF = ParentMBB->getParent();
  6532. MachineFunction::iterator BBI = ParentMBB;
  6533. SuccMBB = MF->CreateMachineBasicBlock(BB);
  6534. MF->insert(++BBI, SuccMBB);
  6535. }
  6536. // Add it as a successor of ParentMBB.
  6537. ParentMBB->addSuccessor(SuccMBB);
  6538. return SuccMBB;
  6539. }