SelectionDAGBuilder.cpp 296 KB

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