SelectionDAGBuilder.cpp 409 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541
  1. //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "SelectionDAGBuilder.h"
  13. #include "SDNodeDbgValue.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Analysis/AliasAnalysis.h"
  29. #include "llvm/Analysis/BranchProbabilityInfo.h"
  30. #include "llvm/Analysis/ConstantFolding.h"
  31. #include "llvm/Analysis/EHPersonalities.h"
  32. #include "llvm/Analysis/Loads.h"
  33. #include "llvm/Analysis/MemoryLocation.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/ValueTracking.h"
  36. #include "llvm/Analysis/VectorUtils.h"
  37. #include "llvm/CodeGen/Analysis.h"
  38. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  39. #include "llvm/CodeGen/GCMetadata.h"
  40. #include "llvm/CodeGen/ISDOpcodes.h"
  41. #include "llvm/CodeGen/MachineBasicBlock.h"
  42. #include "llvm/CodeGen/MachineFrameInfo.h"
  43. #include "llvm/CodeGen/MachineFunction.h"
  44. #include "llvm/CodeGen/MachineInstr.h"
  45. #include "llvm/CodeGen/MachineInstrBuilder.h"
  46. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  47. #include "llvm/CodeGen/MachineMemOperand.h"
  48. #include "llvm/CodeGen/MachineModuleInfo.h"
  49. #include "llvm/CodeGen/MachineOperand.h"
  50. #include "llvm/CodeGen/MachineRegisterInfo.h"
  51. #include "llvm/CodeGen/RuntimeLibcalls.h"
  52. #include "llvm/CodeGen/SelectionDAG.h"
  53. #include "llvm/CodeGen/SelectionDAGNodes.h"
  54. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  55. #include "llvm/CodeGen/StackMaps.h"
  56. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  57. #include "llvm/CodeGen/TargetFrameLowering.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetLowering.h"
  60. #include "llvm/CodeGen/TargetOpcodes.h"
  61. #include "llvm/CodeGen/TargetRegisterInfo.h"
  62. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  63. #include "llvm/CodeGen/ValueTypes.h"
  64. #include "llvm/CodeGen/WinEHFuncInfo.h"
  65. #include "llvm/IR/Argument.h"
  66. #include "llvm/IR/Attributes.h"
  67. #include "llvm/IR/BasicBlock.h"
  68. #include "llvm/IR/CFG.h"
  69. #include "llvm/IR/CallSite.h"
  70. #include "llvm/IR/CallingConv.h"
  71. #include "llvm/IR/Constant.h"
  72. #include "llvm/IR/ConstantRange.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfoMetadata.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/InlineAsm.h"
  81. #include "llvm/IR/InstrTypes.h"
  82. #include "llvm/IR/Instruction.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/Intrinsics.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Metadata.h"
  88. #include "llvm/IR/Module.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/PatternMatch.h"
  91. #include "llvm/IR/Statepoint.h"
  92. #include "llvm/IR/Type.h"
  93. #include "llvm/IR/User.h"
  94. #include "llvm/IR/Value.h"
  95. #include "llvm/MC/MCContext.h"
  96. #include "llvm/MC/MCSymbol.h"
  97. #include "llvm/Support/AtomicOrdering.h"
  98. #include "llvm/Support/BranchProbability.h"
  99. #include "llvm/Support/Casting.h"
  100. #include "llvm/Support/CodeGen.h"
  101. #include "llvm/Support/CommandLine.h"
  102. #include "llvm/Support/Compiler.h"
  103. #include "llvm/Support/Debug.h"
  104. #include "llvm/Support/ErrorHandling.h"
  105. #include "llvm/Support/MachineValueType.h"
  106. #include "llvm/Support/MathExtras.h"
  107. #include "llvm/Support/raw_ostream.h"
  108. #include "llvm/Target/TargetIntrinsicInfo.h"
  109. #include "llvm/Target/TargetMachine.h"
  110. #include "llvm/Target/TargetOptions.h"
  111. #include "llvm/Transforms/Utils/Local.h"
  112. #include <algorithm>
  113. #include <cassert>
  114. #include <cstddef>
  115. #include <cstdint>
  116. #include <cstring>
  117. #include <iterator>
  118. #include <limits>
  119. #include <numeric>
  120. #include <tuple>
  121. #include <utility>
  122. #include <vector>
  123. using namespace llvm;
  124. using namespace PatternMatch;
  125. using namespace SwitchCG;
  126. #define DEBUG_TYPE "isel"
  127. /// LimitFloatPrecision - Generate low-precision inline sequences for
  128. /// some float libcalls (6, 8 or 12 bits).
  129. static unsigned LimitFloatPrecision;
  130. static cl::opt<unsigned, true>
  131. LimitFPPrecision("limit-float-precision",
  132. cl::desc("Generate low-precision inline sequences "
  133. "for some float libcalls"),
  134. cl::location(LimitFloatPrecision), cl::Hidden,
  135. cl::init(0));
  136. static cl::opt<unsigned> SwitchPeelThreshold(
  137. "switch-peel-threshold", cl::Hidden, cl::init(66),
  138. cl::desc("Set the case probability threshold for peeling the case from a "
  139. "switch statement. A value greater than 100 will void this "
  140. "optimization"));
  141. // Limit the width of DAG chains. This is important in general to prevent
  142. // DAG-based analysis from blowing up. For example, alias analysis and
  143. // load clustering may not complete in reasonable time. It is difficult to
  144. // recognize and avoid this situation within each individual analysis, and
  145. // future analyses are likely to have the same behavior. Limiting DAG width is
  146. // the safe approach and will be especially important with global DAGs.
  147. //
  148. // MaxParallelChains default is arbitrarily high to avoid affecting
  149. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  150. // sequence over this should have been converted to llvm.memcpy by the
  151. // frontend. It is easy to induce this behavior with .ll code such as:
  152. // %buffer = alloca [4096 x i8]
  153. // %data = load [4096 x i8]* %argPtr
  154. // store [4096 x i8] %data, [4096 x i8]* %buffer
  155. static const unsigned MaxParallelChains = 64;
  156. // Return the calling convention if the Value passed requires ABI mangling as it
  157. // is a parameter to a function or a return value from a function which is not
  158. // an intrinsic.
  159. static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
  160. if (auto *R = dyn_cast<ReturnInst>(V))
  161. return R->getParent()->getParent()->getCallingConv();
  162. if (auto *CI = dyn_cast<CallInst>(V)) {
  163. const bool IsInlineAsm = CI->isInlineAsm();
  164. const bool IsIndirectFunctionCall =
  165. !IsInlineAsm && !CI->getCalledFunction();
  166. // It is possible that the call instruction is an inline asm statement or an
  167. // indirect function call in which case the return value of
  168. // getCalledFunction() would be nullptr.
  169. const bool IsInstrinsicCall =
  170. !IsInlineAsm && !IsIndirectFunctionCall &&
  171. CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
  172. if (!IsInlineAsm && !IsInstrinsicCall)
  173. return CI->getCallingConv();
  174. }
  175. return None;
  176. }
  177. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  178. const SDValue *Parts, unsigned NumParts,
  179. MVT PartVT, EVT ValueVT, const Value *V,
  180. Optional<CallingConv::ID> CC);
  181. /// getCopyFromParts - Create a value that contains the specified legal parts
  182. /// combined into the value they represent. If the parts combine to a type
  183. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  184. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  185. /// (ISD::AssertSext).
  186. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  187. const SDValue *Parts, unsigned NumParts,
  188. MVT PartVT, EVT ValueVT, const Value *V,
  189. Optional<CallingConv::ID> CC = None,
  190. Optional<ISD::NodeType> AssertOp = None) {
  191. if (ValueVT.isVector())
  192. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  193. CC);
  194. assert(NumParts > 0 && "No parts to assemble!");
  195. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  196. SDValue Val = Parts[0];
  197. if (NumParts > 1) {
  198. // Assemble the value from multiple parts.
  199. if (ValueVT.isInteger()) {
  200. unsigned PartBits = PartVT.getSizeInBits();
  201. unsigned ValueBits = ValueVT.getSizeInBits();
  202. // Assemble the power of 2 part.
  203. unsigned RoundParts =
  204. (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
  205. unsigned RoundBits = PartBits * RoundParts;
  206. EVT RoundVT = RoundBits == ValueBits ?
  207. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  208. SDValue Lo, Hi;
  209. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  210. if (RoundParts > 2) {
  211. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  212. PartVT, HalfVT, V);
  213. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  214. RoundParts / 2, PartVT, HalfVT, V);
  215. } else {
  216. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  217. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  218. }
  219. if (DAG.getDataLayout().isBigEndian())
  220. std::swap(Lo, Hi);
  221. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  222. if (RoundParts < NumParts) {
  223. // Assemble the trailing non-power-of-2 part.
  224. unsigned OddParts = NumParts - RoundParts;
  225. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  226. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  227. OddVT, V, CC);
  228. // Combine the round and odd parts.
  229. Lo = Val;
  230. if (DAG.getDataLayout().isBigEndian())
  231. std::swap(Lo, Hi);
  232. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  233. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  234. Hi =
  235. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  236. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  237. TLI.getPointerTy(DAG.getDataLayout())));
  238. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  239. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  240. }
  241. } else if (PartVT.isFloatingPoint()) {
  242. // FP split into multiple FP parts (for ppcf128)
  243. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  244. "Unexpected split");
  245. SDValue Lo, Hi;
  246. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  247. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  248. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  249. std::swap(Lo, Hi);
  250. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  251. } else {
  252. // FP split into integer parts (soft fp)
  253. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  254. !PartVT.isVector() && "Unexpected split");
  255. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  256. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  257. }
  258. }
  259. // There is now one part, held in Val. Correct it to match ValueVT.
  260. // PartEVT is the type of the register class that holds the value.
  261. // ValueVT is the type of the inline asm operation.
  262. EVT PartEVT = Val.getValueType();
  263. if (PartEVT == ValueVT)
  264. return Val;
  265. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  266. ValueVT.bitsLT(PartEVT)) {
  267. // For an FP value in an integer part, we need to truncate to the right
  268. // width first.
  269. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  270. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  271. }
  272. // Handle types that have the same size.
  273. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  274. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  275. // Handle types with different sizes.
  276. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  277. if (ValueVT.bitsLT(PartEVT)) {
  278. // For a truncate, see if we have any information to
  279. // indicate whether the truncated bits will always be
  280. // zero or sign-extension.
  281. if (AssertOp.hasValue())
  282. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  283. DAG.getValueType(ValueVT));
  284. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  285. }
  286. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  287. }
  288. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  289. // FP_ROUND's are always exact here.
  290. if (ValueVT.bitsLT(Val.getValueType()))
  291. return DAG.getNode(
  292. ISD::FP_ROUND, DL, ValueVT, Val,
  293. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  294. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  295. }
  296. // Handle MMX to a narrower integer type by bitcasting MMX to integer and
  297. // then truncating.
  298. if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
  299. ValueVT.bitsLT(PartEVT)) {
  300. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
  301. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  302. }
  303. report_fatal_error("Unknown mismatch in getCopyFromParts!");
  304. }
  305. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  306. const Twine &ErrMsg) {
  307. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  308. if (!V)
  309. return Ctx.emitError(ErrMsg);
  310. const char *AsmError = ", possible invalid constraint for vector type";
  311. if (const CallInst *CI = dyn_cast<CallInst>(I))
  312. if (isa<InlineAsm>(CI->getCalledValue()))
  313. return Ctx.emitError(I, ErrMsg + AsmError);
  314. return Ctx.emitError(I, ErrMsg);
  315. }
  316. /// getCopyFromPartsVector - Create a value that contains the specified legal
  317. /// parts combined into the value they represent. If the parts combine to a
  318. /// type larger than ValueVT then AssertOp can be used to specify whether the
  319. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  320. /// ValueVT (ISD::AssertSext).
  321. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  322. const SDValue *Parts, unsigned NumParts,
  323. MVT PartVT, EVT ValueVT, const Value *V,
  324. Optional<CallingConv::ID> CallConv) {
  325. assert(ValueVT.isVector() && "Not a vector value");
  326. assert(NumParts > 0 && "No parts to assemble!");
  327. const bool IsABIRegCopy = CallConv.hasValue();
  328. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  329. SDValue Val = Parts[0];
  330. // Handle a multi-element vector.
  331. if (NumParts > 1) {
  332. EVT IntermediateVT;
  333. MVT RegisterVT;
  334. unsigned NumIntermediates;
  335. unsigned NumRegs;
  336. if (IsABIRegCopy) {
  337. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  338. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  339. NumIntermediates, RegisterVT);
  340. } else {
  341. NumRegs =
  342. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  343. NumIntermediates, RegisterVT);
  344. }
  345. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  346. NumParts = NumRegs; // Silence a compiler warning.
  347. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  348. assert(RegisterVT.getSizeInBits() ==
  349. Parts[0].getSimpleValueType().getSizeInBits() &&
  350. "Part type sizes don't match!");
  351. // Assemble the parts into intermediate operands.
  352. SmallVector<SDValue, 8> Ops(NumIntermediates);
  353. if (NumIntermediates == NumParts) {
  354. // If the register was not expanded, truncate or copy the value,
  355. // as appropriate.
  356. for (unsigned i = 0; i != NumParts; ++i)
  357. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  358. PartVT, IntermediateVT, V);
  359. } else if (NumParts > 0) {
  360. // If the intermediate type was expanded, build the intermediate
  361. // operands from the parts.
  362. assert(NumParts % NumIntermediates == 0 &&
  363. "Must expand into a divisible number of parts!");
  364. unsigned Factor = NumParts / NumIntermediates;
  365. for (unsigned i = 0; i != NumIntermediates; ++i)
  366. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  367. PartVT, IntermediateVT, V);
  368. }
  369. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  370. // intermediate operands.
  371. EVT BuiltVectorTy =
  372. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  373. (IntermediateVT.isVector()
  374. ? IntermediateVT.getVectorNumElements() * NumParts
  375. : NumIntermediates));
  376. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  377. : ISD::BUILD_VECTOR,
  378. DL, BuiltVectorTy, Ops);
  379. }
  380. // There is now one part, held in Val. Correct it to match ValueVT.
  381. EVT PartEVT = Val.getValueType();
  382. if (PartEVT == ValueVT)
  383. return Val;
  384. if (PartEVT.isVector()) {
  385. // If the element type of the source/dest vectors are the same, but the
  386. // parts vector has more elements than the value vector, then we have a
  387. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  388. // elements we want.
  389. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  390. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  391. "Cannot narrow, it would be a lossy transformation");
  392. return DAG.getNode(
  393. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  394. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  395. }
  396. // Vector/Vector bitcast.
  397. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  398. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  399. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  400. "Cannot handle this kind of promotion");
  401. // Promoted vector extract
  402. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  403. }
  404. // Trivial bitcast if the types are the same size and the destination
  405. // vector type is legal.
  406. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  407. TLI.isTypeLegal(ValueVT))
  408. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  409. if (ValueVT.getVectorNumElements() != 1) {
  410. // Certain ABIs require that vectors are passed as integers. For vectors
  411. // are the same size, this is an obvious bitcast.
  412. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  413. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  414. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  415. // Bitcast Val back the original type and extract the corresponding
  416. // vector we want.
  417. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  418. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  419. ValueVT.getVectorElementType(), Elts);
  420. Val = DAG.getBitcast(WiderVecType, Val);
  421. return DAG.getNode(
  422. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  423. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  424. }
  425. diagnosePossiblyInvalidConstraint(
  426. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  427. return DAG.getUNDEF(ValueVT);
  428. }
  429. // Handle cases such as i8 -> <1 x i1>
  430. EVT ValueSVT = ValueVT.getVectorElementType();
  431. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  432. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  433. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  434. return DAG.getBuildVector(ValueVT, DL, Val);
  435. }
  436. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  437. SDValue Val, SDValue *Parts, unsigned NumParts,
  438. MVT PartVT, const Value *V,
  439. Optional<CallingConv::ID> CallConv);
  440. /// getCopyToParts - Create a series of nodes that contain the specified value
  441. /// split into legal parts. If the parts contain more bits than Val, then, for
  442. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  443. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  444. SDValue *Parts, unsigned NumParts, MVT PartVT,
  445. const Value *V,
  446. Optional<CallingConv::ID> CallConv = None,
  447. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  448. EVT ValueVT = Val.getValueType();
  449. // Handle the vector case separately.
  450. if (ValueVT.isVector())
  451. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  452. CallConv);
  453. unsigned PartBits = PartVT.getSizeInBits();
  454. unsigned OrigNumParts = NumParts;
  455. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  456. "Copying to an illegal type!");
  457. if (NumParts == 0)
  458. return;
  459. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  460. EVT PartEVT = PartVT;
  461. if (PartEVT == ValueVT) {
  462. assert(NumParts == 1 && "No-op copy with multiple parts!");
  463. Parts[0] = Val;
  464. return;
  465. }
  466. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  467. // If the parts cover more bits than the value has, promote the value.
  468. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  469. assert(NumParts == 1 && "Do not know what to promote to!");
  470. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  471. } else {
  472. if (ValueVT.isFloatingPoint()) {
  473. // FP values need to be bitcast, then extended if they are being put
  474. // into a larger container.
  475. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  476. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  477. }
  478. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  479. ValueVT.isInteger() &&
  480. "Unknown mismatch!");
  481. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  482. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  483. if (PartVT == MVT::x86mmx)
  484. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  485. }
  486. } else if (PartBits == ValueVT.getSizeInBits()) {
  487. // Different types of the same size.
  488. assert(NumParts == 1 && PartEVT != ValueVT);
  489. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  490. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  491. // If the parts cover less bits than value has, truncate the value.
  492. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  493. ValueVT.isInteger() &&
  494. "Unknown mismatch!");
  495. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  496. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  497. if (PartVT == MVT::x86mmx)
  498. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  499. }
  500. // The value may have changed - recompute ValueVT.
  501. ValueVT = Val.getValueType();
  502. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  503. "Failed to tile the value with PartVT!");
  504. if (NumParts == 1) {
  505. if (PartEVT != ValueVT) {
  506. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  507. "scalar-to-vector conversion failed");
  508. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  509. }
  510. Parts[0] = Val;
  511. return;
  512. }
  513. // Expand the value into multiple parts.
  514. if (NumParts & (NumParts - 1)) {
  515. // The number of parts is not a power of 2. Split off and copy the tail.
  516. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  517. "Do not know what to expand to!");
  518. unsigned RoundParts = 1 << Log2_32(NumParts);
  519. unsigned RoundBits = RoundParts * PartBits;
  520. unsigned OddParts = NumParts - RoundParts;
  521. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  522. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  523. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  524. CallConv);
  525. if (DAG.getDataLayout().isBigEndian())
  526. // The odd parts were reversed by getCopyToParts - unreverse them.
  527. std::reverse(Parts + RoundParts, Parts + NumParts);
  528. NumParts = RoundParts;
  529. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  530. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  531. }
  532. // The number of parts is a power of 2. Repeatedly bisect the value using
  533. // EXTRACT_ELEMENT.
  534. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  535. EVT::getIntegerVT(*DAG.getContext(),
  536. ValueVT.getSizeInBits()),
  537. Val);
  538. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  539. for (unsigned i = 0; i < NumParts; i += StepSize) {
  540. unsigned ThisBits = StepSize * PartBits / 2;
  541. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  542. SDValue &Part0 = Parts[i];
  543. SDValue &Part1 = Parts[i+StepSize/2];
  544. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  545. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  546. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  547. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  548. if (ThisBits == PartBits && ThisVT != PartVT) {
  549. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  550. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  551. }
  552. }
  553. }
  554. if (DAG.getDataLayout().isBigEndian())
  555. std::reverse(Parts, Parts + OrigNumParts);
  556. }
  557. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  558. SDValue Val, const SDLoc &DL, EVT PartVT) {
  559. if (!PartVT.isVector())
  560. return SDValue();
  561. EVT ValueVT = Val.getValueType();
  562. unsigned PartNumElts = PartVT.getVectorNumElements();
  563. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  564. if (PartNumElts > ValueNumElts &&
  565. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  566. EVT ElementVT = PartVT.getVectorElementType();
  567. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  568. // undef elements.
  569. SmallVector<SDValue, 16> Ops;
  570. DAG.ExtractVectorElements(Val, Ops);
  571. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  572. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  573. Ops.push_back(EltUndef);
  574. // FIXME: Use CONCAT for 2x -> 4x.
  575. return DAG.getBuildVector(PartVT, DL, Ops);
  576. }
  577. return SDValue();
  578. }
  579. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  580. /// value split into legal parts.
  581. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  582. SDValue Val, SDValue *Parts, unsigned NumParts,
  583. MVT PartVT, const Value *V,
  584. Optional<CallingConv::ID> CallConv) {
  585. EVT ValueVT = Val.getValueType();
  586. assert(ValueVT.isVector() && "Not a vector");
  587. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  588. const bool IsABIRegCopy = CallConv.hasValue();
  589. if (NumParts == 1) {
  590. EVT PartEVT = PartVT;
  591. if (PartEVT == ValueVT) {
  592. // Nothing to do.
  593. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  594. // Bitconvert vector->vector case.
  595. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  596. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  597. Val = Widened;
  598. } else if (PartVT.isVector() &&
  599. PartEVT.getVectorElementType().bitsGE(
  600. ValueVT.getVectorElementType()) &&
  601. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  602. // Promoted vector extract
  603. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  604. } else {
  605. if (ValueVT.getVectorNumElements() == 1) {
  606. Val = DAG.getNode(
  607. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  608. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  609. } else {
  610. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  611. "lossy conversion of vector to scalar type");
  612. EVT IntermediateType =
  613. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  614. Val = DAG.getBitcast(IntermediateType, Val);
  615. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  616. }
  617. }
  618. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  619. Parts[0] = Val;
  620. return;
  621. }
  622. // Handle a multi-element vector.
  623. EVT IntermediateVT;
  624. MVT RegisterVT;
  625. unsigned NumIntermediates;
  626. unsigned NumRegs;
  627. if (IsABIRegCopy) {
  628. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  629. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  630. NumIntermediates, RegisterVT);
  631. } else {
  632. NumRegs =
  633. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  634. NumIntermediates, RegisterVT);
  635. }
  636. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  637. NumParts = NumRegs; // Silence a compiler warning.
  638. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  639. unsigned IntermediateNumElts = IntermediateVT.isVector() ?
  640. IntermediateVT.getVectorNumElements() : 1;
  641. // Convert the vector to the appropiate type if necessary.
  642. unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
  643. EVT BuiltVectorTy = EVT::getVectorVT(
  644. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  645. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  646. if (ValueVT != BuiltVectorTy) {
  647. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  648. Val = Widened;
  649. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  650. }
  651. // Split the vector into intermediate operands.
  652. SmallVector<SDValue, 8> Ops(NumIntermediates);
  653. for (unsigned i = 0; i != NumIntermediates; ++i) {
  654. if (IntermediateVT.isVector()) {
  655. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  656. DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
  657. } else {
  658. Ops[i] = DAG.getNode(
  659. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  660. DAG.getConstant(i, DL, IdxVT));
  661. }
  662. }
  663. // Split the intermediate operands into legal parts.
  664. if (NumParts == NumIntermediates) {
  665. // If the register was not expanded, promote or copy the value,
  666. // as appropriate.
  667. for (unsigned i = 0; i != NumParts; ++i)
  668. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  669. } else if (NumParts > 0) {
  670. // If the intermediate type was expanded, split each the value into
  671. // legal parts.
  672. assert(NumIntermediates != 0 && "division by zero");
  673. assert(NumParts % NumIntermediates == 0 &&
  674. "Must expand into a divisible number of parts!");
  675. unsigned Factor = NumParts / NumIntermediates;
  676. for (unsigned i = 0; i != NumIntermediates; ++i)
  677. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  678. CallConv);
  679. }
  680. }
  681. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  682. EVT valuevt, Optional<CallingConv::ID> CC)
  683. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  684. RegCount(1, regs.size()), CallConv(CC) {}
  685. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  686. const DataLayout &DL, unsigned Reg, Type *Ty,
  687. Optional<CallingConv::ID> CC) {
  688. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  689. CallConv = CC;
  690. for (EVT ValueVT : ValueVTs) {
  691. unsigned NumRegs =
  692. isABIMangled()
  693. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  694. : TLI.getNumRegisters(Context, ValueVT);
  695. MVT RegisterVT =
  696. isABIMangled()
  697. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  698. : TLI.getRegisterType(Context, ValueVT);
  699. for (unsigned i = 0; i != NumRegs; ++i)
  700. Regs.push_back(Reg + i);
  701. RegVTs.push_back(RegisterVT);
  702. RegCount.push_back(NumRegs);
  703. Reg += NumRegs;
  704. }
  705. }
  706. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  707. FunctionLoweringInfo &FuncInfo,
  708. const SDLoc &dl, SDValue &Chain,
  709. SDValue *Flag, const Value *V) const {
  710. // A Value with type {} or [0 x %t] needs no registers.
  711. if (ValueVTs.empty())
  712. return SDValue();
  713. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  714. // Assemble the legal parts into the final values.
  715. SmallVector<SDValue, 4> Values(ValueVTs.size());
  716. SmallVector<SDValue, 8> Parts;
  717. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  718. // Copy the legal parts from the registers.
  719. EVT ValueVT = ValueVTs[Value];
  720. unsigned NumRegs = RegCount[Value];
  721. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  722. *DAG.getContext(),
  723. CallConv.getValue(), RegVTs[Value])
  724. : RegVTs[Value];
  725. Parts.resize(NumRegs);
  726. for (unsigned i = 0; i != NumRegs; ++i) {
  727. SDValue P;
  728. if (!Flag) {
  729. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  730. } else {
  731. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  732. *Flag = P.getValue(2);
  733. }
  734. Chain = P.getValue(1);
  735. Parts[i] = P;
  736. // If the source register was virtual and if we know something about it,
  737. // add an assert node.
  738. if (!Register::isVirtualRegister(Regs[Part + i]) ||
  739. !RegisterVT.isInteger())
  740. continue;
  741. const FunctionLoweringInfo::LiveOutInfo *LOI =
  742. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  743. if (!LOI)
  744. continue;
  745. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  746. unsigned NumSignBits = LOI->NumSignBits;
  747. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  748. if (NumZeroBits == RegSize) {
  749. // The current value is a zero.
  750. // Explicitly express that as it would be easier for
  751. // optimizations to kick in.
  752. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  753. continue;
  754. }
  755. // FIXME: We capture more information than the dag can represent. For
  756. // now, just use the tightest assertzext/assertsext possible.
  757. bool isSExt;
  758. EVT FromVT(MVT::Other);
  759. if (NumZeroBits) {
  760. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  761. isSExt = false;
  762. } else if (NumSignBits > 1) {
  763. FromVT =
  764. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  765. isSExt = true;
  766. } else {
  767. continue;
  768. }
  769. // Add an assertion node.
  770. assert(FromVT != MVT::Other);
  771. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  772. RegisterVT, P, DAG.getValueType(FromVT));
  773. }
  774. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  775. RegisterVT, ValueVT, V, CallConv);
  776. Part += NumRegs;
  777. Parts.clear();
  778. }
  779. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  780. }
  781. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  782. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  783. const Value *V,
  784. ISD::NodeType PreferredExtendType) const {
  785. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  786. ISD::NodeType ExtendKind = PreferredExtendType;
  787. // Get the list of the values's legal parts.
  788. unsigned NumRegs = Regs.size();
  789. SmallVector<SDValue, 8> Parts(NumRegs);
  790. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  791. unsigned NumParts = RegCount[Value];
  792. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  793. *DAG.getContext(),
  794. CallConv.getValue(), RegVTs[Value])
  795. : RegVTs[Value];
  796. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  797. ExtendKind = ISD::ZERO_EXTEND;
  798. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  799. NumParts, RegisterVT, V, CallConv, ExtendKind);
  800. Part += NumParts;
  801. }
  802. // Copy the parts into the registers.
  803. SmallVector<SDValue, 8> Chains(NumRegs);
  804. for (unsigned i = 0; i != NumRegs; ++i) {
  805. SDValue Part;
  806. if (!Flag) {
  807. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  808. } else {
  809. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  810. *Flag = Part.getValue(1);
  811. }
  812. Chains[i] = Part.getValue(0);
  813. }
  814. if (NumRegs == 1 || Flag)
  815. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  816. // flagged to it. That is the CopyToReg nodes and the user are considered
  817. // a single scheduling unit. If we create a TokenFactor and return it as
  818. // chain, then the TokenFactor is both a predecessor (operand) of the
  819. // user as well as a successor (the TF operands are flagged to the user).
  820. // c1, f1 = CopyToReg
  821. // c2, f2 = CopyToReg
  822. // c3 = TokenFactor c1, c2
  823. // ...
  824. // = op c3, ..., f2
  825. Chain = Chains[NumRegs-1];
  826. else
  827. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  828. }
  829. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  830. unsigned MatchingIdx, const SDLoc &dl,
  831. SelectionDAG &DAG,
  832. std::vector<SDValue> &Ops) const {
  833. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  834. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  835. if (HasMatching)
  836. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  837. else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
  838. // Put the register class of the virtual registers in the flag word. That
  839. // way, later passes can recompute register class constraints for inline
  840. // assembly as well as normal instructions.
  841. // Don't do this for tied operands that can use the regclass information
  842. // from the def.
  843. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  844. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  845. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  846. }
  847. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  848. Ops.push_back(Res);
  849. if (Code == InlineAsm::Kind_Clobber) {
  850. // Clobbers should always have a 1:1 mapping with registers, and may
  851. // reference registers that have illegal (e.g. vector) types. Hence, we
  852. // shouldn't try to apply any sort of splitting logic to them.
  853. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  854. "No 1:1 mapping from clobbers to regs?");
  855. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  856. (void)SP;
  857. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  858. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  859. assert(
  860. (Regs[I] != SP ||
  861. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  862. "If we clobbered the stack pointer, MFI should know about it.");
  863. }
  864. return;
  865. }
  866. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  867. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  868. MVT RegisterVT = RegVTs[Value];
  869. for (unsigned i = 0; i != NumRegs; ++i) {
  870. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  871. unsigned TheReg = Regs[Reg++];
  872. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  873. }
  874. }
  875. }
  876. SmallVector<std::pair<unsigned, unsigned>, 4>
  877. RegsForValue::getRegsAndSizes() const {
  878. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  879. unsigned I = 0;
  880. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  881. unsigned RegCount = std::get<0>(CountAndVT);
  882. MVT RegisterVT = std::get<1>(CountAndVT);
  883. unsigned RegisterSize = RegisterVT.getSizeInBits();
  884. for (unsigned E = I + RegCount; I != E; ++I)
  885. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  886. }
  887. return OutVec;
  888. }
  889. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  890. const TargetLibraryInfo *li) {
  891. AA = aa;
  892. GFI = gfi;
  893. LibInfo = li;
  894. DL = &DAG.getDataLayout();
  895. Context = DAG.getContext();
  896. LPadToCallSiteMap.clear();
  897. SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
  898. }
  899. void SelectionDAGBuilder::clear() {
  900. NodeMap.clear();
  901. UnusedArgNodeMap.clear();
  902. PendingLoads.clear();
  903. PendingExports.clear();
  904. CurInst = nullptr;
  905. HasTailCall = false;
  906. SDNodeOrder = LowestSDNodeOrder;
  907. StatepointLowering.clear();
  908. }
  909. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  910. DanglingDebugInfoMap.clear();
  911. }
  912. SDValue SelectionDAGBuilder::getRoot() {
  913. if (PendingLoads.empty())
  914. return DAG.getRoot();
  915. if (PendingLoads.size() == 1) {
  916. SDValue Root = PendingLoads[0];
  917. DAG.setRoot(Root);
  918. PendingLoads.clear();
  919. return Root;
  920. }
  921. // Otherwise, we have to make a token factor node.
  922. SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
  923. PendingLoads.clear();
  924. DAG.setRoot(Root);
  925. return Root;
  926. }
  927. SDValue SelectionDAGBuilder::getControlRoot() {
  928. SDValue Root = DAG.getRoot();
  929. if (PendingExports.empty())
  930. return Root;
  931. // Turn all of the CopyToReg chains into one factored node.
  932. if (Root.getOpcode() != ISD::EntryToken) {
  933. unsigned i = 0, e = PendingExports.size();
  934. for (; i != e; ++i) {
  935. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  936. if (PendingExports[i].getNode()->getOperand(0) == Root)
  937. break; // Don't add the root if we already indirectly depend on it.
  938. }
  939. if (i == e)
  940. PendingExports.push_back(Root);
  941. }
  942. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  943. PendingExports);
  944. PendingExports.clear();
  945. DAG.setRoot(Root);
  946. return Root;
  947. }
  948. void SelectionDAGBuilder::visit(const Instruction &I) {
  949. // Set up outgoing PHI node register values before emitting the terminator.
  950. if (I.isTerminator()) {
  951. HandlePHINodesInSuccessorBlocks(I.getParent());
  952. }
  953. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  954. if (!isa<DbgInfoIntrinsic>(I))
  955. ++SDNodeOrder;
  956. CurInst = &I;
  957. visit(I.getOpcode(), I);
  958. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  959. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  960. // maps to this instruction.
  961. // TODO: We could handle all flags (nsw, etc) here.
  962. // TODO: If an IR instruction maps to >1 node, only the final node will have
  963. // flags set.
  964. if (SDNode *Node = getNodeForIRValue(&I)) {
  965. SDNodeFlags IncomingFlags;
  966. IncomingFlags.copyFMF(*FPMO);
  967. if (!Node->getFlags().isDefined())
  968. Node->setFlags(IncomingFlags);
  969. else
  970. Node->intersectFlagsWith(IncomingFlags);
  971. }
  972. }
  973. if (!I.isTerminator() && !HasTailCall &&
  974. !isStatepoint(&I)) // statepoints handle their exports internally
  975. CopyToExportRegsIfNeeded(&I);
  976. CurInst = nullptr;
  977. }
  978. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  979. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  980. }
  981. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  982. // Note: this doesn't use InstVisitor, because it has to work with
  983. // ConstantExpr's in addition to instructions.
  984. switch (Opcode) {
  985. default: llvm_unreachable("Unknown instruction type encountered!");
  986. // Build the switch statement using the Instruction.def file.
  987. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  988. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  989. #include "llvm/IR/Instruction.def"
  990. }
  991. }
  992. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  993. const DIExpression *Expr) {
  994. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  995. const DbgValueInst *DI = DDI.getDI();
  996. DIVariable *DanglingVariable = DI->getVariable();
  997. DIExpression *DanglingExpr = DI->getExpression();
  998. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  999. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  1000. return true;
  1001. }
  1002. return false;
  1003. };
  1004. for (auto &DDIMI : DanglingDebugInfoMap) {
  1005. DanglingDebugInfoVector &DDIV = DDIMI.second;
  1006. // If debug info is to be dropped, run it through final checks to see
  1007. // whether it can be salvaged.
  1008. for (auto &DDI : DDIV)
  1009. if (isMatchingDbgValue(DDI))
  1010. salvageUnresolvedDbgValue(DDI);
  1011. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  1012. }
  1013. }
  1014. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1015. // generate the debug data structures now that we've seen its definition.
  1016. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1017. SDValue Val) {
  1018. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1019. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1020. return;
  1021. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1022. for (auto &DDI : DDIV) {
  1023. const DbgValueInst *DI = DDI.getDI();
  1024. assert(DI && "Ill-formed DanglingDebugInfo");
  1025. DebugLoc dl = DDI.getdl();
  1026. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1027. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1028. DILocalVariable *Variable = DI->getVariable();
  1029. DIExpression *Expr = DI->getExpression();
  1030. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1031. "Expected inlined-at fields to agree");
  1032. SDDbgValue *SDV;
  1033. if (Val.getNode()) {
  1034. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1035. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1036. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1037. // in the first place we should not be more successful here). Unless we
  1038. // have some test case that prove this to be correct we should avoid
  1039. // calling EmitFuncArgumentDbgValue here.
  1040. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1041. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1042. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1043. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1044. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1045. // inserted after the definition of Val when emitting the instructions
  1046. // after ISel. An alternative could be to teach
  1047. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1048. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1049. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1050. << ValSDNodeOrder << "\n");
  1051. SDV = getDbgValue(Val, Variable, Expr, dl,
  1052. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1053. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1054. } else
  1055. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1056. << "in EmitFuncArgumentDbgValue\n");
  1057. } else {
  1058. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1059. auto Undef =
  1060. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1061. auto SDV =
  1062. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1063. DAG.AddDbgValue(SDV, nullptr, false);
  1064. }
  1065. }
  1066. DDIV.clear();
  1067. }
  1068. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1069. Value *V = DDI.getDI()->getValue();
  1070. DILocalVariable *Var = DDI.getDI()->getVariable();
  1071. DIExpression *Expr = DDI.getDI()->getExpression();
  1072. DebugLoc DL = DDI.getdl();
  1073. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1074. unsigned SDOrder = DDI.getSDNodeOrder();
  1075. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1076. // that DW_OP_stack_value is desired.
  1077. assert(isa<DbgValueInst>(DDI.getDI()));
  1078. bool StackValue = true;
  1079. // Can this Value can be encoded without any further work?
  1080. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1081. return;
  1082. // Attempt to salvage back through as many instructions as possible. Bail if
  1083. // a non-instruction is seen, such as a constant expression or global
  1084. // variable. FIXME: Further work could recover those too.
  1085. while (isa<Instruction>(V)) {
  1086. Instruction &VAsInst = *cast<Instruction>(V);
  1087. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1088. // If we cannot salvage any further, and haven't yet found a suitable debug
  1089. // expression, bail out.
  1090. if (!NewExpr)
  1091. break;
  1092. // New value and expr now represent this debuginfo.
  1093. V = VAsInst.getOperand(0);
  1094. Expr = NewExpr;
  1095. // Some kind of simplification occurred: check whether the operand of the
  1096. // salvaged debug expression can be encoded in this DAG.
  1097. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1098. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1099. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1100. return;
  1101. }
  1102. }
  1103. // This was the final opportunity to salvage this debug information, and it
  1104. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1105. // any earlier variable location.
  1106. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1107. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1108. DAG.AddDbgValue(SDV, nullptr, false);
  1109. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1110. << "\n");
  1111. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1112. << "\n");
  1113. }
  1114. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1115. DIExpression *Expr, DebugLoc dl,
  1116. DebugLoc InstDL, unsigned Order) {
  1117. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1118. SDDbgValue *SDV;
  1119. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1120. isa<ConstantPointerNull>(V)) {
  1121. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1122. DAG.AddDbgValue(SDV, nullptr, false);
  1123. return true;
  1124. }
  1125. // If the Value is a frame index, we can create a FrameIndex debug value
  1126. // without relying on the DAG at all.
  1127. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1128. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1129. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1130. auto SDV =
  1131. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1132. /*IsIndirect*/ false, dl, SDNodeOrder);
  1133. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1134. // is still available even if the SDNode gets optimized out.
  1135. DAG.AddDbgValue(SDV, nullptr, false);
  1136. return true;
  1137. }
  1138. }
  1139. // Do not use getValue() in here; we don't want to generate code at
  1140. // this point if it hasn't been done yet.
  1141. SDValue N = NodeMap[V];
  1142. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1143. N = UnusedArgNodeMap[V];
  1144. if (N.getNode()) {
  1145. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1146. return true;
  1147. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1148. DAG.AddDbgValue(SDV, N.getNode(), false);
  1149. return true;
  1150. }
  1151. // Special rules apply for the first dbg.values of parameter variables in a
  1152. // function. Identify them by the fact they reference Argument Values, that
  1153. // they're parameters, and they are parameters of the current function. We
  1154. // need to let them dangle until they get an SDNode.
  1155. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1156. !InstDL.getInlinedAt();
  1157. if (!IsParamOfFunc) {
  1158. // The value is not used in this block yet (or it would have an SDNode).
  1159. // We still want the value to appear for the user if possible -- if it has
  1160. // an associated VReg, we can refer to that instead.
  1161. auto VMI = FuncInfo.ValueMap.find(V);
  1162. if (VMI != FuncInfo.ValueMap.end()) {
  1163. unsigned Reg = VMI->second;
  1164. // If this is a PHI node, it may be split up into several MI PHI nodes
  1165. // (in FunctionLoweringInfo::set).
  1166. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1167. V->getType(), None);
  1168. if (RFV.occupiesMultipleRegs()) {
  1169. unsigned Offset = 0;
  1170. unsigned BitsToDescribe = 0;
  1171. if (auto VarSize = Var->getSizeInBits())
  1172. BitsToDescribe = *VarSize;
  1173. if (auto Fragment = Expr->getFragmentInfo())
  1174. BitsToDescribe = Fragment->SizeInBits;
  1175. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1176. unsigned RegisterSize = RegAndSize.second;
  1177. // Bail out if all bits are described already.
  1178. if (Offset >= BitsToDescribe)
  1179. break;
  1180. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1181. ? BitsToDescribe - Offset
  1182. : RegisterSize;
  1183. auto FragmentExpr = DIExpression::createFragmentExpression(
  1184. Expr, Offset, FragmentSize);
  1185. if (!FragmentExpr)
  1186. continue;
  1187. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1188. false, dl, SDNodeOrder);
  1189. DAG.AddDbgValue(SDV, nullptr, false);
  1190. Offset += RegisterSize;
  1191. }
  1192. } else {
  1193. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1194. DAG.AddDbgValue(SDV, nullptr, false);
  1195. }
  1196. return true;
  1197. }
  1198. }
  1199. return false;
  1200. }
  1201. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1202. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1203. for (auto &Pair : DanglingDebugInfoMap)
  1204. for (auto &DDI : Pair.second)
  1205. salvageUnresolvedDbgValue(DDI);
  1206. clearDanglingDebugInfo();
  1207. }
  1208. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1209. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1210. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1211. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1212. SDValue Result;
  1213. if (It != FuncInfo.ValueMap.end()) {
  1214. unsigned InReg = It->second;
  1215. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1216. DAG.getDataLayout(), InReg, Ty,
  1217. None); // This is not an ABI copy.
  1218. SDValue Chain = DAG.getEntryNode();
  1219. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1220. V);
  1221. resolveDanglingDebugInfo(V, Result);
  1222. }
  1223. return Result;
  1224. }
  1225. /// getValue - Return an SDValue for the given Value.
  1226. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1227. // If we already have an SDValue for this value, use it. It's important
  1228. // to do this first, so that we don't create a CopyFromReg if we already
  1229. // have a regular SDValue.
  1230. SDValue &N = NodeMap[V];
  1231. if (N.getNode()) return N;
  1232. // If there's a virtual register allocated and initialized for this
  1233. // value, use it.
  1234. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1235. return copyFromReg;
  1236. // Otherwise create a new SDValue and remember it.
  1237. SDValue Val = getValueImpl(V);
  1238. NodeMap[V] = Val;
  1239. resolveDanglingDebugInfo(V, Val);
  1240. return Val;
  1241. }
  1242. // Return true if SDValue exists for the given Value
  1243. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1244. return (NodeMap.find(V) != NodeMap.end()) ||
  1245. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1246. }
  1247. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1248. /// don't look in FuncInfo.ValueMap for a virtual register.
  1249. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1250. // If we already have an SDValue for this value, use it.
  1251. SDValue &N = NodeMap[V];
  1252. if (N.getNode()) {
  1253. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1254. // Remove the debug location from the node as the node is about to be used
  1255. // in a location which may differ from the original debug location. This
  1256. // is relevant to Constant and ConstantFP nodes because they can appear
  1257. // as constant expressions inside PHI nodes.
  1258. N->setDebugLoc(DebugLoc());
  1259. }
  1260. return N;
  1261. }
  1262. // Otherwise create a new SDValue and remember it.
  1263. SDValue Val = getValueImpl(V);
  1264. NodeMap[V] = Val;
  1265. resolveDanglingDebugInfo(V, Val);
  1266. return Val;
  1267. }
  1268. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1269. /// Create an SDValue for the given value.
  1270. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1271. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1272. if (const Constant *C = dyn_cast<Constant>(V)) {
  1273. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1274. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1275. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1276. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1277. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1278. if (isa<ConstantPointerNull>(C)) {
  1279. unsigned AS = V->getType()->getPointerAddressSpace();
  1280. return DAG.getConstant(0, getCurSDLoc(),
  1281. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1282. }
  1283. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1284. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1285. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1286. return DAG.getUNDEF(VT);
  1287. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1288. visit(CE->getOpcode(), *CE);
  1289. SDValue N1 = NodeMap[V];
  1290. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1291. return N1;
  1292. }
  1293. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1294. SmallVector<SDValue, 4> Constants;
  1295. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1296. OI != OE; ++OI) {
  1297. SDNode *Val = getValue(*OI).getNode();
  1298. // If the operand is an empty aggregate, there are no values.
  1299. if (!Val) continue;
  1300. // Add each leaf value from the operand to the Constants list
  1301. // to form a flattened list of all the values.
  1302. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1303. Constants.push_back(SDValue(Val, i));
  1304. }
  1305. return DAG.getMergeValues(Constants, getCurSDLoc());
  1306. }
  1307. if (const ConstantDataSequential *CDS =
  1308. dyn_cast<ConstantDataSequential>(C)) {
  1309. SmallVector<SDValue, 4> Ops;
  1310. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1311. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1312. // Add each leaf value from the operand to the Constants list
  1313. // to form a flattened list of all the values.
  1314. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1315. Ops.push_back(SDValue(Val, i));
  1316. }
  1317. if (isa<ArrayType>(CDS->getType()))
  1318. return DAG.getMergeValues(Ops, getCurSDLoc());
  1319. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1320. }
  1321. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1322. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1323. "Unknown struct or array constant!");
  1324. SmallVector<EVT, 4> ValueVTs;
  1325. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1326. unsigned NumElts = ValueVTs.size();
  1327. if (NumElts == 0)
  1328. return SDValue(); // empty struct
  1329. SmallVector<SDValue, 4> Constants(NumElts);
  1330. for (unsigned i = 0; i != NumElts; ++i) {
  1331. EVT EltVT = ValueVTs[i];
  1332. if (isa<UndefValue>(C))
  1333. Constants[i] = DAG.getUNDEF(EltVT);
  1334. else if (EltVT.isFloatingPoint())
  1335. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1336. else
  1337. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1338. }
  1339. return DAG.getMergeValues(Constants, getCurSDLoc());
  1340. }
  1341. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1342. return DAG.getBlockAddress(BA, VT);
  1343. VectorType *VecTy = cast<VectorType>(V->getType());
  1344. unsigned NumElements = VecTy->getNumElements();
  1345. // Now that we know the number and type of the elements, get that number of
  1346. // elements into the Ops array based on what kind of constant it is.
  1347. SmallVector<SDValue, 16> Ops;
  1348. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1349. for (unsigned i = 0; i != NumElements; ++i)
  1350. Ops.push_back(getValue(CV->getOperand(i)));
  1351. } else {
  1352. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1353. EVT EltVT =
  1354. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1355. SDValue Op;
  1356. if (EltVT.isFloatingPoint())
  1357. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1358. else
  1359. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1360. Ops.assign(NumElements, Op);
  1361. }
  1362. // Create a BUILD_VECTOR node.
  1363. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1364. }
  1365. // If this is a static alloca, generate it as the frameindex instead of
  1366. // computation.
  1367. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1368. DenseMap<const AllocaInst*, int>::iterator SI =
  1369. FuncInfo.StaticAllocaMap.find(AI);
  1370. if (SI != FuncInfo.StaticAllocaMap.end())
  1371. return DAG.getFrameIndex(SI->second,
  1372. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1373. }
  1374. // If this is an instruction which fast-isel has deferred, select it now.
  1375. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1376. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1377. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1378. Inst->getType(), getABIRegCopyCC(V));
  1379. SDValue Chain = DAG.getEntryNode();
  1380. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1381. }
  1382. llvm_unreachable("Can't get register for value!");
  1383. }
  1384. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1385. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1386. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1387. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1388. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1389. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1390. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1391. if (!IsSEH)
  1392. CatchPadMBB->setIsEHScopeEntry();
  1393. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1394. if (IsMSVCCXX || IsCoreCLR)
  1395. CatchPadMBB->setIsEHFuncletEntry();
  1396. // Wasm does not need catchpads anymore
  1397. if (!IsWasmCXX)
  1398. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1399. getControlRoot()));
  1400. }
  1401. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1402. // Update machine-CFG edge.
  1403. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1404. FuncInfo.MBB->addSuccessor(TargetMBB);
  1405. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1406. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1407. if (IsSEH) {
  1408. // If this is not a fall-through branch or optimizations are switched off,
  1409. // emit the branch.
  1410. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1411. TM.getOptLevel() == CodeGenOpt::None)
  1412. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1413. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1414. return;
  1415. }
  1416. // Figure out the funclet membership for the catchret's successor.
  1417. // This will be used by the FuncletLayout pass to determine how to order the
  1418. // BB's.
  1419. // A 'catchret' returns to the outer scope's color.
  1420. Value *ParentPad = I.getCatchSwitchParentPad();
  1421. const BasicBlock *SuccessorColor;
  1422. if (isa<ConstantTokenNone>(ParentPad))
  1423. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1424. else
  1425. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1426. assert(SuccessorColor && "No parent funclet for catchret!");
  1427. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1428. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1429. // Create the terminator node.
  1430. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1431. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1432. DAG.getBasicBlock(SuccessorColorMBB));
  1433. DAG.setRoot(Ret);
  1434. }
  1435. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1436. // Don't emit any special code for the cleanuppad instruction. It just marks
  1437. // the start of an EH scope/funclet.
  1438. FuncInfo.MBB->setIsEHScopeEntry();
  1439. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1440. if (Pers != EHPersonality::Wasm_CXX) {
  1441. FuncInfo.MBB->setIsEHFuncletEntry();
  1442. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1443. }
  1444. }
  1445. // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
  1446. // the control flow always stops at the single catch pad, as it does for a
  1447. // cleanup pad. In case the exception caught is not of the types the catch pad
  1448. // catches, it will be rethrown by a rethrow.
  1449. static void findWasmUnwindDestinations(
  1450. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1451. BranchProbability Prob,
  1452. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1453. &UnwindDests) {
  1454. while (EHPadBB) {
  1455. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1456. if (isa<CleanupPadInst>(Pad)) {
  1457. // Stop on cleanup pads.
  1458. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1459. UnwindDests.back().first->setIsEHScopeEntry();
  1460. break;
  1461. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1462. // Add the catchpad handlers to the possible destinations. We don't
  1463. // continue to the unwind destination of the catchswitch for wasm.
  1464. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1465. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1466. UnwindDests.back().first->setIsEHScopeEntry();
  1467. }
  1468. break;
  1469. } else {
  1470. continue;
  1471. }
  1472. }
  1473. }
  1474. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1475. /// many places it could ultimately go. In the IR, we have a single unwind
  1476. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1477. /// This function skips over imaginary basic blocks that hold catchswitch
  1478. /// instructions, and finds all the "real" machine
  1479. /// basic block destinations. As those destinations may not be successors of
  1480. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1481. /// The passed-in Prob is the edge probability to EHPadBB.
  1482. static void findUnwindDestinations(
  1483. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1484. BranchProbability Prob,
  1485. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1486. &UnwindDests) {
  1487. EHPersonality Personality =
  1488. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1489. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1490. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1491. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1492. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1493. if (IsWasmCXX) {
  1494. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1495. assert(UnwindDests.size() <= 1 &&
  1496. "There should be at most one unwind destination for wasm");
  1497. return;
  1498. }
  1499. while (EHPadBB) {
  1500. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1501. BasicBlock *NewEHPadBB = nullptr;
  1502. if (isa<LandingPadInst>(Pad)) {
  1503. // Stop on landingpads. They are not funclets.
  1504. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1505. break;
  1506. } else if (isa<CleanupPadInst>(Pad)) {
  1507. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1508. // personalities.
  1509. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1510. UnwindDests.back().first->setIsEHScopeEntry();
  1511. UnwindDests.back().first->setIsEHFuncletEntry();
  1512. break;
  1513. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1514. // Add the catchpad handlers to the possible destinations.
  1515. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1516. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1517. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1518. if (IsMSVCCXX || IsCoreCLR)
  1519. UnwindDests.back().first->setIsEHFuncletEntry();
  1520. if (!IsSEH)
  1521. UnwindDests.back().first->setIsEHScopeEntry();
  1522. }
  1523. NewEHPadBB = CatchSwitch->getUnwindDest();
  1524. } else {
  1525. continue;
  1526. }
  1527. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1528. if (BPI && NewEHPadBB)
  1529. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1530. EHPadBB = NewEHPadBB;
  1531. }
  1532. }
  1533. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1534. // Update successor info.
  1535. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1536. auto UnwindDest = I.getUnwindDest();
  1537. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1538. BranchProbability UnwindDestProb =
  1539. (BPI && UnwindDest)
  1540. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1541. : BranchProbability::getZero();
  1542. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1543. for (auto &UnwindDest : UnwindDests) {
  1544. UnwindDest.first->setIsEHPad();
  1545. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1546. }
  1547. FuncInfo.MBB->normalizeSuccProbs();
  1548. // Create the terminator node.
  1549. SDValue Ret =
  1550. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1551. DAG.setRoot(Ret);
  1552. }
  1553. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1554. report_fatal_error("visitCatchSwitch not yet implemented!");
  1555. }
  1556. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1557. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1558. auto &DL = DAG.getDataLayout();
  1559. SDValue Chain = getControlRoot();
  1560. SmallVector<ISD::OutputArg, 8> Outs;
  1561. SmallVector<SDValue, 8> OutVals;
  1562. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1563. // lower
  1564. //
  1565. // %val = call <ty> @llvm.experimental.deoptimize()
  1566. // ret <ty> %val
  1567. //
  1568. // differently.
  1569. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1570. LowerDeoptimizingReturn();
  1571. return;
  1572. }
  1573. if (!FuncInfo.CanLowerReturn) {
  1574. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1575. const Function *F = I.getParent()->getParent();
  1576. // Emit a store of the return value through the virtual register.
  1577. // Leave Outs empty so that LowerReturn won't try to load return
  1578. // registers the usual way.
  1579. SmallVector<EVT, 1> PtrValueVTs;
  1580. ComputeValueVTs(TLI, DL,
  1581. F->getReturnType()->getPointerTo(
  1582. DAG.getDataLayout().getAllocaAddrSpace()),
  1583. PtrValueVTs);
  1584. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1585. DemoteReg, PtrValueVTs[0]);
  1586. SDValue RetOp = getValue(I.getOperand(0));
  1587. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1588. SmallVector<uint64_t, 4> Offsets;
  1589. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1590. &Offsets);
  1591. unsigned NumValues = ValueVTs.size();
  1592. SmallVector<SDValue, 4> Chains(NumValues);
  1593. for (unsigned i = 0; i != NumValues; ++i) {
  1594. // An aggregate return value cannot wrap around the address space, so
  1595. // offsets to its parts don't wrap either.
  1596. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1597. SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
  1598. if (MemVTs[i] != ValueVTs[i])
  1599. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1600. Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
  1601. // FIXME: better loc info would be nice.
  1602. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1603. }
  1604. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1605. MVT::Other, Chains);
  1606. } else if (I.getNumOperands() != 0) {
  1607. SmallVector<EVT, 4> ValueVTs;
  1608. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1609. unsigned NumValues = ValueVTs.size();
  1610. if (NumValues) {
  1611. SDValue RetOp = getValue(I.getOperand(0));
  1612. const Function *F = I.getParent()->getParent();
  1613. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1614. I.getOperand(0)->getType(), F->getCallingConv(),
  1615. /*IsVarArg*/ false);
  1616. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1617. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1618. Attribute::SExt))
  1619. ExtendKind = ISD::SIGN_EXTEND;
  1620. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1621. Attribute::ZExt))
  1622. ExtendKind = ISD::ZERO_EXTEND;
  1623. LLVMContext &Context = F->getContext();
  1624. bool RetInReg = F->getAttributes().hasAttribute(
  1625. AttributeList::ReturnIndex, Attribute::InReg);
  1626. for (unsigned j = 0; j != NumValues; ++j) {
  1627. EVT VT = ValueVTs[j];
  1628. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1629. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1630. CallingConv::ID CC = F->getCallingConv();
  1631. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1632. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1633. SmallVector<SDValue, 4> Parts(NumParts);
  1634. getCopyToParts(DAG, getCurSDLoc(),
  1635. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1636. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1637. // 'inreg' on function refers to return value
  1638. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1639. if (RetInReg)
  1640. Flags.setInReg();
  1641. if (I.getOperand(0)->getType()->isPointerTy()) {
  1642. Flags.setPointer();
  1643. Flags.setPointerAddrSpace(
  1644. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1645. }
  1646. if (NeedsRegBlock) {
  1647. Flags.setInConsecutiveRegs();
  1648. if (j == NumValues - 1)
  1649. Flags.setInConsecutiveRegsLast();
  1650. }
  1651. // Propagate extension type if any
  1652. if (ExtendKind == ISD::SIGN_EXTEND)
  1653. Flags.setSExt();
  1654. else if (ExtendKind == ISD::ZERO_EXTEND)
  1655. Flags.setZExt();
  1656. for (unsigned i = 0; i < NumParts; ++i) {
  1657. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1658. VT, /*isfixed=*/true, 0, 0));
  1659. OutVals.push_back(Parts[i]);
  1660. }
  1661. }
  1662. }
  1663. }
  1664. // Push in swifterror virtual register as the last element of Outs. This makes
  1665. // sure swifterror virtual register will be returned in the swifterror
  1666. // physical register.
  1667. const Function *F = I.getParent()->getParent();
  1668. if (TLI.supportSwiftError() &&
  1669. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1670. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1671. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1672. Flags.setSwiftError();
  1673. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1674. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1675. true /*isfixed*/, 1 /*origidx*/,
  1676. 0 /*partOffs*/));
  1677. // Create SDNode for the swifterror virtual register.
  1678. OutVals.push_back(
  1679. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1680. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1681. EVT(TLI.getPointerTy(DL))));
  1682. }
  1683. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1684. CallingConv::ID CallConv =
  1685. DAG.getMachineFunction().getFunction().getCallingConv();
  1686. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1687. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1688. // Verify that the target's LowerReturn behaved as expected.
  1689. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1690. "LowerReturn didn't return a valid chain!");
  1691. // Update the DAG with the new chain value resulting from return lowering.
  1692. DAG.setRoot(Chain);
  1693. }
  1694. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1695. /// created for it, emit nodes to copy the value into the virtual
  1696. /// registers.
  1697. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1698. // Skip empty types
  1699. if (V->getType()->isEmptyTy())
  1700. return;
  1701. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1702. if (VMI != FuncInfo.ValueMap.end()) {
  1703. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1704. CopyValueToVirtualRegister(V, VMI->second);
  1705. }
  1706. }
  1707. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1708. /// the current basic block, add it to ValueMap now so that we'll get a
  1709. /// CopyTo/FromReg.
  1710. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1711. // No need to export constants.
  1712. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1713. // Already exported?
  1714. if (FuncInfo.isExportedInst(V)) return;
  1715. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1716. CopyValueToVirtualRegister(V, Reg);
  1717. }
  1718. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1719. const BasicBlock *FromBB) {
  1720. // The operands of the setcc have to be in this block. We don't know
  1721. // how to export them from some other block.
  1722. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1723. // Can export from current BB.
  1724. if (VI->getParent() == FromBB)
  1725. return true;
  1726. // Is already exported, noop.
  1727. return FuncInfo.isExportedInst(V);
  1728. }
  1729. // If this is an argument, we can export it if the BB is the entry block or
  1730. // if it is already exported.
  1731. if (isa<Argument>(V)) {
  1732. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1733. return true;
  1734. // Otherwise, can only export this if it is already exported.
  1735. return FuncInfo.isExportedInst(V);
  1736. }
  1737. // Otherwise, constants can always be exported.
  1738. return true;
  1739. }
  1740. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1741. BranchProbability
  1742. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1743. const MachineBasicBlock *Dst) const {
  1744. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1745. const BasicBlock *SrcBB = Src->getBasicBlock();
  1746. const BasicBlock *DstBB = Dst->getBasicBlock();
  1747. if (!BPI) {
  1748. // If BPI is not available, set the default probability as 1 / N, where N is
  1749. // the number of successors.
  1750. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1751. return BranchProbability(1, SuccSize);
  1752. }
  1753. return BPI->getEdgeProbability(SrcBB, DstBB);
  1754. }
  1755. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1756. MachineBasicBlock *Dst,
  1757. BranchProbability Prob) {
  1758. if (!FuncInfo.BPI)
  1759. Src->addSuccessorWithoutProb(Dst);
  1760. else {
  1761. if (Prob.isUnknown())
  1762. Prob = getEdgeProbability(Src, Dst);
  1763. Src->addSuccessor(Dst, Prob);
  1764. }
  1765. }
  1766. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1767. if (const Instruction *I = dyn_cast<Instruction>(V))
  1768. return I->getParent() == BB;
  1769. return true;
  1770. }
  1771. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1772. /// This function emits a branch and is used at the leaves of an OR or an
  1773. /// AND operator tree.
  1774. void
  1775. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1776. MachineBasicBlock *TBB,
  1777. MachineBasicBlock *FBB,
  1778. MachineBasicBlock *CurBB,
  1779. MachineBasicBlock *SwitchBB,
  1780. BranchProbability TProb,
  1781. BranchProbability FProb,
  1782. bool InvertCond) {
  1783. const BasicBlock *BB = CurBB->getBasicBlock();
  1784. // If the leaf of the tree is a comparison, merge the condition into
  1785. // the caseblock.
  1786. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1787. // The operands of the cmp have to be in this block. We don't know
  1788. // how to export them from some other block. If this is the first block
  1789. // of the sequence, no exporting is needed.
  1790. if (CurBB == SwitchBB ||
  1791. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1792. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1793. ISD::CondCode Condition;
  1794. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1795. ICmpInst::Predicate Pred =
  1796. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1797. Condition = getICmpCondCode(Pred);
  1798. } else {
  1799. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1800. FCmpInst::Predicate Pred =
  1801. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1802. Condition = getFCmpCondCode(Pred);
  1803. if (TM.Options.NoNaNsFPMath)
  1804. Condition = getFCmpCodeWithoutNaN(Condition);
  1805. }
  1806. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1807. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1808. SL->SwitchCases.push_back(CB);
  1809. return;
  1810. }
  1811. }
  1812. // Create a CaseBlock record representing this branch.
  1813. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1814. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1815. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1816. SL->SwitchCases.push_back(CB);
  1817. }
  1818. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1819. MachineBasicBlock *TBB,
  1820. MachineBasicBlock *FBB,
  1821. MachineBasicBlock *CurBB,
  1822. MachineBasicBlock *SwitchBB,
  1823. Instruction::BinaryOps Opc,
  1824. BranchProbability TProb,
  1825. BranchProbability FProb,
  1826. bool InvertCond) {
  1827. // Skip over not part of the tree and remember to invert op and operands at
  1828. // next level.
  1829. Value *NotCond;
  1830. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1831. InBlock(NotCond, CurBB->getBasicBlock())) {
  1832. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1833. !InvertCond);
  1834. return;
  1835. }
  1836. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1837. // Compute the effective opcode for Cond, taking into account whether it needs
  1838. // to be inverted, e.g.
  1839. // and (not (or A, B)), C
  1840. // gets lowered as
  1841. // and (and (not A, not B), C)
  1842. unsigned BOpc = 0;
  1843. if (BOp) {
  1844. BOpc = BOp->getOpcode();
  1845. if (InvertCond) {
  1846. if (BOpc == Instruction::And)
  1847. BOpc = Instruction::Or;
  1848. else if (BOpc == Instruction::Or)
  1849. BOpc = Instruction::And;
  1850. }
  1851. }
  1852. // If this node is not part of the or/and tree, emit it as a branch.
  1853. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1854. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1855. BOp->getParent() != CurBB->getBasicBlock() ||
  1856. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1857. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1858. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1859. TProb, FProb, InvertCond);
  1860. return;
  1861. }
  1862. // Create TmpBB after CurBB.
  1863. MachineFunction::iterator BBI(CurBB);
  1864. MachineFunction &MF = DAG.getMachineFunction();
  1865. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1866. CurBB->getParent()->insert(++BBI, TmpBB);
  1867. if (Opc == Instruction::Or) {
  1868. // Codegen X | Y as:
  1869. // BB1:
  1870. // jmp_if_X TBB
  1871. // jmp TmpBB
  1872. // TmpBB:
  1873. // jmp_if_Y TBB
  1874. // jmp FBB
  1875. //
  1876. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1877. // The requirement is that
  1878. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1879. // = TrueProb for original BB.
  1880. // Assuming the original probabilities are A and B, one choice is to set
  1881. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1882. // A/(1+B) and 2B/(1+B). This choice assumes that
  1883. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1884. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1885. // TmpBB, but the math is more complicated.
  1886. auto NewTrueProb = TProb / 2;
  1887. auto NewFalseProb = TProb / 2 + FProb;
  1888. // Emit the LHS condition.
  1889. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1890. NewTrueProb, NewFalseProb, InvertCond);
  1891. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1892. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1893. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1894. // Emit the RHS condition into TmpBB.
  1895. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1896. Probs[0], Probs[1], InvertCond);
  1897. } else {
  1898. assert(Opc == Instruction::And && "Unknown merge op!");
  1899. // Codegen X & Y as:
  1900. // BB1:
  1901. // jmp_if_X TmpBB
  1902. // jmp FBB
  1903. // TmpBB:
  1904. // jmp_if_Y TBB
  1905. // jmp FBB
  1906. //
  1907. // This requires creation of TmpBB after CurBB.
  1908. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1909. // The requirement is that
  1910. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1911. // = FalseProb for original BB.
  1912. // Assuming the original probabilities are A and B, one choice is to set
  1913. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1914. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1915. // TrueProb for BB1 * FalseProb for TmpBB.
  1916. auto NewTrueProb = TProb + FProb / 2;
  1917. auto NewFalseProb = FProb / 2;
  1918. // Emit the LHS condition.
  1919. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1920. NewTrueProb, NewFalseProb, InvertCond);
  1921. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1922. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1923. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1924. // Emit the RHS condition into TmpBB.
  1925. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1926. Probs[0], Probs[1], InvertCond);
  1927. }
  1928. }
  1929. /// If the set of cases should be emitted as a series of branches, return true.
  1930. /// If we should emit this as a bunch of and/or'd together conditions, return
  1931. /// false.
  1932. bool
  1933. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1934. if (Cases.size() != 2) return true;
  1935. // If this is two comparisons of the same values or'd or and'd together, they
  1936. // will get folded into a single comparison, so don't emit two blocks.
  1937. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1938. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1939. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1940. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1941. return false;
  1942. }
  1943. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1944. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1945. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1946. Cases[0].CC == Cases[1].CC &&
  1947. isa<Constant>(Cases[0].CmpRHS) &&
  1948. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1949. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1950. return false;
  1951. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1952. return false;
  1953. }
  1954. return true;
  1955. }
  1956. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1957. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1958. // Update machine-CFG edges.
  1959. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1960. if (I.isUnconditional()) {
  1961. // Update machine-CFG edges.
  1962. BrMBB->addSuccessor(Succ0MBB);
  1963. // If this is not a fall-through branch or optimizations are switched off,
  1964. // emit the branch.
  1965. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1966. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1967. MVT::Other, getControlRoot(),
  1968. DAG.getBasicBlock(Succ0MBB)));
  1969. return;
  1970. }
  1971. // If this condition is one of the special cases we handle, do special stuff
  1972. // now.
  1973. const Value *CondVal = I.getCondition();
  1974. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1975. // If this is a series of conditions that are or'd or and'd together, emit
  1976. // this as a sequence of branches instead of setcc's with and/or operations.
  1977. // As long as jumps are not expensive, this should improve performance.
  1978. // For example, instead of something like:
  1979. // cmp A, B
  1980. // C = seteq
  1981. // cmp D, E
  1982. // F = setle
  1983. // or C, F
  1984. // jnz foo
  1985. // Emit:
  1986. // cmp A, B
  1987. // je foo
  1988. // cmp D, E
  1989. // jle foo
  1990. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1991. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1992. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1993. !I.hasMetadata(LLVMContext::MD_unpredictable) &&
  1994. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1995. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1996. Opcode,
  1997. getEdgeProbability(BrMBB, Succ0MBB),
  1998. getEdgeProbability(BrMBB, Succ1MBB),
  1999. /*InvertCond=*/false);
  2000. // If the compares in later blocks need to use values not currently
  2001. // exported from this block, export them now. This block should always
  2002. // be the first entry.
  2003. assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2004. // Allow some cases to be rejected.
  2005. if (ShouldEmitAsBranches(SL->SwitchCases)) {
  2006. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
  2007. ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
  2008. ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
  2009. }
  2010. // Emit the branch for this block.
  2011. visitSwitchCase(SL->SwitchCases[0], BrMBB);
  2012. SL->SwitchCases.erase(SL->SwitchCases.begin());
  2013. return;
  2014. }
  2015. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2016. // SwitchCases.
  2017. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
  2018. FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
  2019. SL->SwitchCases.clear();
  2020. }
  2021. }
  2022. // Create a CaseBlock record representing this branch.
  2023. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2024. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2025. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2026. // cond branch.
  2027. visitSwitchCase(CB, BrMBB);
  2028. }
  2029. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2030. /// the binary search tree resulting from lowering a switch instruction.
  2031. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2032. MachineBasicBlock *SwitchBB) {
  2033. SDValue Cond;
  2034. SDValue CondLHS = getValue(CB.CmpLHS);
  2035. SDLoc dl = CB.DL;
  2036. if (CB.CC == ISD::SETTRUE) {
  2037. // Branch or fall through to TrueBB.
  2038. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2039. SwitchBB->normalizeSuccProbs();
  2040. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2041. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2042. DAG.getBasicBlock(CB.TrueBB)));
  2043. }
  2044. return;
  2045. }
  2046. auto &TLI = DAG.getTargetLoweringInfo();
  2047. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2048. // Build the setcc now.
  2049. if (!CB.CmpMHS) {
  2050. // Fold "(X == true)" to X and "(X == false)" to !X to
  2051. // handle common cases produced by branch lowering.
  2052. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2053. CB.CC == ISD::SETEQ)
  2054. Cond = CondLHS;
  2055. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2056. CB.CC == ISD::SETEQ) {
  2057. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2058. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2059. } else {
  2060. SDValue CondRHS = getValue(CB.CmpRHS);
  2061. // If a pointer's DAG type is larger than its memory type then the DAG
  2062. // values are zero-extended. This breaks signed comparisons so truncate
  2063. // back to the underlying type before doing the compare.
  2064. if (CondLHS.getValueType() != MemVT) {
  2065. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2066. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2067. }
  2068. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2069. }
  2070. } else {
  2071. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2072. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2073. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2074. SDValue CmpOp = getValue(CB.CmpMHS);
  2075. EVT VT = CmpOp.getValueType();
  2076. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2077. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2078. ISD::SETLE);
  2079. } else {
  2080. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2081. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2082. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2083. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2084. }
  2085. }
  2086. // Update successor info
  2087. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2088. // TrueBB and FalseBB are always different unless the incoming IR is
  2089. // degenerate. This only happens when running llc on weird IR.
  2090. if (CB.TrueBB != CB.FalseBB)
  2091. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2092. SwitchBB->normalizeSuccProbs();
  2093. // If the lhs block is the next block, invert the condition so that we can
  2094. // fall through to the lhs instead of the rhs block.
  2095. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2096. std::swap(CB.TrueBB, CB.FalseBB);
  2097. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2098. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2099. }
  2100. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2101. MVT::Other, getControlRoot(), Cond,
  2102. DAG.getBasicBlock(CB.TrueBB));
  2103. // Insert the false branch. Do this even if it's a fall through branch,
  2104. // this makes it easier to do DAG optimizations which require inverting
  2105. // the branch condition.
  2106. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2107. DAG.getBasicBlock(CB.FalseBB));
  2108. DAG.setRoot(BrCond);
  2109. }
  2110. /// visitJumpTable - Emit JumpTable node in the current MBB
  2111. void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
  2112. // Emit the code for the jump table
  2113. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2114. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2115. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2116. JT.Reg, PTy);
  2117. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2118. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2119. MVT::Other, Index.getValue(1),
  2120. Table, Index);
  2121. DAG.setRoot(BrJumpTable);
  2122. }
  2123. /// visitJumpTableHeader - This function emits necessary code to produce index
  2124. /// in the JumpTable from switch case.
  2125. void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
  2126. JumpTableHeader &JTH,
  2127. MachineBasicBlock *SwitchBB) {
  2128. SDLoc dl = getCurSDLoc();
  2129. // Subtract the lowest switch case value from the value being switched on.
  2130. SDValue SwitchOp = getValue(JTH.SValue);
  2131. EVT VT = SwitchOp.getValueType();
  2132. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2133. DAG.getConstant(JTH.First, dl, VT));
  2134. // The SDNode we just created, which holds the value being switched on minus
  2135. // the smallest case value, needs to be copied to a virtual register so it
  2136. // can be used as an index into the jump table in a subsequent basic block.
  2137. // This value may be smaller or larger than the target's pointer type, and
  2138. // therefore require extension or truncating.
  2139. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2140. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2141. unsigned JumpTableReg =
  2142. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2143. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2144. JumpTableReg, SwitchOp);
  2145. JT.Reg = JumpTableReg;
  2146. if (!JTH.OmitRangeCheck) {
  2147. // Emit the range check for the jump table, and branch to the default block
  2148. // for the switch statement if the value being switched on exceeds the
  2149. // largest case in the switch.
  2150. SDValue CMP = DAG.getSetCC(
  2151. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2152. Sub.getValueType()),
  2153. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2154. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2155. MVT::Other, CopyTo, CMP,
  2156. DAG.getBasicBlock(JT.Default));
  2157. // Avoid emitting unnecessary branches to the next block.
  2158. if (JT.MBB != NextBlock(SwitchBB))
  2159. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2160. DAG.getBasicBlock(JT.MBB));
  2161. DAG.setRoot(BrCond);
  2162. } else {
  2163. // Avoid emitting unnecessary branches to the next block.
  2164. if (JT.MBB != NextBlock(SwitchBB))
  2165. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2166. DAG.getBasicBlock(JT.MBB)));
  2167. else
  2168. DAG.setRoot(CopyTo);
  2169. }
  2170. }
  2171. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2172. /// variable if there exists one.
  2173. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2174. SDValue &Chain) {
  2175. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2176. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2177. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2178. MachineFunction &MF = DAG.getMachineFunction();
  2179. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2180. MachineSDNode *Node =
  2181. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2182. if (Global) {
  2183. MachinePointerInfo MPInfo(Global);
  2184. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2185. MachineMemOperand::MODereferenceable;
  2186. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2187. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  2188. DAG.setNodeMemRefs(Node, {MemRef});
  2189. }
  2190. if (PtrTy != PtrMemTy)
  2191. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2192. return SDValue(Node, 0);
  2193. }
  2194. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2195. /// tail spliced into a stack protector check success bb.
  2196. ///
  2197. /// For a high level explanation of how this fits into the stack protector
  2198. /// generation see the comment on the declaration of class
  2199. /// StackProtectorDescriptor.
  2200. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2201. MachineBasicBlock *ParentBB) {
  2202. // First create the loads to the guard/stack slot for the comparison.
  2203. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2204. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2205. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2206. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2207. int FI = MFI.getStackProtectorIndex();
  2208. SDValue Guard;
  2209. SDLoc dl = getCurSDLoc();
  2210. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2211. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2212. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  2213. // Generate code to load the content of the guard slot.
  2214. SDValue GuardVal = DAG.getLoad(
  2215. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2216. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2217. MachineMemOperand::MOVolatile);
  2218. if (TLI.useStackGuardXorFP())
  2219. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2220. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2221. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2222. // The target provides a guard check function to validate the guard value.
  2223. // Generate a call to that function with the content of the guard slot as
  2224. // argument.
  2225. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2226. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2227. TargetLowering::ArgListTy Args;
  2228. TargetLowering::ArgListEntry Entry;
  2229. Entry.Node = GuardVal;
  2230. Entry.Ty = FnTy->getParamType(0);
  2231. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2232. Entry.IsInReg = true;
  2233. Args.push_back(Entry);
  2234. TargetLowering::CallLoweringInfo CLI(DAG);
  2235. CLI.setDebugLoc(getCurSDLoc())
  2236. .setChain(DAG.getEntryNode())
  2237. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2238. getValue(GuardCheckFn), std::move(Args));
  2239. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2240. DAG.setRoot(Result.second);
  2241. return;
  2242. }
  2243. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2244. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2245. SDValue Chain = DAG.getEntryNode();
  2246. if (TLI.useLoadStackGuardNode()) {
  2247. Guard = getLoadStackGuard(DAG, dl, Chain);
  2248. } else {
  2249. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2250. SDValue GuardPtr = getValue(IRGuard);
  2251. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2252. MachinePointerInfo(IRGuard, 0), Align,
  2253. MachineMemOperand::MOVolatile);
  2254. }
  2255. // Perform the comparison via a subtract/getsetcc.
  2256. EVT VT = Guard.getValueType();
  2257. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2258. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2259. *DAG.getContext(),
  2260. Sub.getValueType()),
  2261. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2262. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2263. // branch to failure MBB.
  2264. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2265. MVT::Other, GuardVal.getOperand(0),
  2266. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2267. // Otherwise branch to success MBB.
  2268. SDValue Br = DAG.getNode(ISD::BR, dl,
  2269. MVT::Other, BrCond,
  2270. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2271. DAG.setRoot(Br);
  2272. }
  2273. /// Codegen the failure basic block for a stack protector check.
  2274. ///
  2275. /// A failure stack protector machine basic block consists simply of a call to
  2276. /// __stack_chk_fail().
  2277. ///
  2278. /// For a high level explanation of how this fits into the stack protector
  2279. /// generation see the comment on the declaration of class
  2280. /// StackProtectorDescriptor.
  2281. void
  2282. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2283. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2284. TargetLowering::MakeLibCallOptions CallOptions;
  2285. CallOptions.setDiscardResult(true);
  2286. SDValue Chain =
  2287. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2288. None, CallOptions, getCurSDLoc()).second;
  2289. // On PS4, the "return address" must still be within the calling function,
  2290. // even if it's at the very end, so emit an explicit TRAP here.
  2291. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2292. if (TM.getTargetTriple().isPS4CPU())
  2293. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2294. DAG.setRoot(Chain);
  2295. }
  2296. /// visitBitTestHeader - This function emits necessary code to produce value
  2297. /// suitable for "bit tests"
  2298. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2299. MachineBasicBlock *SwitchBB) {
  2300. SDLoc dl = getCurSDLoc();
  2301. // Subtract the minimum value.
  2302. SDValue SwitchOp = getValue(B.SValue);
  2303. EVT VT = SwitchOp.getValueType();
  2304. SDValue RangeSub =
  2305. DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
  2306. // Determine the type of the test operands.
  2307. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2308. bool UsePtrType = false;
  2309. if (!TLI.isTypeLegal(VT)) {
  2310. UsePtrType = true;
  2311. } else {
  2312. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2313. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2314. // Switch table case range are encoded into series of masks.
  2315. // Just use pointer type, it's guaranteed to fit.
  2316. UsePtrType = true;
  2317. break;
  2318. }
  2319. }
  2320. SDValue Sub = RangeSub;
  2321. if (UsePtrType) {
  2322. VT = TLI.getPointerTy(DAG.getDataLayout());
  2323. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2324. }
  2325. B.RegVT = VT.getSimpleVT();
  2326. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2327. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2328. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2329. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2330. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2331. SwitchBB->normalizeSuccProbs();
  2332. SDValue Root = CopyTo;
  2333. if (!B.OmitRangeCheck) {
  2334. // Conditional branch to the default block.
  2335. SDValue RangeCmp = DAG.getSetCC(dl,
  2336. TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2337. RangeSub.getValueType()),
  2338. RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
  2339. ISD::SETUGT);
  2340. Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
  2341. DAG.getBasicBlock(B.Default));
  2342. }
  2343. // Avoid emitting unnecessary branches to the next block.
  2344. if (MBB != NextBlock(SwitchBB))
  2345. Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
  2346. DAG.setRoot(Root);
  2347. }
  2348. /// visitBitTestCase - this function produces one "bit test"
  2349. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2350. MachineBasicBlock* NextMBB,
  2351. BranchProbability BranchProbToNext,
  2352. unsigned Reg,
  2353. BitTestCase &B,
  2354. MachineBasicBlock *SwitchBB) {
  2355. SDLoc dl = getCurSDLoc();
  2356. MVT VT = BB.RegVT;
  2357. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2358. SDValue Cmp;
  2359. unsigned PopCount = countPopulation(B.Mask);
  2360. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2361. if (PopCount == 1) {
  2362. // Testing for a single bit; just compare the shift count with what it
  2363. // would need to be to shift a 1 bit in that position.
  2364. Cmp = DAG.getSetCC(
  2365. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2366. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2367. ISD::SETEQ);
  2368. } else if (PopCount == BB.Range) {
  2369. // There is only one zero bit in the range, test for it directly.
  2370. Cmp = DAG.getSetCC(
  2371. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2372. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2373. ISD::SETNE);
  2374. } else {
  2375. // Make desired shift
  2376. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2377. DAG.getConstant(1, dl, VT), ShiftOp);
  2378. // Emit bit tests and jumps
  2379. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2380. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2381. Cmp = DAG.getSetCC(
  2382. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2383. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2384. }
  2385. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2386. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2387. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2388. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2389. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2390. // one as they are relative probabilities (and thus work more like weights),
  2391. // and hence we need to normalize them to let the sum of them become one.
  2392. SwitchBB->normalizeSuccProbs();
  2393. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2394. MVT::Other, getControlRoot(),
  2395. Cmp, DAG.getBasicBlock(B.TargetBB));
  2396. // Avoid emitting unnecessary branches to the next block.
  2397. if (NextMBB != NextBlock(SwitchBB))
  2398. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2399. DAG.getBasicBlock(NextMBB));
  2400. DAG.setRoot(BrAnd);
  2401. }
  2402. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2403. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2404. // Retrieve successors. Look through artificial IR level blocks like
  2405. // catchswitch for successors.
  2406. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2407. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2408. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2409. // have to do anything here to lower funclet bundles.
  2410. assert(!I.hasOperandBundlesOtherThan(
  2411. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2412. "Cannot lower invokes with arbitrary operand bundles yet!");
  2413. const Value *Callee(I.getCalledValue());
  2414. const Function *Fn = dyn_cast<Function>(Callee);
  2415. if (isa<InlineAsm>(Callee))
  2416. visitInlineAsm(&I);
  2417. else if (Fn && Fn->isIntrinsic()) {
  2418. switch (Fn->getIntrinsicID()) {
  2419. default:
  2420. llvm_unreachable("Cannot invoke this intrinsic");
  2421. case Intrinsic::donothing:
  2422. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2423. break;
  2424. case Intrinsic::experimental_patchpoint_void:
  2425. case Intrinsic::experimental_patchpoint_i64:
  2426. visitPatchpoint(&I, EHPadBB);
  2427. break;
  2428. case Intrinsic::experimental_gc_statepoint:
  2429. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2430. break;
  2431. case Intrinsic::wasm_rethrow_in_catch: {
  2432. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2433. // special because it can be invoked, so we manually lower it to a DAG
  2434. // node here.
  2435. SmallVector<SDValue, 8> Ops;
  2436. Ops.push_back(getRoot()); // inchain
  2437. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2438. Ops.push_back(
  2439. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2440. TLI.getPointerTy(DAG.getDataLayout())));
  2441. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2442. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2443. break;
  2444. }
  2445. }
  2446. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2447. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2448. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2449. // intrinsic, and right now there are no plans to support other intrinsics
  2450. // with deopt state.
  2451. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2452. } else {
  2453. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2454. }
  2455. // If the value of the invoke is used outside of its defining block, make it
  2456. // available as a virtual register.
  2457. // We already took care of the exported value for the statepoint instruction
  2458. // during call to the LowerStatepoint.
  2459. if (!isStatepoint(I)) {
  2460. CopyToExportRegsIfNeeded(&I);
  2461. }
  2462. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2463. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2464. BranchProbability EHPadBBProb =
  2465. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2466. : BranchProbability::getZero();
  2467. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2468. // Update successor info.
  2469. addSuccessorWithProb(InvokeMBB, Return);
  2470. for (auto &UnwindDest : UnwindDests) {
  2471. UnwindDest.first->setIsEHPad();
  2472. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2473. }
  2474. InvokeMBB->normalizeSuccProbs();
  2475. // Drop into normal successor.
  2476. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2477. DAG.getBasicBlock(Return)));
  2478. }
  2479. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2480. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2481. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2482. // have to do anything here to lower funclet bundles.
  2483. assert(!I.hasOperandBundlesOtherThan(
  2484. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2485. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2486. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2487. "Only know how to handle inlineasm callbr");
  2488. visitInlineAsm(&I);
  2489. // Retrieve successors.
  2490. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2491. // Update successor info.
  2492. addSuccessorWithProb(CallBrMBB, Return);
  2493. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2494. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2495. addSuccessorWithProb(CallBrMBB, Target);
  2496. }
  2497. CallBrMBB->normalizeSuccProbs();
  2498. // Drop into default successor.
  2499. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2500. MVT::Other, getControlRoot(),
  2501. DAG.getBasicBlock(Return)));
  2502. }
  2503. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2504. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2505. }
  2506. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2507. assert(FuncInfo.MBB->isEHPad() &&
  2508. "Call to landingpad not in landing pad!");
  2509. // If there aren't registers to copy the values into (e.g., during SjLj
  2510. // exceptions), then don't bother to create these DAG nodes.
  2511. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2512. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2513. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2514. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2515. return;
  2516. // If landingpad's return type is token type, we don't create DAG nodes
  2517. // for its exception pointer and selector value. The extraction of exception
  2518. // pointer or selector value from token type landingpads is not currently
  2519. // supported.
  2520. if (LP.getType()->isTokenTy())
  2521. return;
  2522. SmallVector<EVT, 2> ValueVTs;
  2523. SDLoc dl = getCurSDLoc();
  2524. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2525. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2526. // Get the two live-in registers as SDValues. The physregs have already been
  2527. // copied into virtual registers.
  2528. SDValue Ops[2];
  2529. if (FuncInfo.ExceptionPointerVirtReg) {
  2530. Ops[0] = DAG.getZExtOrTrunc(
  2531. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2532. FuncInfo.ExceptionPointerVirtReg,
  2533. TLI.getPointerTy(DAG.getDataLayout())),
  2534. dl, ValueVTs[0]);
  2535. } else {
  2536. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2537. }
  2538. Ops[1] = DAG.getZExtOrTrunc(
  2539. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2540. FuncInfo.ExceptionSelectorVirtReg,
  2541. TLI.getPointerTy(DAG.getDataLayout())),
  2542. dl, ValueVTs[1]);
  2543. // Merge into one.
  2544. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2545. DAG.getVTList(ValueVTs), Ops);
  2546. setValue(&LP, Res);
  2547. }
  2548. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2549. MachineBasicBlock *Last) {
  2550. // Update JTCases.
  2551. for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
  2552. if (SL->JTCases[i].first.HeaderBB == First)
  2553. SL->JTCases[i].first.HeaderBB = Last;
  2554. // Update BitTestCases.
  2555. for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
  2556. if (SL->BitTestCases[i].Parent == First)
  2557. SL->BitTestCases[i].Parent = Last;
  2558. }
  2559. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2560. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2561. // Update machine-CFG edges with unique successors.
  2562. SmallSet<BasicBlock*, 32> Done;
  2563. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2564. BasicBlock *BB = I.getSuccessor(i);
  2565. bool Inserted = Done.insert(BB).second;
  2566. if (!Inserted)
  2567. continue;
  2568. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2569. addSuccessorWithProb(IndirectBrMBB, Succ);
  2570. }
  2571. IndirectBrMBB->normalizeSuccProbs();
  2572. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2573. MVT::Other, getControlRoot(),
  2574. getValue(I.getAddress())));
  2575. }
  2576. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2577. if (!DAG.getTarget().Options.TrapUnreachable)
  2578. return;
  2579. // We may be able to ignore unreachable behind a noreturn call.
  2580. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2581. const BasicBlock &BB = *I.getParent();
  2582. if (&I != &BB.front()) {
  2583. BasicBlock::const_iterator PredI =
  2584. std::prev(BasicBlock::const_iterator(&I));
  2585. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2586. if (Call->doesNotReturn())
  2587. return;
  2588. }
  2589. }
  2590. }
  2591. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2592. }
  2593. void SelectionDAGBuilder::visitFSub(const User &I) {
  2594. // -0.0 - X --> fneg
  2595. Type *Ty = I.getType();
  2596. if (isa<Constant>(I.getOperand(0)) &&
  2597. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2598. SDValue Op2 = getValue(I.getOperand(1));
  2599. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2600. Op2.getValueType(), Op2));
  2601. return;
  2602. }
  2603. visitBinary(I, ISD::FSUB);
  2604. }
  2605. /// Checks if the given instruction performs a vector reduction, in which case
  2606. /// we have the freedom to alter the elements in the result as long as the
  2607. /// reduction of them stays unchanged.
  2608. static bool isVectorReductionOp(const User *I) {
  2609. const Instruction *Inst = dyn_cast<Instruction>(I);
  2610. if (!Inst || !Inst->getType()->isVectorTy())
  2611. return false;
  2612. auto OpCode = Inst->getOpcode();
  2613. switch (OpCode) {
  2614. case Instruction::Add:
  2615. case Instruction::Mul:
  2616. case Instruction::And:
  2617. case Instruction::Or:
  2618. case Instruction::Xor:
  2619. break;
  2620. case Instruction::FAdd:
  2621. case Instruction::FMul:
  2622. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2623. if (FPOp->getFastMathFlags().isFast())
  2624. break;
  2625. LLVM_FALLTHROUGH;
  2626. default:
  2627. return false;
  2628. }
  2629. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2630. // Ensure the reduction size is a power of 2.
  2631. if (!isPowerOf2_32(ElemNum))
  2632. return false;
  2633. unsigned ElemNumToReduce = ElemNum;
  2634. // Do DFS search on the def-use chain from the given instruction. We only
  2635. // allow four kinds of operations during the search until we reach the
  2636. // instruction that extracts the first element from the vector:
  2637. //
  2638. // 1. The reduction operation of the same opcode as the given instruction.
  2639. //
  2640. // 2. PHI node.
  2641. //
  2642. // 3. ShuffleVector instruction together with a reduction operation that
  2643. // does a partial reduction.
  2644. //
  2645. // 4. ExtractElement that extracts the first element from the vector, and we
  2646. // stop searching the def-use chain here.
  2647. //
  2648. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2649. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2650. // a reduction operation if we meet any other instructions other than those
  2651. // listed above.
  2652. SmallVector<const User *, 16> UsersToVisit{Inst};
  2653. SmallPtrSet<const User *, 16> Visited;
  2654. bool ReduxExtracted = false;
  2655. while (!UsersToVisit.empty()) {
  2656. auto User = UsersToVisit.back();
  2657. UsersToVisit.pop_back();
  2658. if (!Visited.insert(User).second)
  2659. continue;
  2660. for (const auto &U : User->users()) {
  2661. auto Inst = dyn_cast<Instruction>(U);
  2662. if (!Inst)
  2663. return false;
  2664. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2665. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2666. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2667. return false;
  2668. UsersToVisit.push_back(U);
  2669. } else if (const ShuffleVectorInst *ShufInst =
  2670. dyn_cast<ShuffleVectorInst>(U)) {
  2671. // Detect the following pattern: A ShuffleVector instruction together
  2672. // with a reduction that do partial reduction on the first and second
  2673. // ElemNumToReduce / 2 elements, and store the result in
  2674. // ElemNumToReduce / 2 elements in another vector.
  2675. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2676. if (ResultElements < ElemNum)
  2677. return false;
  2678. if (ElemNumToReduce == 1)
  2679. return false;
  2680. if (!isa<UndefValue>(U->getOperand(1)))
  2681. return false;
  2682. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2683. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2684. return false;
  2685. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2686. if (ShufInst->getMaskValue(i) != -1)
  2687. return false;
  2688. // There is only one user of this ShuffleVector instruction, which
  2689. // must be a reduction operation.
  2690. if (!U->hasOneUse())
  2691. return false;
  2692. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2693. if (!U2 || U2->getOpcode() != OpCode)
  2694. return false;
  2695. // Check operands of the reduction operation.
  2696. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2697. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2698. UsersToVisit.push_back(U2);
  2699. ElemNumToReduce /= 2;
  2700. } else
  2701. return false;
  2702. } else if (isa<ExtractElementInst>(U)) {
  2703. // At this moment we should have reduced all elements in the vector.
  2704. if (ElemNumToReduce != 1)
  2705. return false;
  2706. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2707. if (!Val || !Val->isZero())
  2708. return false;
  2709. ReduxExtracted = true;
  2710. } else
  2711. return false;
  2712. }
  2713. }
  2714. return ReduxExtracted;
  2715. }
  2716. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2717. SDNodeFlags Flags;
  2718. SDValue Op = getValue(I.getOperand(0));
  2719. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2720. Op, Flags);
  2721. setValue(&I, UnNodeValue);
  2722. }
  2723. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2724. SDNodeFlags Flags;
  2725. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2726. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2727. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2728. }
  2729. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2730. Flags.setExact(ExactOp->isExact());
  2731. }
  2732. if (isVectorReductionOp(&I)) {
  2733. Flags.setVectorReduction(true);
  2734. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2735. }
  2736. SDValue Op1 = getValue(I.getOperand(0));
  2737. SDValue Op2 = getValue(I.getOperand(1));
  2738. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2739. Op1, Op2, Flags);
  2740. setValue(&I, BinNodeValue);
  2741. }
  2742. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2743. SDValue Op1 = getValue(I.getOperand(0));
  2744. SDValue Op2 = getValue(I.getOperand(1));
  2745. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2746. Op1.getValueType(), DAG.getDataLayout());
  2747. // Coerce the shift amount to the right type if we can.
  2748. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2749. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2750. unsigned Op2Size = Op2.getValueSizeInBits();
  2751. SDLoc DL = getCurSDLoc();
  2752. // If the operand is smaller than the shift count type, promote it.
  2753. if (ShiftSize > Op2Size)
  2754. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2755. // If the operand is larger than the shift count type but the shift
  2756. // count type has enough bits to represent any shift value, truncate
  2757. // it now. This is a common case and it exposes the truncate to
  2758. // optimization early.
  2759. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2760. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2761. // Otherwise we'll need to temporarily settle for some other convenient
  2762. // type. Type legalization will make adjustments once the shiftee is split.
  2763. else
  2764. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2765. }
  2766. bool nuw = false;
  2767. bool nsw = false;
  2768. bool exact = false;
  2769. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2770. if (const OverflowingBinaryOperator *OFBinOp =
  2771. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2772. nuw = OFBinOp->hasNoUnsignedWrap();
  2773. nsw = OFBinOp->hasNoSignedWrap();
  2774. }
  2775. if (const PossiblyExactOperator *ExactOp =
  2776. dyn_cast<const PossiblyExactOperator>(&I))
  2777. exact = ExactOp->isExact();
  2778. }
  2779. SDNodeFlags Flags;
  2780. Flags.setExact(exact);
  2781. Flags.setNoSignedWrap(nsw);
  2782. Flags.setNoUnsignedWrap(nuw);
  2783. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2784. Flags);
  2785. setValue(&I, Res);
  2786. }
  2787. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2788. SDValue Op1 = getValue(I.getOperand(0));
  2789. SDValue Op2 = getValue(I.getOperand(1));
  2790. SDNodeFlags Flags;
  2791. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2792. cast<PossiblyExactOperator>(&I)->isExact());
  2793. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2794. Op2, Flags));
  2795. }
  2796. void SelectionDAGBuilder::visitICmp(const User &I) {
  2797. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2798. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2799. predicate = IC->getPredicate();
  2800. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2801. predicate = ICmpInst::Predicate(IC->getPredicate());
  2802. SDValue Op1 = getValue(I.getOperand(0));
  2803. SDValue Op2 = getValue(I.getOperand(1));
  2804. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2805. auto &TLI = DAG.getTargetLoweringInfo();
  2806. EVT MemVT =
  2807. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2808. // If a pointer's DAG type is larger than its memory type then the DAG values
  2809. // are zero-extended. This breaks signed comparisons so truncate back to the
  2810. // underlying type before doing the compare.
  2811. if (Op1.getValueType() != MemVT) {
  2812. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2813. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2814. }
  2815. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2816. I.getType());
  2817. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2818. }
  2819. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2820. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2821. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2822. predicate = FC->getPredicate();
  2823. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2824. predicate = FCmpInst::Predicate(FC->getPredicate());
  2825. SDValue Op1 = getValue(I.getOperand(0));
  2826. SDValue Op2 = getValue(I.getOperand(1));
  2827. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2828. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2829. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2830. Condition = getFCmpCodeWithoutNaN(Condition);
  2831. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2832. I.getType());
  2833. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2834. }
  2835. // Check if the condition of the select has one use or two users that are both
  2836. // selects with the same condition.
  2837. static bool hasOnlySelectUsers(const Value *Cond) {
  2838. return llvm::all_of(Cond->users(), [](const Value *V) {
  2839. return isa<SelectInst>(V);
  2840. });
  2841. }
  2842. void SelectionDAGBuilder::visitSelect(const User &I) {
  2843. SmallVector<EVT, 4> ValueVTs;
  2844. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2845. ValueVTs);
  2846. unsigned NumValues = ValueVTs.size();
  2847. if (NumValues == 0) return;
  2848. SmallVector<SDValue, 4> Values(NumValues);
  2849. SDValue Cond = getValue(I.getOperand(0));
  2850. SDValue LHSVal = getValue(I.getOperand(1));
  2851. SDValue RHSVal = getValue(I.getOperand(2));
  2852. auto BaseOps = {Cond};
  2853. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2854. ISD::VSELECT : ISD::SELECT;
  2855. bool IsUnaryAbs = false;
  2856. // Min/max matching is only viable if all output VTs are the same.
  2857. if (is_splat(ValueVTs)) {
  2858. EVT VT = ValueVTs[0];
  2859. LLVMContext &Ctx = *DAG.getContext();
  2860. auto &TLI = DAG.getTargetLoweringInfo();
  2861. // We care about the legality of the operation after it has been type
  2862. // legalized.
  2863. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
  2864. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2865. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2866. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2867. // min/max is legal on the scalar type.
  2868. bool UseScalarMinMax = VT.isVector() &&
  2869. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2870. Value *LHS, *RHS;
  2871. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2872. ISD::NodeType Opc = ISD::DELETED_NODE;
  2873. switch (SPR.Flavor) {
  2874. case SPF_UMAX: Opc = ISD::UMAX; break;
  2875. case SPF_UMIN: Opc = ISD::UMIN; break;
  2876. case SPF_SMAX: Opc = ISD::SMAX; break;
  2877. case SPF_SMIN: Opc = ISD::SMIN; break;
  2878. case SPF_FMINNUM:
  2879. switch (SPR.NaNBehavior) {
  2880. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2881. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2882. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2883. case SPNB_RETURNS_ANY: {
  2884. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2885. Opc = ISD::FMINNUM;
  2886. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2887. Opc = ISD::FMINIMUM;
  2888. else if (UseScalarMinMax)
  2889. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2890. ISD::FMINNUM : ISD::FMINIMUM;
  2891. break;
  2892. }
  2893. }
  2894. break;
  2895. case SPF_FMAXNUM:
  2896. switch (SPR.NaNBehavior) {
  2897. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2898. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2899. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2900. case SPNB_RETURNS_ANY:
  2901. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2902. Opc = ISD::FMAXNUM;
  2903. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2904. Opc = ISD::FMAXIMUM;
  2905. else if (UseScalarMinMax)
  2906. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2907. ISD::FMAXNUM : ISD::FMAXIMUM;
  2908. break;
  2909. }
  2910. break;
  2911. case SPF_ABS:
  2912. IsUnaryAbs = true;
  2913. Opc = ISD::ABS;
  2914. break;
  2915. case SPF_NABS:
  2916. // TODO: we need to produce sub(0, abs(X)).
  2917. default: break;
  2918. }
  2919. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2920. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2921. (UseScalarMinMax &&
  2922. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2923. // If the underlying comparison instruction is used by any other
  2924. // instruction, the consumed instructions won't be destroyed, so it is
  2925. // not profitable to convert to a min/max.
  2926. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2927. OpCode = Opc;
  2928. LHSVal = getValue(LHS);
  2929. RHSVal = getValue(RHS);
  2930. BaseOps = {};
  2931. }
  2932. if (IsUnaryAbs) {
  2933. OpCode = Opc;
  2934. LHSVal = getValue(LHS);
  2935. BaseOps = {};
  2936. }
  2937. }
  2938. if (IsUnaryAbs) {
  2939. for (unsigned i = 0; i != NumValues; ++i) {
  2940. Values[i] =
  2941. DAG.getNode(OpCode, getCurSDLoc(),
  2942. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2943. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2944. }
  2945. } else {
  2946. for (unsigned i = 0; i != NumValues; ++i) {
  2947. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2948. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2949. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2950. Values[i] = DAG.getNode(
  2951. OpCode, getCurSDLoc(),
  2952. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2953. }
  2954. }
  2955. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2956. DAG.getVTList(ValueVTs), Values));
  2957. }
  2958. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2959. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2960. SDValue N = getValue(I.getOperand(0));
  2961. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2962. I.getType());
  2963. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2964. }
  2965. void SelectionDAGBuilder::visitZExt(const User &I) {
  2966. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2967. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2968. SDValue N = getValue(I.getOperand(0));
  2969. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2970. I.getType());
  2971. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2972. }
  2973. void SelectionDAGBuilder::visitSExt(const User &I) {
  2974. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2975. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2976. SDValue N = getValue(I.getOperand(0));
  2977. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2978. I.getType());
  2979. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2980. }
  2981. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2982. // FPTrunc is never a no-op cast, no need to check
  2983. SDValue N = getValue(I.getOperand(0));
  2984. SDLoc dl = getCurSDLoc();
  2985. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2986. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2987. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2988. DAG.getTargetConstant(
  2989. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2990. }
  2991. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2992. // FPExt is never a no-op cast, no need to check
  2993. SDValue N = getValue(I.getOperand(0));
  2994. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2995. I.getType());
  2996. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2997. }
  2998. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2999. // FPToUI is never a no-op cast, no need to check
  3000. SDValue N = getValue(I.getOperand(0));
  3001. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3002. I.getType());
  3003. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3004. }
  3005. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3006. // FPToSI is never a no-op cast, no need to check
  3007. SDValue N = getValue(I.getOperand(0));
  3008. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3009. I.getType());
  3010. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3011. }
  3012. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3013. // UIToFP is never a no-op cast, no need to check
  3014. SDValue N = getValue(I.getOperand(0));
  3015. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3016. I.getType());
  3017. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3018. }
  3019. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3020. // SIToFP is never a no-op cast, no need to check
  3021. SDValue N = getValue(I.getOperand(0));
  3022. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3023. I.getType());
  3024. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3025. }
  3026. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3027. // What to do depends on the size of the integer and the size of the pointer.
  3028. // We can either truncate, zero extend, or no-op, accordingly.
  3029. SDValue N = getValue(I.getOperand(0));
  3030. auto &TLI = DAG.getTargetLoweringInfo();
  3031. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3032. I.getType());
  3033. EVT PtrMemVT =
  3034. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3035. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3036. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3037. setValue(&I, N);
  3038. }
  3039. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3040. // What to do depends on the size of the integer and the size of the pointer.
  3041. // We can either truncate, zero extend, or no-op, accordingly.
  3042. SDValue N = getValue(I.getOperand(0));
  3043. auto &TLI = DAG.getTargetLoweringInfo();
  3044. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3045. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3046. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3047. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3048. setValue(&I, N);
  3049. }
  3050. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3051. SDValue N = getValue(I.getOperand(0));
  3052. SDLoc dl = getCurSDLoc();
  3053. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3054. I.getType());
  3055. // BitCast assures us that source and destination are the same size so this is
  3056. // either a BITCAST or a no-op.
  3057. if (DestVT != N.getValueType())
  3058. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3059. DestVT, N)); // convert types.
  3060. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3061. // might fold any kind of constant expression to an integer constant and that
  3062. // is not what we are looking for. Only recognize a bitcast of a genuine
  3063. // constant integer as an opaque constant.
  3064. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3065. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3066. /*isOpaque*/true));
  3067. else
  3068. setValue(&I, N); // noop cast.
  3069. }
  3070. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3071. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3072. const Value *SV = I.getOperand(0);
  3073. SDValue N = getValue(SV);
  3074. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3075. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3076. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3077. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3078. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3079. setValue(&I, N);
  3080. }
  3081. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3082. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3083. SDValue InVec = getValue(I.getOperand(0));
  3084. SDValue InVal = getValue(I.getOperand(1));
  3085. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3086. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3087. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3088. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3089. InVec, InVal, InIdx));
  3090. }
  3091. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3092. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3093. SDValue InVec = getValue(I.getOperand(0));
  3094. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3095. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3096. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3097. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3098. InVec, InIdx));
  3099. }
  3100. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3101. SDValue Src1 = getValue(I.getOperand(0));
  3102. SDValue Src2 = getValue(I.getOperand(1));
  3103. SDLoc DL = getCurSDLoc();
  3104. SmallVector<int, 8> Mask;
  3105. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3106. unsigned MaskNumElts = Mask.size();
  3107. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3108. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3109. EVT SrcVT = Src1.getValueType();
  3110. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3111. if (SrcNumElts == MaskNumElts) {
  3112. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3113. return;
  3114. }
  3115. // Normalize the shuffle vector since mask and vector length don't match.
  3116. if (SrcNumElts < MaskNumElts) {
  3117. // Mask is longer than the source vectors. We can use concatenate vector to
  3118. // make the mask and vectors lengths match.
  3119. if (MaskNumElts % SrcNumElts == 0) {
  3120. // Mask length is a multiple of the source vector length.
  3121. // Check if the shuffle is some kind of concatenation of the input
  3122. // vectors.
  3123. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3124. bool IsConcat = true;
  3125. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3126. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3127. int Idx = Mask[i];
  3128. if (Idx < 0)
  3129. continue;
  3130. // Ensure the indices in each SrcVT sized piece are sequential and that
  3131. // the same source is used for the whole piece.
  3132. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3133. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3134. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3135. IsConcat = false;
  3136. break;
  3137. }
  3138. // Remember which source this index came from.
  3139. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3140. }
  3141. // The shuffle is concatenating multiple vectors together. Just emit
  3142. // a CONCAT_VECTORS operation.
  3143. if (IsConcat) {
  3144. SmallVector<SDValue, 8> ConcatOps;
  3145. for (auto Src : ConcatSrcs) {
  3146. if (Src < 0)
  3147. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3148. else if (Src == 0)
  3149. ConcatOps.push_back(Src1);
  3150. else
  3151. ConcatOps.push_back(Src2);
  3152. }
  3153. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3154. return;
  3155. }
  3156. }
  3157. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3158. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3159. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3160. PaddedMaskNumElts);
  3161. // Pad both vectors with undefs to make them the same length as the mask.
  3162. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3163. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3164. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3165. MOps1[0] = Src1;
  3166. MOps2[0] = Src2;
  3167. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3168. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3169. // Readjust mask for new input vector length.
  3170. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3171. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3172. int Idx = Mask[i];
  3173. if (Idx >= (int)SrcNumElts)
  3174. Idx -= SrcNumElts - PaddedMaskNumElts;
  3175. MappedOps[i] = Idx;
  3176. }
  3177. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3178. // If the concatenated vector was padded, extract a subvector with the
  3179. // correct number of elements.
  3180. if (MaskNumElts != PaddedMaskNumElts)
  3181. Result = DAG.getNode(
  3182. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3183. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3184. setValue(&I, Result);
  3185. return;
  3186. }
  3187. if (SrcNumElts > MaskNumElts) {
  3188. // Analyze the access pattern of the vector to see if we can extract
  3189. // two subvectors and do the shuffle.
  3190. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3191. bool CanExtract = true;
  3192. for (int Idx : Mask) {
  3193. unsigned Input = 0;
  3194. if (Idx < 0)
  3195. continue;
  3196. if (Idx >= (int)SrcNumElts) {
  3197. Input = 1;
  3198. Idx -= SrcNumElts;
  3199. }
  3200. // If all the indices come from the same MaskNumElts sized portion of
  3201. // the sources we can use extract. Also make sure the extract wouldn't
  3202. // extract past the end of the source.
  3203. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3204. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3205. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3206. CanExtract = false;
  3207. // Make sure we always update StartIdx as we use it to track if all
  3208. // elements are undef.
  3209. StartIdx[Input] = NewStartIdx;
  3210. }
  3211. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3212. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3213. return;
  3214. }
  3215. if (CanExtract) {
  3216. // Extract appropriate subvector and generate a vector shuffle
  3217. for (unsigned Input = 0; Input < 2; ++Input) {
  3218. SDValue &Src = Input == 0 ? Src1 : Src2;
  3219. if (StartIdx[Input] < 0)
  3220. Src = DAG.getUNDEF(VT);
  3221. else {
  3222. Src = DAG.getNode(
  3223. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3224. DAG.getConstant(StartIdx[Input], DL,
  3225. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3226. }
  3227. }
  3228. // Calculate new mask.
  3229. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3230. for (int &Idx : MappedOps) {
  3231. if (Idx >= (int)SrcNumElts)
  3232. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3233. else if (Idx >= 0)
  3234. Idx -= StartIdx[0];
  3235. }
  3236. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3237. return;
  3238. }
  3239. }
  3240. // We can't use either concat vectors or extract subvectors so fall back to
  3241. // replacing the shuffle with extract and build vector.
  3242. // to insert and build vector.
  3243. EVT EltVT = VT.getVectorElementType();
  3244. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3245. SmallVector<SDValue,8> Ops;
  3246. for (int Idx : Mask) {
  3247. SDValue Res;
  3248. if (Idx < 0) {
  3249. Res = DAG.getUNDEF(EltVT);
  3250. } else {
  3251. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3252. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3253. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3254. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3255. }
  3256. Ops.push_back(Res);
  3257. }
  3258. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3259. }
  3260. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3261. ArrayRef<unsigned> Indices;
  3262. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3263. Indices = IV->getIndices();
  3264. else
  3265. Indices = cast<ConstantExpr>(&I)->getIndices();
  3266. const Value *Op0 = I.getOperand(0);
  3267. const Value *Op1 = I.getOperand(1);
  3268. Type *AggTy = I.getType();
  3269. Type *ValTy = Op1->getType();
  3270. bool IntoUndef = isa<UndefValue>(Op0);
  3271. bool FromUndef = isa<UndefValue>(Op1);
  3272. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3273. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3274. SmallVector<EVT, 4> AggValueVTs;
  3275. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3276. SmallVector<EVT, 4> ValValueVTs;
  3277. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3278. unsigned NumAggValues = AggValueVTs.size();
  3279. unsigned NumValValues = ValValueVTs.size();
  3280. SmallVector<SDValue, 4> Values(NumAggValues);
  3281. // Ignore an insertvalue that produces an empty object
  3282. if (!NumAggValues) {
  3283. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3284. return;
  3285. }
  3286. SDValue Agg = getValue(Op0);
  3287. unsigned i = 0;
  3288. // Copy the beginning value(s) from the original aggregate.
  3289. for (; i != LinearIndex; ++i)
  3290. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3291. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3292. // Copy values from the inserted value(s).
  3293. if (NumValValues) {
  3294. SDValue Val = getValue(Op1);
  3295. for (; i != LinearIndex + NumValValues; ++i)
  3296. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3297. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3298. }
  3299. // Copy remaining value(s) from the original aggregate.
  3300. for (; i != NumAggValues; ++i)
  3301. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3302. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3303. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3304. DAG.getVTList(AggValueVTs), Values));
  3305. }
  3306. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3307. ArrayRef<unsigned> Indices;
  3308. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3309. Indices = EV->getIndices();
  3310. else
  3311. Indices = cast<ConstantExpr>(&I)->getIndices();
  3312. const Value *Op0 = I.getOperand(0);
  3313. Type *AggTy = Op0->getType();
  3314. Type *ValTy = I.getType();
  3315. bool OutOfUndef = isa<UndefValue>(Op0);
  3316. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3317. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3318. SmallVector<EVT, 4> ValValueVTs;
  3319. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3320. unsigned NumValValues = ValValueVTs.size();
  3321. // Ignore a extractvalue that produces an empty object
  3322. if (!NumValValues) {
  3323. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3324. return;
  3325. }
  3326. SmallVector<SDValue, 4> Values(NumValValues);
  3327. SDValue Agg = getValue(Op0);
  3328. // Copy out the selected value(s).
  3329. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3330. Values[i - LinearIndex] =
  3331. OutOfUndef ?
  3332. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3333. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3334. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3335. DAG.getVTList(ValValueVTs), Values));
  3336. }
  3337. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3338. Value *Op0 = I.getOperand(0);
  3339. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3340. // element which holds a pointer.
  3341. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3342. SDValue N = getValue(Op0);
  3343. SDLoc dl = getCurSDLoc();
  3344. auto &TLI = DAG.getTargetLoweringInfo();
  3345. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3346. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3347. // Normalize Vector GEP - all scalar operands should be converted to the
  3348. // splat vector.
  3349. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3350. I.getType()->getVectorNumElements() : 0;
  3351. if (VectorWidth && !N.getValueType().isVector()) {
  3352. LLVMContext &Context = *DAG.getContext();
  3353. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3354. N = DAG.getSplatBuildVector(VT, dl, N);
  3355. }
  3356. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3357. GTI != E; ++GTI) {
  3358. const Value *Idx = GTI.getOperand();
  3359. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3360. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3361. if (Field) {
  3362. // N = N + Offset
  3363. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3364. // In an inbounds GEP with an offset that is nonnegative even when
  3365. // interpreted as signed, assume there is no unsigned overflow.
  3366. SDNodeFlags Flags;
  3367. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3368. Flags.setNoUnsignedWrap(true);
  3369. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3370. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3371. }
  3372. } else {
  3373. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3374. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3375. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3376. // If this is a scalar constant or a splat vector of constants,
  3377. // handle it quickly.
  3378. const auto *C = dyn_cast<Constant>(Idx);
  3379. if (C && isa<VectorType>(C->getType()))
  3380. C = C->getSplatValue();
  3381. if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
  3382. if (CI->isZero())
  3383. continue;
  3384. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3385. LLVMContext &Context = *DAG.getContext();
  3386. SDValue OffsVal = VectorWidth ?
  3387. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3388. DAG.getConstant(Offs, dl, IdxTy);
  3389. // In an inbounds GEP with an offset that is nonnegative even when
  3390. // interpreted as signed, assume there is no unsigned overflow.
  3391. SDNodeFlags Flags;
  3392. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3393. Flags.setNoUnsignedWrap(true);
  3394. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3395. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3396. continue;
  3397. }
  3398. // N = N + Idx * ElementSize;
  3399. SDValue IdxN = getValue(Idx);
  3400. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3401. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3402. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3403. }
  3404. // If the index is smaller or larger than intptr_t, truncate or extend
  3405. // it.
  3406. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3407. // If this is a multiply by a power of two, turn it into a shl
  3408. // immediately. This is a very common case.
  3409. if (ElementSize != 1) {
  3410. if (ElementSize.isPowerOf2()) {
  3411. unsigned Amt = ElementSize.logBase2();
  3412. IdxN = DAG.getNode(ISD::SHL, dl,
  3413. N.getValueType(), IdxN,
  3414. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3415. } else {
  3416. SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
  3417. IdxN.getValueType());
  3418. IdxN = DAG.getNode(ISD::MUL, dl,
  3419. N.getValueType(), IdxN, Scale);
  3420. }
  3421. }
  3422. N = DAG.getNode(ISD::ADD, dl,
  3423. N.getValueType(), N, IdxN);
  3424. }
  3425. }
  3426. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3427. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3428. setValue(&I, N);
  3429. }
  3430. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3431. // If this is a fixed sized alloca in the entry block of the function,
  3432. // allocate it statically on the stack.
  3433. if (FuncInfo.StaticAllocaMap.count(&I))
  3434. return; // getValue will auto-populate this.
  3435. SDLoc dl = getCurSDLoc();
  3436. Type *Ty = I.getAllocatedType();
  3437. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3438. auto &DL = DAG.getDataLayout();
  3439. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3440. unsigned Align =
  3441. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3442. SDValue AllocSize = getValue(I.getArraySize());
  3443. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3444. if (AllocSize.getValueType() != IntPtr)
  3445. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3446. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3447. AllocSize,
  3448. DAG.getConstant(TySize, dl, IntPtr));
  3449. // Handle alignment. If the requested alignment is less than or equal to
  3450. // the stack alignment, ignore it. If the size is greater than or equal to
  3451. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3452. unsigned StackAlign =
  3453. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3454. if (Align <= StackAlign)
  3455. Align = 0;
  3456. // Round the size of the allocation up to the stack alignment size
  3457. // by add SA-1 to the size. This doesn't overflow because we're computing
  3458. // an address inside an alloca.
  3459. SDNodeFlags Flags;
  3460. Flags.setNoUnsignedWrap(true);
  3461. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3462. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3463. // Mask out the low bits for alignment purposes.
  3464. AllocSize =
  3465. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3466. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3467. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3468. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3469. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3470. setValue(&I, DSA);
  3471. DAG.setRoot(DSA.getValue(1));
  3472. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3473. }
  3474. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3475. if (I.isAtomic())
  3476. return visitAtomicLoad(I);
  3477. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3478. const Value *SV = I.getOperand(0);
  3479. if (TLI.supportSwiftError()) {
  3480. // Swifterror values can come from either a function parameter with
  3481. // swifterror attribute or an alloca with swifterror attribute.
  3482. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3483. if (Arg->hasSwiftErrorAttr())
  3484. return visitLoadFromSwiftError(I);
  3485. }
  3486. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3487. if (Alloca->isSwiftError())
  3488. return visitLoadFromSwiftError(I);
  3489. }
  3490. }
  3491. SDValue Ptr = getValue(SV);
  3492. Type *Ty = I.getType();
  3493. bool isVolatile = I.isVolatile();
  3494. bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
  3495. bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
  3496. bool isDereferenceable =
  3497. isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
  3498. unsigned Alignment = I.getAlignment();
  3499. AAMDNodes AAInfo;
  3500. I.getAAMetadata(AAInfo);
  3501. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3502. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3503. SmallVector<uint64_t, 4> Offsets;
  3504. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3505. unsigned NumValues = ValueVTs.size();
  3506. if (NumValues == 0)
  3507. return;
  3508. SDValue Root;
  3509. bool ConstantMemory = false;
  3510. if (isVolatile || NumValues > MaxParallelChains)
  3511. // Serialize volatile loads with other side effects.
  3512. Root = getRoot();
  3513. else if (AA &&
  3514. AA->pointsToConstantMemory(MemoryLocation(
  3515. SV,
  3516. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3517. AAInfo))) {
  3518. // Do not serialize (non-volatile) loads of constant memory with anything.
  3519. Root = DAG.getEntryNode();
  3520. ConstantMemory = true;
  3521. } else {
  3522. // Do not serialize non-volatile loads against each other.
  3523. Root = DAG.getRoot();
  3524. }
  3525. SDLoc dl = getCurSDLoc();
  3526. if (isVolatile)
  3527. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3528. // An aggregate load cannot wrap around the address space, so offsets to its
  3529. // parts don't wrap either.
  3530. SDNodeFlags Flags;
  3531. Flags.setNoUnsignedWrap(true);
  3532. SmallVector<SDValue, 4> Values(NumValues);
  3533. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3534. EVT PtrVT = Ptr.getValueType();
  3535. unsigned ChainI = 0;
  3536. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3537. // Serializing loads here may result in excessive register pressure, and
  3538. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3539. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3540. // they are side-effect free or do not alias. The optimizer should really
  3541. // avoid this case by converting large object/array copies to llvm.memcpy
  3542. // (MaxParallelChains should always remain as failsafe).
  3543. if (ChainI == MaxParallelChains) {
  3544. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3545. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3546. makeArrayRef(Chains.data(), ChainI));
  3547. Root = Chain;
  3548. ChainI = 0;
  3549. }
  3550. SDValue A = DAG.getNode(ISD::ADD, dl,
  3551. PtrVT, Ptr,
  3552. DAG.getConstant(Offsets[i], dl, PtrVT),
  3553. Flags);
  3554. auto MMOFlags = MachineMemOperand::MONone;
  3555. if (isVolatile)
  3556. MMOFlags |= MachineMemOperand::MOVolatile;
  3557. if (isNonTemporal)
  3558. MMOFlags |= MachineMemOperand::MONonTemporal;
  3559. if (isInvariant)
  3560. MMOFlags |= MachineMemOperand::MOInvariant;
  3561. if (isDereferenceable)
  3562. MMOFlags |= MachineMemOperand::MODereferenceable;
  3563. MMOFlags |= TLI.getMMOFlags(I);
  3564. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3565. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3566. MMOFlags, AAInfo, Ranges);
  3567. Chains[ChainI] = L.getValue(1);
  3568. if (MemVTs[i] != ValueVTs[i])
  3569. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3570. Values[i] = L;
  3571. }
  3572. if (!ConstantMemory) {
  3573. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3574. makeArrayRef(Chains.data(), ChainI));
  3575. if (isVolatile)
  3576. DAG.setRoot(Chain);
  3577. else
  3578. PendingLoads.push_back(Chain);
  3579. }
  3580. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3581. DAG.getVTList(ValueVTs), Values));
  3582. }
  3583. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3584. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3585. "call visitStoreToSwiftError when backend supports swifterror");
  3586. SmallVector<EVT, 4> ValueVTs;
  3587. SmallVector<uint64_t, 4> Offsets;
  3588. const Value *SrcV = I.getOperand(0);
  3589. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3590. SrcV->getType(), ValueVTs, &Offsets);
  3591. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3592. "expect a single EVT for swifterror");
  3593. SDValue Src = getValue(SrcV);
  3594. // Create a virtual register, then update the virtual register.
  3595. Register VReg =
  3596. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3597. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3598. // Chain can be getRoot or getControlRoot.
  3599. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3600. SDValue(Src.getNode(), Src.getResNo()));
  3601. DAG.setRoot(CopyNode);
  3602. }
  3603. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3604. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3605. "call visitLoadFromSwiftError when backend supports swifterror");
  3606. assert(!I.isVolatile() &&
  3607. !I.hasMetadata(LLVMContext::MD_nontemporal) &&
  3608. !I.hasMetadata(LLVMContext::MD_invariant_load) &&
  3609. "Support volatile, non temporal, invariant for load_from_swift_error");
  3610. const Value *SV = I.getOperand(0);
  3611. Type *Ty = I.getType();
  3612. AAMDNodes AAInfo;
  3613. I.getAAMetadata(AAInfo);
  3614. assert(
  3615. (!AA ||
  3616. !AA->pointsToConstantMemory(MemoryLocation(
  3617. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3618. AAInfo))) &&
  3619. "load_from_swift_error should not be constant memory");
  3620. SmallVector<EVT, 4> ValueVTs;
  3621. SmallVector<uint64_t, 4> Offsets;
  3622. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3623. ValueVTs, &Offsets);
  3624. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3625. "expect a single EVT for swifterror");
  3626. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3627. SDValue L = DAG.getCopyFromReg(
  3628. getRoot(), getCurSDLoc(),
  3629. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3630. setValue(&I, L);
  3631. }
  3632. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3633. if (I.isAtomic())
  3634. return visitAtomicStore(I);
  3635. const Value *SrcV = I.getOperand(0);
  3636. const Value *PtrV = I.getOperand(1);
  3637. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3638. if (TLI.supportSwiftError()) {
  3639. // Swifterror values can come from either a function parameter with
  3640. // swifterror attribute or an alloca with swifterror attribute.
  3641. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3642. if (Arg->hasSwiftErrorAttr())
  3643. return visitStoreToSwiftError(I);
  3644. }
  3645. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3646. if (Alloca->isSwiftError())
  3647. return visitStoreToSwiftError(I);
  3648. }
  3649. }
  3650. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3651. SmallVector<uint64_t, 4> Offsets;
  3652. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3653. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3654. unsigned NumValues = ValueVTs.size();
  3655. if (NumValues == 0)
  3656. return;
  3657. // Get the lowered operands. Note that we do this after
  3658. // checking if NumResults is zero, because with zero results
  3659. // the operands won't have values in the map.
  3660. SDValue Src = getValue(SrcV);
  3661. SDValue Ptr = getValue(PtrV);
  3662. SDValue Root = getRoot();
  3663. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3664. SDLoc dl = getCurSDLoc();
  3665. EVT PtrVT = Ptr.getValueType();
  3666. unsigned Alignment = I.getAlignment();
  3667. AAMDNodes AAInfo;
  3668. I.getAAMetadata(AAInfo);
  3669. auto MMOFlags = MachineMemOperand::MONone;
  3670. if (I.isVolatile())
  3671. MMOFlags |= MachineMemOperand::MOVolatile;
  3672. if (I.hasMetadata(LLVMContext::MD_nontemporal))
  3673. MMOFlags |= MachineMemOperand::MONonTemporal;
  3674. MMOFlags |= TLI.getMMOFlags(I);
  3675. // An aggregate load cannot wrap around the address space, so offsets to its
  3676. // parts don't wrap either.
  3677. SDNodeFlags Flags;
  3678. Flags.setNoUnsignedWrap(true);
  3679. unsigned ChainI = 0;
  3680. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3681. // See visitLoad comments.
  3682. if (ChainI == MaxParallelChains) {
  3683. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3684. makeArrayRef(Chains.data(), ChainI));
  3685. Root = Chain;
  3686. ChainI = 0;
  3687. }
  3688. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3689. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3690. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3691. if (MemVTs[i] != ValueVTs[i])
  3692. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3693. SDValue St =
  3694. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3695. Alignment, MMOFlags, AAInfo);
  3696. Chains[ChainI] = St;
  3697. }
  3698. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3699. makeArrayRef(Chains.data(), ChainI));
  3700. DAG.setRoot(StoreNode);
  3701. }
  3702. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3703. bool IsCompressing) {
  3704. SDLoc sdl = getCurSDLoc();
  3705. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3706. unsigned& Alignment) {
  3707. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3708. Src0 = I.getArgOperand(0);
  3709. Ptr = I.getArgOperand(1);
  3710. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3711. Mask = I.getArgOperand(3);
  3712. };
  3713. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3714. unsigned& Alignment) {
  3715. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3716. Src0 = I.getArgOperand(0);
  3717. Ptr = I.getArgOperand(1);
  3718. Mask = I.getArgOperand(2);
  3719. Alignment = 0;
  3720. };
  3721. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3722. unsigned Alignment;
  3723. if (IsCompressing)
  3724. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3725. else
  3726. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3727. SDValue Ptr = getValue(PtrOperand);
  3728. SDValue Src0 = getValue(Src0Operand);
  3729. SDValue Mask = getValue(MaskOperand);
  3730. EVT VT = Src0.getValueType();
  3731. if (!Alignment)
  3732. Alignment = DAG.getEVTAlignment(VT);
  3733. AAMDNodes AAInfo;
  3734. I.getAAMetadata(AAInfo);
  3735. MachineMemOperand *MMO =
  3736. DAG.getMachineFunction().
  3737. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3738. MachineMemOperand::MOStore, VT.getStoreSize(),
  3739. Alignment, AAInfo);
  3740. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3741. MMO, false /* Truncating */,
  3742. IsCompressing);
  3743. DAG.setRoot(StoreNode);
  3744. setValue(&I, StoreNode);
  3745. }
  3746. // Get a uniform base for the Gather/Scatter intrinsic.
  3747. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3748. // We try to represent it as a base pointer + vector of indices.
  3749. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3750. // The first operand of the GEP may be a single pointer or a vector of pointers
  3751. // Example:
  3752. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3753. // or
  3754. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3755. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3756. //
  3757. // When the first GEP operand is a single pointer - it is the uniform base we
  3758. // are looking for. If first operand of the GEP is a splat vector - we
  3759. // extract the splat value and use it as a uniform base.
  3760. // In all other cases the function returns 'false'.
  3761. static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
  3762. ISD::MemIndexType &IndexType, SDValue &Scale,
  3763. SelectionDAGBuilder *SDB) {
  3764. SelectionDAG& DAG = SDB->DAG;
  3765. LLVMContext &Context = *DAG.getContext();
  3766. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3767. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3768. if (!GEP)
  3769. return false;
  3770. const Value *GEPPtr = GEP->getPointerOperand();
  3771. if (!GEPPtr->getType()->isVectorTy())
  3772. Ptr = GEPPtr;
  3773. else if (!(Ptr = getSplatValue(GEPPtr)))
  3774. return false;
  3775. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3776. Value *IndexVal = GEP->getOperand(FinalIndex);
  3777. // Ensure all the other indices are 0.
  3778. for (unsigned i = 1; i < FinalIndex; ++i) {
  3779. auto *C = dyn_cast<Constant>(GEP->getOperand(i));
  3780. if (!C)
  3781. return false;
  3782. if (isa<VectorType>(C->getType()))
  3783. C = C->getSplatValue();
  3784. auto *CI = dyn_cast_or_null<ConstantInt>(C);
  3785. if (!CI || !CI->isZero())
  3786. return false;
  3787. }
  3788. // The operands of the GEP may be defined in another basic block.
  3789. // In this case we'll not find nodes for the operands.
  3790. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3791. return false;
  3792. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3793. const DataLayout &DL = DAG.getDataLayout();
  3794. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3795. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3796. Base = SDB->getValue(Ptr);
  3797. Index = SDB->getValue(IndexVal);
  3798. IndexType = ISD::SIGNED_SCALED;
  3799. if (!Index.getValueType().isVector()) {
  3800. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3801. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3802. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3803. }
  3804. return true;
  3805. }
  3806. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3807. SDLoc sdl = getCurSDLoc();
  3808. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3809. const Value *Ptr = I.getArgOperand(1);
  3810. SDValue Src0 = getValue(I.getArgOperand(0));
  3811. SDValue Mask = getValue(I.getArgOperand(3));
  3812. EVT VT = Src0.getValueType();
  3813. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3814. if (!Alignment)
  3815. Alignment = DAG.getEVTAlignment(VT);
  3816. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3817. AAMDNodes AAInfo;
  3818. I.getAAMetadata(AAInfo);
  3819. SDValue Base;
  3820. SDValue Index;
  3821. ISD::MemIndexType IndexType;
  3822. SDValue Scale;
  3823. const Value *BasePtr = Ptr;
  3824. bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
  3825. this);
  3826. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3827. MachineMemOperand *MMO = DAG.getMachineFunction().
  3828. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3829. MachineMemOperand::MOStore, VT.getStoreSize(),
  3830. Alignment, AAInfo);
  3831. if (!UniformBase) {
  3832. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3833. Index = getValue(Ptr);
  3834. IndexType = ISD::SIGNED_SCALED;
  3835. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3836. }
  3837. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3838. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3839. Ops, MMO, IndexType);
  3840. DAG.setRoot(Scatter);
  3841. setValue(&I, Scatter);
  3842. }
  3843. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3844. SDLoc sdl = getCurSDLoc();
  3845. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3846. unsigned& Alignment) {
  3847. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3848. Ptr = I.getArgOperand(0);
  3849. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3850. Mask = I.getArgOperand(2);
  3851. Src0 = I.getArgOperand(3);
  3852. };
  3853. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3854. unsigned& Alignment) {
  3855. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3856. Ptr = I.getArgOperand(0);
  3857. Alignment = 0;
  3858. Mask = I.getArgOperand(1);
  3859. Src0 = I.getArgOperand(2);
  3860. };
  3861. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3862. unsigned Alignment;
  3863. if (IsExpanding)
  3864. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3865. else
  3866. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3867. SDValue Ptr = getValue(PtrOperand);
  3868. SDValue Src0 = getValue(Src0Operand);
  3869. SDValue Mask = getValue(MaskOperand);
  3870. EVT VT = Src0.getValueType();
  3871. if (!Alignment)
  3872. Alignment = DAG.getEVTAlignment(VT);
  3873. AAMDNodes AAInfo;
  3874. I.getAAMetadata(AAInfo);
  3875. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3876. // Do not serialize masked loads of constant memory with anything.
  3877. bool AddToChain =
  3878. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3879. PtrOperand,
  3880. LocationSize::precise(
  3881. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3882. AAInfo));
  3883. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3884. MachineMemOperand *MMO =
  3885. DAG.getMachineFunction().
  3886. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3887. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3888. Alignment, AAInfo, Ranges);
  3889. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3890. ISD::NON_EXTLOAD, IsExpanding);
  3891. if (AddToChain)
  3892. PendingLoads.push_back(Load.getValue(1));
  3893. setValue(&I, Load);
  3894. }
  3895. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3896. SDLoc sdl = getCurSDLoc();
  3897. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3898. const Value *Ptr = I.getArgOperand(0);
  3899. SDValue Src0 = getValue(I.getArgOperand(3));
  3900. SDValue Mask = getValue(I.getArgOperand(2));
  3901. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3902. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3903. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3904. if (!Alignment)
  3905. Alignment = DAG.getEVTAlignment(VT);
  3906. AAMDNodes AAInfo;
  3907. I.getAAMetadata(AAInfo);
  3908. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3909. SDValue Root = DAG.getRoot();
  3910. SDValue Base;
  3911. SDValue Index;
  3912. ISD::MemIndexType IndexType;
  3913. SDValue Scale;
  3914. const Value *BasePtr = Ptr;
  3915. bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
  3916. this);
  3917. bool ConstantMemory = false;
  3918. if (UniformBase && AA &&
  3919. AA->pointsToConstantMemory(
  3920. MemoryLocation(BasePtr,
  3921. LocationSize::precise(
  3922. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3923. AAInfo))) {
  3924. // Do not serialize (non-volatile) loads of constant memory with anything.
  3925. Root = DAG.getEntryNode();
  3926. ConstantMemory = true;
  3927. }
  3928. MachineMemOperand *MMO =
  3929. DAG.getMachineFunction().
  3930. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3931. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3932. Alignment, AAInfo, Ranges);
  3933. if (!UniformBase) {
  3934. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3935. Index = getValue(Ptr);
  3936. IndexType = ISD::SIGNED_SCALED;
  3937. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3938. }
  3939. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3940. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3941. Ops, MMO, IndexType);
  3942. SDValue OutChain = Gather.getValue(1);
  3943. if (!ConstantMemory)
  3944. PendingLoads.push_back(OutChain);
  3945. setValue(&I, Gather);
  3946. }
  3947. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3948. SDLoc dl = getCurSDLoc();
  3949. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3950. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3951. SyncScope::ID SSID = I.getSyncScopeID();
  3952. SDValue InChain = getRoot();
  3953. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3954. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3955. auto Alignment = DAG.getEVTAlignment(MemVT);
  3956. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3957. if (I.isVolatile())
  3958. Flags |= MachineMemOperand::MOVolatile;
  3959. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3960. MachineFunction &MF = DAG.getMachineFunction();
  3961. MachineMemOperand *MMO =
  3962. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3963. Flags, MemVT.getStoreSize(), Alignment,
  3964. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3965. FailureOrdering);
  3966. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3967. dl, MemVT, VTs, InChain,
  3968. getValue(I.getPointerOperand()),
  3969. getValue(I.getCompareOperand()),
  3970. getValue(I.getNewValOperand()), MMO);
  3971. SDValue OutChain = L.getValue(2);
  3972. setValue(&I, L);
  3973. DAG.setRoot(OutChain);
  3974. }
  3975. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3976. SDLoc dl = getCurSDLoc();
  3977. ISD::NodeType NT;
  3978. switch (I.getOperation()) {
  3979. default: llvm_unreachable("Unknown atomicrmw operation");
  3980. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3981. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3982. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3983. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3984. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3985. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3986. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3987. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3988. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3989. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3990. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3991. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3992. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3993. }
  3994. AtomicOrdering Ordering = I.getOrdering();
  3995. SyncScope::ID SSID = I.getSyncScopeID();
  3996. SDValue InChain = getRoot();
  3997. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3998. auto Alignment = DAG.getEVTAlignment(MemVT);
  3999. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  4000. if (I.isVolatile())
  4001. Flags |= MachineMemOperand::MOVolatile;
  4002. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  4003. MachineFunction &MF = DAG.getMachineFunction();
  4004. MachineMemOperand *MMO =
  4005. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4006. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  4007. nullptr, SSID, Ordering);
  4008. SDValue L =
  4009. DAG.getAtomic(NT, dl, MemVT, InChain,
  4010. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  4011. MMO);
  4012. SDValue OutChain = L.getValue(1);
  4013. setValue(&I, L);
  4014. DAG.setRoot(OutChain);
  4015. }
  4016. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4017. SDLoc dl = getCurSDLoc();
  4018. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4019. SDValue Ops[3];
  4020. Ops[0] = getRoot();
  4021. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  4022. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4023. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  4024. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4025. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  4026. }
  4027. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4028. SDLoc dl = getCurSDLoc();
  4029. AtomicOrdering Order = I.getOrdering();
  4030. SyncScope::ID SSID = I.getSyncScopeID();
  4031. SDValue InChain = getRoot();
  4032. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4033. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4034. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4035. if (!TLI.supportsUnalignedAtomics() &&
  4036. I.getAlignment() < MemVT.getSizeInBits() / 8)
  4037. report_fatal_error("Cannot generate unaligned atomic load");
  4038. auto Flags = MachineMemOperand::MOLoad;
  4039. if (I.isVolatile())
  4040. Flags |= MachineMemOperand::MOVolatile;
  4041. if (I.hasMetadata(LLVMContext::MD_invariant_load))
  4042. Flags |= MachineMemOperand::MOInvariant;
  4043. if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
  4044. DAG.getDataLayout()))
  4045. Flags |= MachineMemOperand::MODereferenceable;
  4046. Flags |= TLI.getMMOFlags(I);
  4047. MachineMemOperand *MMO =
  4048. DAG.getMachineFunction().
  4049. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  4050. Flags, MemVT.getStoreSize(),
  4051. I.getAlignment() ? I.getAlignment() :
  4052. DAG.getEVTAlignment(MemVT),
  4053. AAMDNodes(), nullptr, SSID, Order);
  4054. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4055. SDValue Ptr = getValue(I.getPointerOperand());
  4056. if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
  4057. // TODO: Once this is better exercised by tests, it should be merged with
  4058. // the normal path for loads to prevent future divergence.
  4059. SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
  4060. if (MemVT != VT)
  4061. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4062. setValue(&I, L);
  4063. if (!I.isUnordered()) {
  4064. SDValue OutChain = L.getValue(1);
  4065. DAG.setRoot(OutChain);
  4066. }
  4067. return;
  4068. }
  4069. SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4070. Ptr, MMO);
  4071. SDValue OutChain = L.getValue(1);
  4072. if (MemVT != VT)
  4073. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4074. setValue(&I, L);
  4075. DAG.setRoot(OutChain);
  4076. }
  4077. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4078. SDLoc dl = getCurSDLoc();
  4079. AtomicOrdering Ordering = I.getOrdering();
  4080. SyncScope::ID SSID = I.getSyncScopeID();
  4081. SDValue InChain = getRoot();
  4082. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4083. EVT MemVT =
  4084. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4085. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4086. report_fatal_error("Cannot generate unaligned atomic store");
  4087. auto Flags = MachineMemOperand::MOStore;
  4088. if (I.isVolatile())
  4089. Flags |= MachineMemOperand::MOVolatile;
  4090. Flags |= TLI.getMMOFlags(I);
  4091. MachineFunction &MF = DAG.getMachineFunction();
  4092. MachineMemOperand *MMO =
  4093. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4094. MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4095. nullptr, SSID, Ordering);
  4096. SDValue Val = getValue(I.getValueOperand());
  4097. if (Val.getValueType() != MemVT)
  4098. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4099. SDValue Ptr = getValue(I.getPointerOperand());
  4100. if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
  4101. // TODO: Once this is better exercised by tests, it should be merged with
  4102. // the normal path for stores to prevent future divergence.
  4103. SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
  4104. DAG.setRoot(S);
  4105. return;
  4106. }
  4107. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4108. Ptr, Val, MMO);
  4109. DAG.setRoot(OutChain);
  4110. }
  4111. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4112. /// node.
  4113. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4114. unsigned Intrinsic) {
  4115. // Ignore the callsite's attributes. A specific call site may be marked with
  4116. // readnone, but the lowering code will expect the chain based on the
  4117. // definition.
  4118. const Function *F = I.getCalledFunction();
  4119. bool HasChain = !F->doesNotAccessMemory();
  4120. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4121. // Build the operand list.
  4122. SmallVector<SDValue, 8> Ops;
  4123. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4124. if (OnlyLoad) {
  4125. // We don't need to serialize loads against other loads.
  4126. Ops.push_back(DAG.getRoot());
  4127. } else {
  4128. Ops.push_back(getRoot());
  4129. }
  4130. }
  4131. // Info is set by getTgtMemInstrinsic
  4132. TargetLowering::IntrinsicInfo Info;
  4133. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4134. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4135. DAG.getMachineFunction(),
  4136. Intrinsic);
  4137. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4138. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4139. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4140. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4141. TLI.getPointerTy(DAG.getDataLayout())));
  4142. // Add all operands of the call to the operand list.
  4143. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4144. const Value *Arg = I.getArgOperand(i);
  4145. if (!I.paramHasAttr(i, Attribute::ImmArg)) {
  4146. Ops.push_back(getValue(Arg));
  4147. continue;
  4148. }
  4149. // Use TargetConstant instead of a regular constant for immarg.
  4150. EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
  4151. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
  4152. assert(CI->getBitWidth() <= 64 &&
  4153. "large intrinsic immediates not handled");
  4154. Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
  4155. } else {
  4156. Ops.push_back(
  4157. DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
  4158. }
  4159. }
  4160. SmallVector<EVT, 4> ValueVTs;
  4161. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4162. if (HasChain)
  4163. ValueVTs.push_back(MVT::Other);
  4164. SDVTList VTs = DAG.getVTList(ValueVTs);
  4165. // Create the node.
  4166. SDValue Result;
  4167. if (IsTgtIntrinsic) {
  4168. // This is target intrinsic that touches memory
  4169. AAMDNodes AAInfo;
  4170. I.getAAMetadata(AAInfo);
  4171. Result = DAG.getMemIntrinsicNode(
  4172. Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
  4173. MachinePointerInfo(Info.ptrVal, Info.offset),
  4174. Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
  4175. } else if (!HasChain) {
  4176. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4177. } else if (!I.getType()->isVoidTy()) {
  4178. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4179. } else {
  4180. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4181. }
  4182. if (HasChain) {
  4183. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4184. if (OnlyLoad)
  4185. PendingLoads.push_back(Chain);
  4186. else
  4187. DAG.setRoot(Chain);
  4188. }
  4189. if (!I.getType()->isVoidTy()) {
  4190. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4191. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4192. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4193. } else
  4194. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4195. setValue(&I, Result);
  4196. }
  4197. }
  4198. /// GetSignificand - Get the significand and build it into a floating-point
  4199. /// number with exponent of 1:
  4200. ///
  4201. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4202. ///
  4203. /// where Op is the hexadecimal representation of floating point value.
  4204. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4205. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4206. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4207. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4208. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4209. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4210. }
  4211. /// GetExponent - Get the exponent:
  4212. ///
  4213. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4214. ///
  4215. /// where Op is the hexadecimal representation of floating point value.
  4216. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4217. const TargetLowering &TLI, const SDLoc &dl) {
  4218. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4219. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4220. SDValue t1 = DAG.getNode(
  4221. ISD::SRL, dl, MVT::i32, t0,
  4222. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4223. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4224. DAG.getConstant(127, dl, MVT::i32));
  4225. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4226. }
  4227. /// getF32Constant - Get 32-bit floating point constant.
  4228. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4229. const SDLoc &dl) {
  4230. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4231. MVT::f32);
  4232. }
  4233. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4234. SelectionDAG &DAG) {
  4235. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4236. // IntegerPartOfX = ((int32_t)(t0);
  4237. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4238. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4239. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4240. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4241. // IntegerPartOfX <<= 23;
  4242. IntegerPartOfX = DAG.getNode(
  4243. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4244. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4245. DAG.getDataLayout())));
  4246. SDValue TwoToFractionalPartOfX;
  4247. if (LimitFloatPrecision <= 6) {
  4248. // For floating-point precision of 6:
  4249. //
  4250. // TwoToFractionalPartOfX =
  4251. // 0.997535578f +
  4252. // (0.735607626f + 0.252464424f * x) * x;
  4253. //
  4254. // error 0.0144103317, which is 6 bits
  4255. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4256. getF32Constant(DAG, 0x3e814304, dl));
  4257. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4258. getF32Constant(DAG, 0x3f3c50c8, dl));
  4259. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4260. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4261. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4262. } else if (LimitFloatPrecision <= 12) {
  4263. // For floating-point precision of 12:
  4264. //
  4265. // TwoToFractionalPartOfX =
  4266. // 0.999892986f +
  4267. // (0.696457318f +
  4268. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4269. //
  4270. // error 0.000107046256, which is 13 to 14 bits
  4271. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4272. getF32Constant(DAG, 0x3da235e3, dl));
  4273. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4274. getF32Constant(DAG, 0x3e65b8f3, dl));
  4275. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4276. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4277. getF32Constant(DAG, 0x3f324b07, dl));
  4278. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4279. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4280. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4281. } else { // LimitFloatPrecision <= 18
  4282. // For floating-point precision of 18:
  4283. //
  4284. // TwoToFractionalPartOfX =
  4285. // 0.999999982f +
  4286. // (0.693148872f +
  4287. // (0.240227044f +
  4288. // (0.554906021e-1f +
  4289. // (0.961591928e-2f +
  4290. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4291. // error 2.47208000*10^(-7), which is better than 18 bits
  4292. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4293. getF32Constant(DAG, 0x3924b03e, dl));
  4294. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4295. getF32Constant(DAG, 0x3ab24b87, dl));
  4296. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4297. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4298. getF32Constant(DAG, 0x3c1d8c17, dl));
  4299. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4300. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4301. getF32Constant(DAG, 0x3d634a1d, dl));
  4302. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4303. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4304. getF32Constant(DAG, 0x3e75fe14, dl));
  4305. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4306. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4307. getF32Constant(DAG, 0x3f317234, dl));
  4308. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4309. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4310. getF32Constant(DAG, 0x3f800000, dl));
  4311. }
  4312. // Add the exponent into the result in integer domain.
  4313. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4314. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4315. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4316. }
  4317. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4318. /// limited-precision mode.
  4319. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4320. const TargetLowering &TLI) {
  4321. if (Op.getValueType() == MVT::f32 &&
  4322. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4323. // Put the exponent in the right bit position for later addition to the
  4324. // final result:
  4325. //
  4326. // #define LOG2OFe 1.4426950f
  4327. // t0 = Op * LOG2OFe
  4328. // TODO: What fast-math-flags should be set here?
  4329. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4330. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4331. return getLimitedPrecisionExp2(t0, dl, DAG);
  4332. }
  4333. // No special expansion.
  4334. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4335. }
  4336. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4337. /// limited-precision mode.
  4338. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4339. const TargetLowering &TLI) {
  4340. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4341. if (Op.getValueType() == MVT::f32 &&
  4342. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4343. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4344. // Scale the exponent by log(2) [0.69314718f].
  4345. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4346. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4347. getF32Constant(DAG, 0x3f317218, dl));
  4348. // Get the significand and build it into a floating-point number with
  4349. // exponent of 1.
  4350. SDValue X = GetSignificand(DAG, Op1, dl);
  4351. SDValue LogOfMantissa;
  4352. if (LimitFloatPrecision <= 6) {
  4353. // For floating-point precision of 6:
  4354. //
  4355. // LogofMantissa =
  4356. // -1.1609546f +
  4357. // (1.4034025f - 0.23903021f * x) * x;
  4358. //
  4359. // error 0.0034276066, which is better than 8 bits
  4360. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4361. getF32Constant(DAG, 0xbe74c456, dl));
  4362. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4363. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4364. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4365. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4366. getF32Constant(DAG, 0x3f949a29, dl));
  4367. } else if (LimitFloatPrecision <= 12) {
  4368. // For floating-point precision of 12:
  4369. //
  4370. // LogOfMantissa =
  4371. // -1.7417939f +
  4372. // (2.8212026f +
  4373. // (-1.4699568f +
  4374. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4375. //
  4376. // error 0.000061011436, which is 14 bits
  4377. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4378. getF32Constant(DAG, 0xbd67b6d6, dl));
  4379. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4380. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4381. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4382. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4383. getF32Constant(DAG, 0x3fbc278b, dl));
  4384. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4385. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4386. getF32Constant(DAG, 0x40348e95, dl));
  4387. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4388. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4389. getF32Constant(DAG, 0x3fdef31a, dl));
  4390. } else { // LimitFloatPrecision <= 18
  4391. // For floating-point precision of 18:
  4392. //
  4393. // LogOfMantissa =
  4394. // -2.1072184f +
  4395. // (4.2372794f +
  4396. // (-3.7029485f +
  4397. // (2.2781945f +
  4398. // (-0.87823314f +
  4399. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4400. //
  4401. // error 0.0000023660568, which is better than 18 bits
  4402. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4403. getF32Constant(DAG, 0xbc91e5ac, dl));
  4404. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4405. getF32Constant(DAG, 0x3e4350aa, dl));
  4406. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4407. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4408. getF32Constant(DAG, 0x3f60d3e3, dl));
  4409. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4410. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4411. getF32Constant(DAG, 0x4011cdf0, dl));
  4412. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4413. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4414. getF32Constant(DAG, 0x406cfd1c, dl));
  4415. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4416. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4417. getF32Constant(DAG, 0x408797cb, dl));
  4418. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4419. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4420. getF32Constant(DAG, 0x4006dcab, dl));
  4421. }
  4422. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4423. }
  4424. // No special expansion.
  4425. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4426. }
  4427. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4428. /// limited-precision mode.
  4429. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4430. const TargetLowering &TLI) {
  4431. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4432. if (Op.getValueType() == MVT::f32 &&
  4433. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4434. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4435. // Get the exponent.
  4436. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4437. // Get the significand and build it into a floating-point number with
  4438. // exponent of 1.
  4439. SDValue X = GetSignificand(DAG, Op1, dl);
  4440. // Different possible minimax approximations of significand in
  4441. // floating-point for various degrees of accuracy over [1,2].
  4442. SDValue Log2ofMantissa;
  4443. if (LimitFloatPrecision <= 6) {
  4444. // For floating-point precision of 6:
  4445. //
  4446. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4447. //
  4448. // error 0.0049451742, which is more than 7 bits
  4449. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4450. getF32Constant(DAG, 0xbeb08fe0, dl));
  4451. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4452. getF32Constant(DAG, 0x40019463, dl));
  4453. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4454. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4455. getF32Constant(DAG, 0x3fd6633d, dl));
  4456. } else if (LimitFloatPrecision <= 12) {
  4457. // For floating-point precision of 12:
  4458. //
  4459. // Log2ofMantissa =
  4460. // -2.51285454f +
  4461. // (4.07009056f +
  4462. // (-2.12067489f +
  4463. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4464. //
  4465. // error 0.0000876136000, which is better than 13 bits
  4466. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4467. getF32Constant(DAG, 0xbda7262e, dl));
  4468. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4469. getF32Constant(DAG, 0x3f25280b, dl));
  4470. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4471. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4472. getF32Constant(DAG, 0x4007b923, dl));
  4473. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4474. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4475. getF32Constant(DAG, 0x40823e2f, dl));
  4476. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4477. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4478. getF32Constant(DAG, 0x4020d29c, dl));
  4479. } else { // LimitFloatPrecision <= 18
  4480. // For floating-point precision of 18:
  4481. //
  4482. // Log2ofMantissa =
  4483. // -3.0400495f +
  4484. // (6.1129976f +
  4485. // (-5.3420409f +
  4486. // (3.2865683f +
  4487. // (-1.2669343f +
  4488. // (0.27515199f -
  4489. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4490. //
  4491. // error 0.0000018516, which is better than 18 bits
  4492. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4493. getF32Constant(DAG, 0xbcd2769e, dl));
  4494. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4495. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4496. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4497. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4498. getF32Constant(DAG, 0x3fa22ae7, dl));
  4499. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4500. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4501. getF32Constant(DAG, 0x40525723, dl));
  4502. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4503. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4504. getF32Constant(DAG, 0x40aaf200, dl));
  4505. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4506. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4507. getF32Constant(DAG, 0x40c39dad, dl));
  4508. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4509. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4510. getF32Constant(DAG, 0x4042902c, dl));
  4511. }
  4512. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4513. }
  4514. // No special expansion.
  4515. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4516. }
  4517. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4518. /// limited-precision mode.
  4519. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4520. const TargetLowering &TLI) {
  4521. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4522. if (Op.getValueType() == MVT::f32 &&
  4523. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4524. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4525. // Scale the exponent by log10(2) [0.30102999f].
  4526. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4527. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4528. getF32Constant(DAG, 0x3e9a209a, dl));
  4529. // Get the significand and build it into a floating-point number with
  4530. // exponent of 1.
  4531. SDValue X = GetSignificand(DAG, Op1, dl);
  4532. SDValue Log10ofMantissa;
  4533. if (LimitFloatPrecision <= 6) {
  4534. // For floating-point precision of 6:
  4535. //
  4536. // Log10ofMantissa =
  4537. // -0.50419619f +
  4538. // (0.60948995f - 0.10380950f * x) * x;
  4539. //
  4540. // error 0.0014886165, which is 6 bits
  4541. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4542. getF32Constant(DAG, 0xbdd49a13, dl));
  4543. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4544. getF32Constant(DAG, 0x3f1c0789, dl));
  4545. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4546. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4547. getF32Constant(DAG, 0x3f011300, dl));
  4548. } else if (LimitFloatPrecision <= 12) {
  4549. // For floating-point precision of 12:
  4550. //
  4551. // Log10ofMantissa =
  4552. // -0.64831180f +
  4553. // (0.91751397f +
  4554. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4555. //
  4556. // error 0.00019228036, which is better than 12 bits
  4557. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4558. getF32Constant(DAG, 0x3d431f31, dl));
  4559. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4560. getF32Constant(DAG, 0x3ea21fb2, dl));
  4561. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4562. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4563. getF32Constant(DAG, 0x3f6ae232, dl));
  4564. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4565. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4566. getF32Constant(DAG, 0x3f25f7c3, dl));
  4567. } else { // LimitFloatPrecision <= 18
  4568. // For floating-point precision of 18:
  4569. //
  4570. // Log10ofMantissa =
  4571. // -0.84299375f +
  4572. // (1.5327582f +
  4573. // (-1.0688956f +
  4574. // (0.49102474f +
  4575. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4576. //
  4577. // error 0.0000037995730, which is better than 18 bits
  4578. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4579. getF32Constant(DAG, 0x3c5d51ce, dl));
  4580. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4581. getF32Constant(DAG, 0x3e00685a, dl));
  4582. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4583. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4584. getF32Constant(DAG, 0x3efb6798, dl));
  4585. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4586. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4587. getF32Constant(DAG, 0x3f88d192, dl));
  4588. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4589. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4590. getF32Constant(DAG, 0x3fc4316c, dl));
  4591. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4592. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4593. getF32Constant(DAG, 0x3f57ce70, dl));
  4594. }
  4595. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4596. }
  4597. // No special expansion.
  4598. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4599. }
  4600. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4601. /// limited-precision mode.
  4602. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4603. const TargetLowering &TLI) {
  4604. if (Op.getValueType() == MVT::f32 &&
  4605. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4606. return getLimitedPrecisionExp2(Op, dl, DAG);
  4607. // No special expansion.
  4608. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4609. }
  4610. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4611. /// limited-precision mode with x == 10.0f.
  4612. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4613. SelectionDAG &DAG, const TargetLowering &TLI) {
  4614. bool IsExp10 = false;
  4615. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4616. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4617. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4618. APFloat Ten(10.0f);
  4619. IsExp10 = LHSC->isExactlyValue(Ten);
  4620. }
  4621. }
  4622. // TODO: What fast-math-flags should be set on the FMUL node?
  4623. if (IsExp10) {
  4624. // Put the exponent in the right bit position for later addition to the
  4625. // final result:
  4626. //
  4627. // #define LOG2OF10 3.3219281f
  4628. // t0 = Op * LOG2OF10;
  4629. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4630. getF32Constant(DAG, 0x40549a78, dl));
  4631. return getLimitedPrecisionExp2(t0, dl, DAG);
  4632. }
  4633. // No special expansion.
  4634. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4635. }
  4636. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4637. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4638. SelectionDAG &DAG) {
  4639. // If RHS is a constant, we can expand this out to a multiplication tree,
  4640. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4641. // optimizing for size, we only want to do this if the expansion would produce
  4642. // a small number of multiplies, otherwise we do the full expansion.
  4643. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4644. // Get the exponent as a positive value.
  4645. unsigned Val = RHSC->getSExtValue();
  4646. if ((int)Val < 0) Val = -Val;
  4647. // powi(x, 0) -> 1.0
  4648. if (Val == 0)
  4649. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4650. const Function &F = DAG.getMachineFunction().getFunction();
  4651. if (!F.hasOptSize() ||
  4652. // If optimizing for size, don't insert too many multiplies.
  4653. // This inserts up to 5 multiplies.
  4654. countPopulation(Val) + Log2_32(Val) < 7) {
  4655. // We use the simple binary decomposition method to generate the multiply
  4656. // sequence. There are more optimal ways to do this (for example,
  4657. // powi(x,15) generates one more multiply than it should), but this has
  4658. // the benefit of being both really simple and much better than a libcall.
  4659. SDValue Res; // Logically starts equal to 1.0
  4660. SDValue CurSquare = LHS;
  4661. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4662. // nodes.
  4663. while (Val) {
  4664. if (Val & 1) {
  4665. if (Res.getNode())
  4666. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4667. else
  4668. Res = CurSquare; // 1.0*CurSquare.
  4669. }
  4670. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4671. CurSquare, CurSquare);
  4672. Val >>= 1;
  4673. }
  4674. // If the original was negative, invert the result, producing 1/(x*x*x).
  4675. if (RHSC->getSExtValue() < 0)
  4676. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4677. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4678. return Res;
  4679. }
  4680. }
  4681. // Otherwise, expand to a libcall.
  4682. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4683. }
  4684. // getUnderlyingArgRegs - Find underlying registers used for a truncated,
  4685. // bitcasted, or split argument. Returns a list of <Register, size in bits>
  4686. static void
  4687. getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
  4688. const SDValue &N) {
  4689. switch (N.getOpcode()) {
  4690. case ISD::CopyFromReg: {
  4691. SDValue Op = N.getOperand(1);
  4692. Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
  4693. Op.getValueType().getSizeInBits());
  4694. return;
  4695. }
  4696. case ISD::BITCAST:
  4697. case ISD::AssertZext:
  4698. case ISD::AssertSext:
  4699. case ISD::TRUNCATE:
  4700. getUnderlyingArgRegs(Regs, N.getOperand(0));
  4701. return;
  4702. case ISD::BUILD_PAIR:
  4703. case ISD::BUILD_VECTOR:
  4704. case ISD::CONCAT_VECTORS:
  4705. for (SDValue Op : N->op_values())
  4706. getUnderlyingArgRegs(Regs, Op);
  4707. return;
  4708. default:
  4709. return;
  4710. }
  4711. }
  4712. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4713. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4714. /// instruction selection, they will be inserted to the entry BB.
  4715. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4716. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4717. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4718. const Argument *Arg = dyn_cast<Argument>(V);
  4719. if (!Arg)
  4720. return false;
  4721. if (!IsDbgDeclare) {
  4722. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4723. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4724. // the entry block.
  4725. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4726. if (!IsInEntryBlock)
  4727. return false;
  4728. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4729. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4730. // variable that also is a param.
  4731. //
  4732. // Although, if we are at the top of the entry block already, we can still
  4733. // emit using ArgDbgValue. This might catch some situations when the
  4734. // dbg.value refers to an argument that isn't used in the entry block, so
  4735. // any CopyToReg node would be optimized out and the only way to express
  4736. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4737. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4738. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4739. // current function, and the dbg.value intrinsic is found in the entry
  4740. // block.
  4741. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4742. !DL->getInlinedAt();
  4743. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4744. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4745. return false;
  4746. // Here we assume that a function argument on IR level only can be used to
  4747. // describe one input parameter on source level. If we for example have
  4748. // source code like this
  4749. //
  4750. // struct A { long x, y; };
  4751. // void foo(struct A a, long b) {
  4752. // ...
  4753. // b = a.x;
  4754. // ...
  4755. // }
  4756. //
  4757. // and IR like this
  4758. //
  4759. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4760. // entry:
  4761. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4762. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4763. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4764. // ...
  4765. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4766. // ...
  4767. //
  4768. // then the last dbg.value is describing a parameter "b" using a value that
  4769. // is an argument. But since we already has used %a1 to describe a parameter
  4770. // we should not handle that last dbg.value here (that would result in an
  4771. // incorrect hoisting of the DBG_VALUE to the function entry).
  4772. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4773. // for the situation with fragments above.
  4774. if (VariableIsFunctionInputArg) {
  4775. unsigned ArgNo = Arg->getArgNo();
  4776. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4777. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4778. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4779. return false;
  4780. FuncInfo.DescribedArgs.set(ArgNo);
  4781. }
  4782. }
  4783. MachineFunction &MF = DAG.getMachineFunction();
  4784. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4785. bool IsIndirect = false;
  4786. Optional<MachineOperand> Op;
  4787. // Some arguments' frame index is recorded during argument lowering.
  4788. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4789. if (FI != std::numeric_limits<int>::max())
  4790. Op = MachineOperand::CreateFI(FI);
  4791. SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
  4792. if (!Op && N.getNode()) {
  4793. getUnderlyingArgRegs(ArgRegsAndSizes, N);
  4794. Register Reg;
  4795. if (ArgRegsAndSizes.size() == 1)
  4796. Reg = ArgRegsAndSizes.front().first;
  4797. if (Reg && Reg.isVirtual()) {
  4798. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4799. Register PR = RegInfo.getLiveInPhysReg(Reg);
  4800. if (PR)
  4801. Reg = PR;
  4802. }
  4803. if (Reg) {
  4804. Op = MachineOperand::CreateReg(Reg, false);
  4805. IsIndirect = IsDbgDeclare;
  4806. }
  4807. }
  4808. if (!Op && N.getNode()) {
  4809. // Check if frame index is available.
  4810. SDValue LCandidate = peekThroughBitcasts(N);
  4811. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4812. if (FrameIndexSDNode *FINode =
  4813. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4814. Op = MachineOperand::CreateFI(FINode->getIndex());
  4815. }
  4816. if (!Op) {
  4817. // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
  4818. auto splitMultiRegDbgValue
  4819. = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
  4820. unsigned Offset = 0;
  4821. for (auto RegAndSize : SplitRegs) {
  4822. auto FragmentExpr = DIExpression::createFragmentExpression(
  4823. Expr, Offset, RegAndSize.second);
  4824. if (!FragmentExpr)
  4825. continue;
  4826. FuncInfo.ArgDbgValues.push_back(
  4827. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4828. RegAndSize.first, Variable, *FragmentExpr));
  4829. Offset += RegAndSize.second;
  4830. }
  4831. };
  4832. // Check if ValueMap has reg number.
  4833. DenseMap<const Value *, unsigned>::const_iterator
  4834. VMI = FuncInfo.ValueMap.find(V);
  4835. if (VMI != FuncInfo.ValueMap.end()) {
  4836. const auto &TLI = DAG.getTargetLoweringInfo();
  4837. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4838. V->getType(), getABIRegCopyCC(V));
  4839. if (RFV.occupiesMultipleRegs()) {
  4840. splitMultiRegDbgValue(RFV.getRegsAndSizes());
  4841. return true;
  4842. }
  4843. Op = MachineOperand::CreateReg(VMI->second, false);
  4844. IsIndirect = IsDbgDeclare;
  4845. } else if (ArgRegsAndSizes.size() > 1) {
  4846. // This was split due to the calling convention, and no virtual register
  4847. // mapping exists for the value.
  4848. splitMultiRegDbgValue(ArgRegsAndSizes);
  4849. return true;
  4850. }
  4851. }
  4852. if (!Op)
  4853. return false;
  4854. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4855. "Expected inlined-at fields to agree");
  4856. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4857. FuncInfo.ArgDbgValues.push_back(
  4858. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4859. *Op, Variable, Expr));
  4860. return true;
  4861. }
  4862. /// Return the appropriate SDDbgValue based on N.
  4863. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4864. DILocalVariable *Variable,
  4865. DIExpression *Expr,
  4866. const DebugLoc &dl,
  4867. unsigned DbgSDNodeOrder) {
  4868. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4869. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4870. // stack slot locations.
  4871. //
  4872. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4873. // debug values here after optimization:
  4874. //
  4875. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4876. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4877. //
  4878. // Both describe the direct values of their associated variables.
  4879. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4880. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4881. }
  4882. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4883. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4884. }
  4885. // VisualStudio defines setjmp as _setjmp
  4886. #if defined(_MSC_VER) && defined(setjmp) && \
  4887. !defined(setjmp_undefined_for_msvc)
  4888. # pragma push_macro("setjmp")
  4889. # undef setjmp
  4890. # define setjmp_undefined_for_msvc
  4891. #endif
  4892. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4893. switch (Intrinsic) {
  4894. case Intrinsic::smul_fix:
  4895. return ISD::SMULFIX;
  4896. case Intrinsic::umul_fix:
  4897. return ISD::UMULFIX;
  4898. default:
  4899. llvm_unreachable("Unhandled fixed point intrinsic");
  4900. }
  4901. }
  4902. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  4903. const char *FunctionName) {
  4904. assert(FunctionName && "FunctionName must not be nullptr");
  4905. SDValue Callee = DAG.getExternalSymbol(
  4906. FunctionName,
  4907. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  4908. LowerCallTo(&I, Callee, I.isTailCall());
  4909. }
  4910. /// Lower the call to the specified intrinsic function.
  4911. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  4912. unsigned Intrinsic) {
  4913. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4914. SDLoc sdl = getCurSDLoc();
  4915. DebugLoc dl = getCurDebugLoc();
  4916. SDValue Res;
  4917. switch (Intrinsic) {
  4918. default:
  4919. // By default, turn this into a target intrinsic node.
  4920. visitTargetIntrinsic(I, Intrinsic);
  4921. return;
  4922. case Intrinsic::vastart: visitVAStart(I); return;
  4923. case Intrinsic::vaend: visitVAEnd(I); return;
  4924. case Intrinsic::vacopy: visitVACopy(I); return;
  4925. case Intrinsic::returnaddress:
  4926. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4927. TLI.getPointerTy(DAG.getDataLayout()),
  4928. getValue(I.getArgOperand(0))));
  4929. return;
  4930. case Intrinsic::addressofreturnaddress:
  4931. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4932. TLI.getPointerTy(DAG.getDataLayout())));
  4933. return;
  4934. case Intrinsic::sponentry:
  4935. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4936. TLI.getFrameIndexTy(DAG.getDataLayout())));
  4937. return;
  4938. case Intrinsic::frameaddress:
  4939. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4940. TLI.getFrameIndexTy(DAG.getDataLayout()),
  4941. getValue(I.getArgOperand(0))));
  4942. return;
  4943. case Intrinsic::read_register: {
  4944. Value *Reg = I.getArgOperand(0);
  4945. SDValue Chain = getRoot();
  4946. SDValue RegName =
  4947. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4948. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4949. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4950. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4951. setValue(&I, Res);
  4952. DAG.setRoot(Res.getValue(1));
  4953. return;
  4954. }
  4955. case Intrinsic::write_register: {
  4956. Value *Reg = I.getArgOperand(0);
  4957. Value *RegValue = I.getArgOperand(1);
  4958. SDValue Chain = getRoot();
  4959. SDValue RegName =
  4960. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4961. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4962. RegName, getValue(RegValue)));
  4963. return;
  4964. }
  4965. case Intrinsic::setjmp:
  4966. lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
  4967. return;
  4968. case Intrinsic::longjmp:
  4969. lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
  4970. return;
  4971. case Intrinsic::memcpy: {
  4972. const auto &MCI = cast<MemCpyInst>(I);
  4973. SDValue Op1 = getValue(I.getArgOperand(0));
  4974. SDValue Op2 = getValue(I.getArgOperand(1));
  4975. SDValue Op3 = getValue(I.getArgOperand(2));
  4976. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4977. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4978. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4979. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4980. bool isVol = MCI.isVolatile();
  4981. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4982. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4983. // node.
  4984. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4985. false, isTC,
  4986. MachinePointerInfo(I.getArgOperand(0)),
  4987. MachinePointerInfo(I.getArgOperand(1)));
  4988. updateDAGForMaybeTailCall(MC);
  4989. return;
  4990. }
  4991. case Intrinsic::memset: {
  4992. const auto &MSI = cast<MemSetInst>(I);
  4993. SDValue Op1 = getValue(I.getArgOperand(0));
  4994. SDValue Op2 = getValue(I.getArgOperand(1));
  4995. SDValue Op3 = getValue(I.getArgOperand(2));
  4996. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4997. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4998. bool isVol = MSI.isVolatile();
  4999. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5000. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  5001. isTC, MachinePointerInfo(I.getArgOperand(0)));
  5002. updateDAGForMaybeTailCall(MS);
  5003. return;
  5004. }
  5005. case Intrinsic::memmove: {
  5006. const auto &MMI = cast<MemMoveInst>(I);
  5007. SDValue Op1 = getValue(I.getArgOperand(0));
  5008. SDValue Op2 = getValue(I.getArgOperand(1));
  5009. SDValue Op3 = getValue(I.getArgOperand(2));
  5010. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  5011. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  5012. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  5013. unsigned Align = MinAlign(DstAlign, SrcAlign);
  5014. bool isVol = MMI.isVolatile();
  5015. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5016. // FIXME: Support passing different dest/src alignments to the memmove DAG
  5017. // node.
  5018. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  5019. isTC, MachinePointerInfo(I.getArgOperand(0)),
  5020. MachinePointerInfo(I.getArgOperand(1)));
  5021. updateDAGForMaybeTailCall(MM);
  5022. return;
  5023. }
  5024. case Intrinsic::memcpy_element_unordered_atomic: {
  5025. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  5026. SDValue Dst = getValue(MI.getRawDest());
  5027. SDValue Src = getValue(MI.getRawSource());
  5028. SDValue Length = getValue(MI.getLength());
  5029. unsigned DstAlign = MI.getDestAlignment();
  5030. unsigned SrcAlign = MI.getSourceAlignment();
  5031. Type *LengthTy = MI.getLength()->getType();
  5032. unsigned ElemSz = MI.getElementSizeInBytes();
  5033. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5034. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  5035. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5036. MachinePointerInfo(MI.getRawDest()),
  5037. MachinePointerInfo(MI.getRawSource()));
  5038. updateDAGForMaybeTailCall(MC);
  5039. return;
  5040. }
  5041. case Intrinsic::memmove_element_unordered_atomic: {
  5042. auto &MI = cast<AtomicMemMoveInst>(I);
  5043. SDValue Dst = getValue(MI.getRawDest());
  5044. SDValue Src = getValue(MI.getRawSource());
  5045. SDValue Length = getValue(MI.getLength());
  5046. unsigned DstAlign = MI.getDestAlignment();
  5047. unsigned SrcAlign = MI.getSourceAlignment();
  5048. Type *LengthTy = MI.getLength()->getType();
  5049. unsigned ElemSz = MI.getElementSizeInBytes();
  5050. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5051. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  5052. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5053. MachinePointerInfo(MI.getRawDest()),
  5054. MachinePointerInfo(MI.getRawSource()));
  5055. updateDAGForMaybeTailCall(MC);
  5056. return;
  5057. }
  5058. case Intrinsic::memset_element_unordered_atomic: {
  5059. auto &MI = cast<AtomicMemSetInst>(I);
  5060. SDValue Dst = getValue(MI.getRawDest());
  5061. SDValue Val = getValue(MI.getValue());
  5062. SDValue Length = getValue(MI.getLength());
  5063. unsigned DstAlign = MI.getDestAlignment();
  5064. Type *LengthTy = MI.getLength()->getType();
  5065. unsigned ElemSz = MI.getElementSizeInBytes();
  5066. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5067. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  5068. LengthTy, ElemSz, isTC,
  5069. MachinePointerInfo(MI.getRawDest()));
  5070. updateDAGForMaybeTailCall(MC);
  5071. return;
  5072. }
  5073. case Intrinsic::dbg_addr:
  5074. case Intrinsic::dbg_declare: {
  5075. const auto &DI = cast<DbgVariableIntrinsic>(I);
  5076. DILocalVariable *Variable = DI.getVariable();
  5077. DIExpression *Expression = DI.getExpression();
  5078. dropDanglingDebugInfo(Variable, Expression);
  5079. assert(Variable && "Missing variable");
  5080. // Check if address has undef value.
  5081. const Value *Address = DI.getVariableLocation();
  5082. if (!Address || isa<UndefValue>(Address) ||
  5083. (Address->use_empty() && !isa<Argument>(Address))) {
  5084. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5085. return;
  5086. }
  5087. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5088. // Check if this variable can be described by a frame index, typically
  5089. // either as a static alloca or a byval parameter.
  5090. int FI = std::numeric_limits<int>::max();
  5091. if (const auto *AI =
  5092. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5093. if (AI->isStaticAlloca()) {
  5094. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5095. if (I != FuncInfo.StaticAllocaMap.end())
  5096. FI = I->second;
  5097. }
  5098. } else if (const auto *Arg = dyn_cast<Argument>(
  5099. Address->stripInBoundsConstantOffsets())) {
  5100. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5101. }
  5102. // llvm.dbg.addr is control dependent and always generates indirect
  5103. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5104. // the MachineFunction variable table.
  5105. if (FI != std::numeric_limits<int>::max()) {
  5106. if (Intrinsic == Intrinsic::dbg_addr) {
  5107. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5108. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  5109. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  5110. }
  5111. return;
  5112. }
  5113. SDValue &N = NodeMap[Address];
  5114. if (!N.getNode() && isa<Argument>(Address))
  5115. // Check unused arguments map.
  5116. N = UnusedArgNodeMap[Address];
  5117. SDDbgValue *SDV;
  5118. if (N.getNode()) {
  5119. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5120. Address = BCI->getOperand(0);
  5121. // Parameters are handled specially.
  5122. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5123. if (isParameter && FINode) {
  5124. // Byval parameter. We have a frame index at this point.
  5125. SDV =
  5126. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5127. /*IsIndirect*/ true, dl, SDNodeOrder);
  5128. } else if (isa<Argument>(Address)) {
  5129. // Address is an argument, so try to emit its dbg value using
  5130. // virtual register info from the FuncInfo.ValueMap.
  5131. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5132. return;
  5133. } else {
  5134. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5135. true, dl, SDNodeOrder);
  5136. }
  5137. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5138. } else {
  5139. // If Address is an argument then try to emit its dbg value using
  5140. // virtual register info from the FuncInfo.ValueMap.
  5141. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5142. N)) {
  5143. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5144. }
  5145. }
  5146. return;
  5147. }
  5148. case Intrinsic::dbg_label: {
  5149. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5150. DILabel *Label = DI.getLabel();
  5151. assert(Label && "Missing label");
  5152. SDDbgLabel *SDV;
  5153. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5154. DAG.AddDbgLabel(SDV);
  5155. return;
  5156. }
  5157. case Intrinsic::dbg_value: {
  5158. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5159. assert(DI.getVariable() && "Missing variable");
  5160. DILocalVariable *Variable = DI.getVariable();
  5161. DIExpression *Expression = DI.getExpression();
  5162. dropDanglingDebugInfo(Variable, Expression);
  5163. const Value *V = DI.getValue();
  5164. if (!V)
  5165. return;
  5166. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5167. SDNodeOrder))
  5168. return;
  5169. // TODO: Dangling debug info will eventually either be resolved or produce
  5170. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5171. // between the original dbg.value location and its resolved DBG_VALUE, which
  5172. // we should ideally fill with an extra Undef DBG_VALUE.
  5173. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5174. return;
  5175. }
  5176. case Intrinsic::eh_typeid_for: {
  5177. // Find the type id for the given typeinfo.
  5178. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5179. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5180. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5181. setValue(&I, Res);
  5182. return;
  5183. }
  5184. case Intrinsic::eh_return_i32:
  5185. case Intrinsic::eh_return_i64:
  5186. DAG.getMachineFunction().setCallsEHReturn(true);
  5187. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5188. MVT::Other,
  5189. getControlRoot(),
  5190. getValue(I.getArgOperand(0)),
  5191. getValue(I.getArgOperand(1))));
  5192. return;
  5193. case Intrinsic::eh_unwind_init:
  5194. DAG.getMachineFunction().setCallsUnwindInit(true);
  5195. return;
  5196. case Intrinsic::eh_dwarf_cfa:
  5197. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5198. TLI.getPointerTy(DAG.getDataLayout()),
  5199. getValue(I.getArgOperand(0))));
  5200. return;
  5201. case Intrinsic::eh_sjlj_callsite: {
  5202. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5203. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5204. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5205. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5206. MMI.setCurrentCallSite(CI->getZExtValue());
  5207. return;
  5208. }
  5209. case Intrinsic::eh_sjlj_functioncontext: {
  5210. // Get and store the index of the function context.
  5211. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5212. AllocaInst *FnCtx =
  5213. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5214. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5215. MFI.setFunctionContextIndex(FI);
  5216. return;
  5217. }
  5218. case Intrinsic::eh_sjlj_setjmp: {
  5219. SDValue Ops[2];
  5220. Ops[0] = getRoot();
  5221. Ops[1] = getValue(I.getArgOperand(0));
  5222. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5223. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5224. setValue(&I, Op.getValue(0));
  5225. DAG.setRoot(Op.getValue(1));
  5226. return;
  5227. }
  5228. case Intrinsic::eh_sjlj_longjmp:
  5229. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5230. getRoot(), getValue(I.getArgOperand(0))));
  5231. return;
  5232. case Intrinsic::eh_sjlj_setup_dispatch:
  5233. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5234. getRoot()));
  5235. return;
  5236. case Intrinsic::masked_gather:
  5237. visitMaskedGather(I);
  5238. return;
  5239. case Intrinsic::masked_load:
  5240. visitMaskedLoad(I);
  5241. return;
  5242. case Intrinsic::masked_scatter:
  5243. visitMaskedScatter(I);
  5244. return;
  5245. case Intrinsic::masked_store:
  5246. visitMaskedStore(I);
  5247. return;
  5248. case Intrinsic::masked_expandload:
  5249. visitMaskedLoad(I, true /* IsExpanding */);
  5250. return;
  5251. case Intrinsic::masked_compressstore:
  5252. visitMaskedStore(I, true /* IsCompressing */);
  5253. return;
  5254. case Intrinsic::powi:
  5255. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5256. getValue(I.getArgOperand(1)), DAG));
  5257. return;
  5258. case Intrinsic::log:
  5259. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5260. return;
  5261. case Intrinsic::log2:
  5262. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5263. return;
  5264. case Intrinsic::log10:
  5265. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5266. return;
  5267. case Intrinsic::exp:
  5268. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5269. return;
  5270. case Intrinsic::exp2:
  5271. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5272. return;
  5273. case Intrinsic::pow:
  5274. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5275. getValue(I.getArgOperand(1)), DAG, TLI));
  5276. return;
  5277. case Intrinsic::sqrt:
  5278. case Intrinsic::fabs:
  5279. case Intrinsic::sin:
  5280. case Intrinsic::cos:
  5281. case Intrinsic::floor:
  5282. case Intrinsic::ceil:
  5283. case Intrinsic::trunc:
  5284. case Intrinsic::rint:
  5285. case Intrinsic::nearbyint:
  5286. case Intrinsic::round:
  5287. case Intrinsic::canonicalize: {
  5288. unsigned Opcode;
  5289. switch (Intrinsic) {
  5290. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5291. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5292. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5293. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5294. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5295. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5296. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5297. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5298. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5299. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5300. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5301. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5302. }
  5303. setValue(&I, DAG.getNode(Opcode, sdl,
  5304. getValue(I.getArgOperand(0)).getValueType(),
  5305. getValue(I.getArgOperand(0))));
  5306. return;
  5307. }
  5308. case Intrinsic::lround:
  5309. case Intrinsic::llround:
  5310. case Intrinsic::lrint:
  5311. case Intrinsic::llrint: {
  5312. unsigned Opcode;
  5313. switch (Intrinsic) {
  5314. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5315. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5316. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5317. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5318. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5319. }
  5320. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5321. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5322. getValue(I.getArgOperand(0))));
  5323. return;
  5324. }
  5325. case Intrinsic::minnum:
  5326. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  5327. getValue(I.getArgOperand(0)).getValueType(),
  5328. getValue(I.getArgOperand(0)),
  5329. getValue(I.getArgOperand(1))));
  5330. return;
  5331. case Intrinsic::maxnum:
  5332. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  5333. getValue(I.getArgOperand(0)).getValueType(),
  5334. getValue(I.getArgOperand(0)),
  5335. getValue(I.getArgOperand(1))));
  5336. return;
  5337. case Intrinsic::minimum:
  5338. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5339. getValue(I.getArgOperand(0)).getValueType(),
  5340. getValue(I.getArgOperand(0)),
  5341. getValue(I.getArgOperand(1))));
  5342. return;
  5343. case Intrinsic::maximum:
  5344. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5345. getValue(I.getArgOperand(0)).getValueType(),
  5346. getValue(I.getArgOperand(0)),
  5347. getValue(I.getArgOperand(1))));
  5348. return;
  5349. case Intrinsic::copysign:
  5350. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5351. getValue(I.getArgOperand(0)).getValueType(),
  5352. getValue(I.getArgOperand(0)),
  5353. getValue(I.getArgOperand(1))));
  5354. return;
  5355. case Intrinsic::fma:
  5356. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5357. getValue(I.getArgOperand(0)).getValueType(),
  5358. getValue(I.getArgOperand(0)),
  5359. getValue(I.getArgOperand(1)),
  5360. getValue(I.getArgOperand(2))));
  5361. return;
  5362. case Intrinsic::experimental_constrained_fadd:
  5363. case Intrinsic::experimental_constrained_fsub:
  5364. case Intrinsic::experimental_constrained_fmul:
  5365. case Intrinsic::experimental_constrained_fdiv:
  5366. case Intrinsic::experimental_constrained_frem:
  5367. case Intrinsic::experimental_constrained_fma:
  5368. case Intrinsic::experimental_constrained_fptosi:
  5369. case Intrinsic::experimental_constrained_fptoui:
  5370. case Intrinsic::experimental_constrained_fptrunc:
  5371. case Intrinsic::experimental_constrained_fpext:
  5372. case Intrinsic::experimental_constrained_sqrt:
  5373. case Intrinsic::experimental_constrained_pow:
  5374. case Intrinsic::experimental_constrained_powi:
  5375. case Intrinsic::experimental_constrained_sin:
  5376. case Intrinsic::experimental_constrained_cos:
  5377. case Intrinsic::experimental_constrained_exp:
  5378. case Intrinsic::experimental_constrained_exp2:
  5379. case Intrinsic::experimental_constrained_log:
  5380. case Intrinsic::experimental_constrained_log10:
  5381. case Intrinsic::experimental_constrained_log2:
  5382. case Intrinsic::experimental_constrained_rint:
  5383. case Intrinsic::experimental_constrained_nearbyint:
  5384. case Intrinsic::experimental_constrained_maxnum:
  5385. case Intrinsic::experimental_constrained_minnum:
  5386. case Intrinsic::experimental_constrained_ceil:
  5387. case Intrinsic::experimental_constrained_floor:
  5388. case Intrinsic::experimental_constrained_round:
  5389. case Intrinsic::experimental_constrained_trunc:
  5390. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5391. return;
  5392. case Intrinsic::fmuladd: {
  5393. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5394. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5395. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5396. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5397. getValue(I.getArgOperand(0)).getValueType(),
  5398. getValue(I.getArgOperand(0)),
  5399. getValue(I.getArgOperand(1)),
  5400. getValue(I.getArgOperand(2))));
  5401. } else {
  5402. // TODO: Intrinsic calls should have fast-math-flags.
  5403. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5404. getValue(I.getArgOperand(0)).getValueType(),
  5405. getValue(I.getArgOperand(0)),
  5406. getValue(I.getArgOperand(1)));
  5407. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5408. getValue(I.getArgOperand(0)).getValueType(),
  5409. Mul,
  5410. getValue(I.getArgOperand(2)));
  5411. setValue(&I, Add);
  5412. }
  5413. return;
  5414. }
  5415. case Intrinsic::convert_to_fp16:
  5416. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5417. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5418. getValue(I.getArgOperand(0)),
  5419. DAG.getTargetConstant(0, sdl,
  5420. MVT::i32))));
  5421. return;
  5422. case Intrinsic::convert_from_fp16:
  5423. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5424. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5425. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5426. getValue(I.getArgOperand(0)))));
  5427. return;
  5428. case Intrinsic::pcmarker: {
  5429. SDValue Tmp = getValue(I.getArgOperand(0));
  5430. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5431. return;
  5432. }
  5433. case Intrinsic::readcyclecounter: {
  5434. SDValue Op = getRoot();
  5435. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5436. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5437. setValue(&I, Res);
  5438. DAG.setRoot(Res.getValue(1));
  5439. return;
  5440. }
  5441. case Intrinsic::bitreverse:
  5442. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5443. getValue(I.getArgOperand(0)).getValueType(),
  5444. getValue(I.getArgOperand(0))));
  5445. return;
  5446. case Intrinsic::bswap:
  5447. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5448. getValue(I.getArgOperand(0)).getValueType(),
  5449. getValue(I.getArgOperand(0))));
  5450. return;
  5451. case Intrinsic::cttz: {
  5452. SDValue Arg = getValue(I.getArgOperand(0));
  5453. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5454. EVT Ty = Arg.getValueType();
  5455. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5456. sdl, Ty, Arg));
  5457. return;
  5458. }
  5459. case Intrinsic::ctlz: {
  5460. SDValue Arg = getValue(I.getArgOperand(0));
  5461. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5462. EVT Ty = Arg.getValueType();
  5463. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5464. sdl, Ty, Arg));
  5465. return;
  5466. }
  5467. case Intrinsic::ctpop: {
  5468. SDValue Arg = getValue(I.getArgOperand(0));
  5469. EVT Ty = Arg.getValueType();
  5470. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5471. return;
  5472. }
  5473. case Intrinsic::fshl:
  5474. case Intrinsic::fshr: {
  5475. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5476. SDValue X = getValue(I.getArgOperand(0));
  5477. SDValue Y = getValue(I.getArgOperand(1));
  5478. SDValue Z = getValue(I.getArgOperand(2));
  5479. EVT VT = X.getValueType();
  5480. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5481. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5482. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5483. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5484. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5485. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5486. return;
  5487. }
  5488. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5489. // avoid the select that is necessary in the general case to filter out
  5490. // the 0-shift possibility that leads to UB.
  5491. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5492. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5493. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5494. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5495. return;
  5496. }
  5497. // Some targets only rotate one way. Try the opposite direction.
  5498. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5499. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5500. // Negate the shift amount because it is safe to ignore the high bits.
  5501. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5502. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5503. return;
  5504. }
  5505. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5506. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5507. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5508. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5509. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5510. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5511. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5512. return;
  5513. }
  5514. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5515. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5516. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5517. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5518. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5519. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5520. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5521. // and that is undefined. We must compare and select to avoid UB.
  5522. EVT CCVT = MVT::i1;
  5523. if (VT.isVector())
  5524. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5525. // For fshl, 0-shift returns the 1st arg (X).
  5526. // For fshr, 0-shift returns the 2nd arg (Y).
  5527. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5528. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5529. return;
  5530. }
  5531. case Intrinsic::sadd_sat: {
  5532. SDValue Op1 = getValue(I.getArgOperand(0));
  5533. SDValue Op2 = getValue(I.getArgOperand(1));
  5534. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5535. return;
  5536. }
  5537. case Intrinsic::uadd_sat: {
  5538. SDValue Op1 = getValue(I.getArgOperand(0));
  5539. SDValue Op2 = getValue(I.getArgOperand(1));
  5540. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5541. return;
  5542. }
  5543. case Intrinsic::ssub_sat: {
  5544. SDValue Op1 = getValue(I.getArgOperand(0));
  5545. SDValue Op2 = getValue(I.getArgOperand(1));
  5546. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5547. return;
  5548. }
  5549. case Intrinsic::usub_sat: {
  5550. SDValue Op1 = getValue(I.getArgOperand(0));
  5551. SDValue Op2 = getValue(I.getArgOperand(1));
  5552. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5553. return;
  5554. }
  5555. case Intrinsic::smul_fix:
  5556. case Intrinsic::umul_fix: {
  5557. SDValue Op1 = getValue(I.getArgOperand(0));
  5558. SDValue Op2 = getValue(I.getArgOperand(1));
  5559. SDValue Op3 = getValue(I.getArgOperand(2));
  5560. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5561. Op1.getValueType(), Op1, Op2, Op3));
  5562. return;
  5563. }
  5564. case Intrinsic::smul_fix_sat: {
  5565. SDValue Op1 = getValue(I.getArgOperand(0));
  5566. SDValue Op2 = getValue(I.getArgOperand(1));
  5567. SDValue Op3 = getValue(I.getArgOperand(2));
  5568. setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5569. Op3));
  5570. return;
  5571. }
  5572. case Intrinsic::umul_fix_sat: {
  5573. SDValue Op1 = getValue(I.getArgOperand(0));
  5574. SDValue Op2 = getValue(I.getArgOperand(1));
  5575. SDValue Op3 = getValue(I.getArgOperand(2));
  5576. setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5577. Op3));
  5578. return;
  5579. }
  5580. case Intrinsic::stacksave: {
  5581. SDValue Op = getRoot();
  5582. Res = DAG.getNode(
  5583. ISD::STACKSAVE, sdl,
  5584. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5585. setValue(&I, Res);
  5586. DAG.setRoot(Res.getValue(1));
  5587. return;
  5588. }
  5589. case Intrinsic::stackrestore:
  5590. Res = getValue(I.getArgOperand(0));
  5591. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5592. return;
  5593. case Intrinsic::get_dynamic_area_offset: {
  5594. SDValue Op = getRoot();
  5595. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5596. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5597. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5598. // target.
  5599. if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
  5600. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5601. " intrinsic!");
  5602. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5603. Op);
  5604. DAG.setRoot(Op);
  5605. setValue(&I, Res);
  5606. return;
  5607. }
  5608. case Intrinsic::stackguard: {
  5609. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5610. MachineFunction &MF = DAG.getMachineFunction();
  5611. const Module &M = *MF.getFunction().getParent();
  5612. SDValue Chain = getRoot();
  5613. if (TLI.useLoadStackGuardNode()) {
  5614. Res = getLoadStackGuard(DAG, sdl, Chain);
  5615. } else {
  5616. const Value *Global = TLI.getSDagStackGuard(M);
  5617. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5618. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5619. MachinePointerInfo(Global, 0), Align,
  5620. MachineMemOperand::MOVolatile);
  5621. }
  5622. if (TLI.useStackGuardXorFP())
  5623. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5624. DAG.setRoot(Chain);
  5625. setValue(&I, Res);
  5626. return;
  5627. }
  5628. case Intrinsic::stackprotector: {
  5629. // Emit code into the DAG to store the stack guard onto the stack.
  5630. MachineFunction &MF = DAG.getMachineFunction();
  5631. MachineFrameInfo &MFI = MF.getFrameInfo();
  5632. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5633. SDValue Src, Chain = getRoot();
  5634. if (TLI.useLoadStackGuardNode())
  5635. Src = getLoadStackGuard(DAG, sdl, Chain);
  5636. else
  5637. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5638. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5639. int FI = FuncInfo.StaticAllocaMap[Slot];
  5640. MFI.setStackProtectorIndex(FI);
  5641. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5642. // Store the stack protector onto the stack.
  5643. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5644. DAG.getMachineFunction(), FI),
  5645. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5646. setValue(&I, Res);
  5647. DAG.setRoot(Res);
  5648. return;
  5649. }
  5650. case Intrinsic::objectsize: {
  5651. // If we don't know by now, we're never going to know.
  5652. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5653. assert(CI && "Non-constant type in __builtin_object_size?");
  5654. SDValue Arg = getValue(I.getCalledValue());
  5655. EVT Ty = Arg.getValueType();
  5656. if (CI->isZero())
  5657. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5658. else
  5659. Res = DAG.getConstant(0, sdl, Ty);
  5660. setValue(&I, Res);
  5661. return;
  5662. }
  5663. case Intrinsic::is_constant:
  5664. // If this wasn't constant-folded away by now, then it's not a
  5665. // constant.
  5666. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5667. return;
  5668. case Intrinsic::annotation:
  5669. case Intrinsic::ptr_annotation:
  5670. case Intrinsic::launder_invariant_group:
  5671. case Intrinsic::strip_invariant_group:
  5672. // Drop the intrinsic, but forward the value
  5673. setValue(&I, getValue(I.getOperand(0)));
  5674. return;
  5675. case Intrinsic::assume:
  5676. case Intrinsic::var_annotation:
  5677. case Intrinsic::sideeffect:
  5678. // Discard annotate attributes, assumptions, and artificial side-effects.
  5679. return;
  5680. case Intrinsic::codeview_annotation: {
  5681. // Emit a label associated with this metadata.
  5682. MachineFunction &MF = DAG.getMachineFunction();
  5683. MCSymbol *Label =
  5684. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5685. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5686. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5687. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5688. DAG.setRoot(Res);
  5689. return;
  5690. }
  5691. case Intrinsic::init_trampoline: {
  5692. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5693. SDValue Ops[6];
  5694. Ops[0] = getRoot();
  5695. Ops[1] = getValue(I.getArgOperand(0));
  5696. Ops[2] = getValue(I.getArgOperand(1));
  5697. Ops[3] = getValue(I.getArgOperand(2));
  5698. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5699. Ops[5] = DAG.getSrcValue(F);
  5700. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5701. DAG.setRoot(Res);
  5702. return;
  5703. }
  5704. case Intrinsic::adjust_trampoline:
  5705. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5706. TLI.getPointerTy(DAG.getDataLayout()),
  5707. getValue(I.getArgOperand(0))));
  5708. return;
  5709. case Intrinsic::gcroot: {
  5710. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5711. "only valid in functions with gc specified, enforced by Verifier");
  5712. assert(GFI && "implied by previous");
  5713. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5714. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5715. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5716. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5717. return;
  5718. }
  5719. case Intrinsic::gcread:
  5720. case Intrinsic::gcwrite:
  5721. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5722. case Intrinsic::flt_rounds:
  5723. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5724. return;
  5725. case Intrinsic::expect:
  5726. // Just replace __builtin_expect(exp, c) with EXP.
  5727. setValue(&I, getValue(I.getArgOperand(0)));
  5728. return;
  5729. case Intrinsic::debugtrap:
  5730. case Intrinsic::trap: {
  5731. StringRef TrapFuncName =
  5732. I.getAttributes()
  5733. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5734. .getValueAsString();
  5735. if (TrapFuncName.empty()) {
  5736. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5737. ISD::TRAP : ISD::DEBUGTRAP;
  5738. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5739. return;
  5740. }
  5741. TargetLowering::ArgListTy Args;
  5742. TargetLowering::CallLoweringInfo CLI(DAG);
  5743. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5744. CallingConv::C, I.getType(),
  5745. DAG.getExternalSymbol(TrapFuncName.data(),
  5746. TLI.getPointerTy(DAG.getDataLayout())),
  5747. std::move(Args));
  5748. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5749. DAG.setRoot(Result.second);
  5750. return;
  5751. }
  5752. case Intrinsic::uadd_with_overflow:
  5753. case Intrinsic::sadd_with_overflow:
  5754. case Intrinsic::usub_with_overflow:
  5755. case Intrinsic::ssub_with_overflow:
  5756. case Intrinsic::umul_with_overflow:
  5757. case Intrinsic::smul_with_overflow: {
  5758. ISD::NodeType Op;
  5759. switch (Intrinsic) {
  5760. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5761. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5762. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5763. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5764. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5765. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5766. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5767. }
  5768. SDValue Op1 = getValue(I.getArgOperand(0));
  5769. SDValue Op2 = getValue(I.getArgOperand(1));
  5770. EVT ResultVT = Op1.getValueType();
  5771. EVT OverflowVT = MVT::i1;
  5772. if (ResultVT.isVector())
  5773. OverflowVT = EVT::getVectorVT(
  5774. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5775. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5776. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5777. return;
  5778. }
  5779. case Intrinsic::prefetch: {
  5780. SDValue Ops[5];
  5781. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5782. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5783. Ops[0] = DAG.getRoot();
  5784. Ops[1] = getValue(I.getArgOperand(0));
  5785. Ops[2] = getValue(I.getArgOperand(1));
  5786. Ops[3] = getValue(I.getArgOperand(2));
  5787. Ops[4] = getValue(I.getArgOperand(3));
  5788. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5789. DAG.getVTList(MVT::Other), Ops,
  5790. EVT::getIntegerVT(*Context, 8),
  5791. MachinePointerInfo(I.getArgOperand(0)),
  5792. 0, /* align */
  5793. Flags);
  5794. // Chain the prefetch in parallell with any pending loads, to stay out of
  5795. // the way of later optimizations.
  5796. PendingLoads.push_back(Result);
  5797. Result = getRoot();
  5798. DAG.setRoot(Result);
  5799. return;
  5800. }
  5801. case Intrinsic::lifetime_start:
  5802. case Intrinsic::lifetime_end: {
  5803. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5804. // Stack coloring is not enabled in O0, discard region information.
  5805. if (TM.getOptLevel() == CodeGenOpt::None)
  5806. return;
  5807. const int64_t ObjectSize =
  5808. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5809. Value *const ObjectPtr = I.getArgOperand(1);
  5810. SmallVector<const Value *, 4> Allocas;
  5811. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5812. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5813. E = Allocas.end(); Object != E; ++Object) {
  5814. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5815. // Could not find an Alloca.
  5816. if (!LifetimeObject)
  5817. continue;
  5818. // First check that the Alloca is static, otherwise it won't have a
  5819. // valid frame index.
  5820. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5821. if (SI == FuncInfo.StaticAllocaMap.end())
  5822. return;
  5823. const int FrameIndex = SI->second;
  5824. int64_t Offset;
  5825. if (GetPointerBaseWithConstantOffset(
  5826. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5827. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5828. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5829. Offset);
  5830. DAG.setRoot(Res);
  5831. }
  5832. return;
  5833. }
  5834. case Intrinsic::invariant_start:
  5835. // Discard region information.
  5836. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5837. return;
  5838. case Intrinsic::invariant_end:
  5839. // Discard region information.
  5840. return;
  5841. case Intrinsic::clear_cache:
  5842. /// FunctionName may be null.
  5843. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  5844. lowerCallToExternalSymbol(I, FunctionName);
  5845. return;
  5846. case Intrinsic::donothing:
  5847. // ignore
  5848. return;
  5849. case Intrinsic::experimental_stackmap:
  5850. visitStackmap(I);
  5851. return;
  5852. case Intrinsic::experimental_patchpoint_void:
  5853. case Intrinsic::experimental_patchpoint_i64:
  5854. visitPatchpoint(&I);
  5855. return;
  5856. case Intrinsic::experimental_gc_statepoint:
  5857. LowerStatepoint(ImmutableStatepoint(&I));
  5858. return;
  5859. case Intrinsic::experimental_gc_result:
  5860. visitGCResult(cast<GCResultInst>(I));
  5861. return;
  5862. case Intrinsic::experimental_gc_relocate:
  5863. visitGCRelocate(cast<GCRelocateInst>(I));
  5864. return;
  5865. case Intrinsic::instrprof_increment:
  5866. llvm_unreachable("instrprof failed to lower an increment");
  5867. case Intrinsic::instrprof_value_profile:
  5868. llvm_unreachable("instrprof failed to lower a value profiling call");
  5869. case Intrinsic::localescape: {
  5870. MachineFunction &MF = DAG.getMachineFunction();
  5871. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5872. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5873. // is the same on all targets.
  5874. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5875. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5876. if (isa<ConstantPointerNull>(Arg))
  5877. continue; // Skip null pointers. They represent a hole in index space.
  5878. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5879. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5880. "can only escape static allocas");
  5881. int FI = FuncInfo.StaticAllocaMap[Slot];
  5882. MCSymbol *FrameAllocSym =
  5883. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5884. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5885. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5886. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5887. .addSym(FrameAllocSym)
  5888. .addFrameIndex(FI);
  5889. }
  5890. return;
  5891. }
  5892. case Intrinsic::localrecover: {
  5893. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5894. MachineFunction &MF = DAG.getMachineFunction();
  5895. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5896. // Get the symbol that defines the frame offset.
  5897. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5898. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5899. unsigned IdxVal =
  5900. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5901. MCSymbol *FrameAllocSym =
  5902. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5903. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5904. // Create a MCSymbol for the label to avoid any target lowering
  5905. // that would make this PC relative.
  5906. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5907. SDValue OffsetVal =
  5908. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5909. // Add the offset to the FP.
  5910. Value *FP = I.getArgOperand(1);
  5911. SDValue FPVal = getValue(FP);
  5912. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5913. setValue(&I, Add);
  5914. return;
  5915. }
  5916. case Intrinsic::eh_exceptionpointer:
  5917. case Intrinsic::eh_exceptioncode: {
  5918. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5919. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5920. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5921. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5922. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5923. SDValue N =
  5924. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5925. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5926. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5927. setValue(&I, N);
  5928. return;
  5929. }
  5930. case Intrinsic::xray_customevent: {
  5931. // Here we want to make sure that the intrinsic behaves as if it has a
  5932. // specific calling convention, and only for x86_64.
  5933. // FIXME: Support other platforms later.
  5934. const auto &Triple = DAG.getTarget().getTargetTriple();
  5935. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5936. return;
  5937. SDLoc DL = getCurSDLoc();
  5938. SmallVector<SDValue, 8> Ops;
  5939. // We want to say that we always want the arguments in registers.
  5940. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5941. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5942. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5943. SDValue Chain = getRoot();
  5944. Ops.push_back(LogEntryVal);
  5945. Ops.push_back(StrSizeVal);
  5946. Ops.push_back(Chain);
  5947. // We need to enforce the calling convention for the callsite, so that
  5948. // argument ordering is enforced correctly, and that register allocation can
  5949. // see that some registers may be assumed clobbered and have to preserve
  5950. // them across calls to the intrinsic.
  5951. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5952. DL, NodeTys, Ops);
  5953. SDValue patchableNode = SDValue(MN, 0);
  5954. DAG.setRoot(patchableNode);
  5955. setValue(&I, patchableNode);
  5956. return;
  5957. }
  5958. case Intrinsic::xray_typedevent: {
  5959. // Here we want to make sure that the intrinsic behaves as if it has a
  5960. // specific calling convention, and only for x86_64.
  5961. // FIXME: Support other platforms later.
  5962. const auto &Triple = DAG.getTarget().getTargetTriple();
  5963. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5964. return;
  5965. SDLoc DL = getCurSDLoc();
  5966. SmallVector<SDValue, 8> Ops;
  5967. // We want to say that we always want the arguments in registers.
  5968. // It's unclear to me how manipulating the selection DAG here forces callers
  5969. // to provide arguments in registers instead of on the stack.
  5970. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5971. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5972. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5973. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5974. SDValue Chain = getRoot();
  5975. Ops.push_back(LogTypeId);
  5976. Ops.push_back(LogEntryVal);
  5977. Ops.push_back(StrSizeVal);
  5978. Ops.push_back(Chain);
  5979. // We need to enforce the calling convention for the callsite, so that
  5980. // argument ordering is enforced correctly, and that register allocation can
  5981. // see that some registers may be assumed clobbered and have to preserve
  5982. // them across calls to the intrinsic.
  5983. MachineSDNode *MN = DAG.getMachineNode(
  5984. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5985. SDValue patchableNode = SDValue(MN, 0);
  5986. DAG.setRoot(patchableNode);
  5987. setValue(&I, patchableNode);
  5988. return;
  5989. }
  5990. case Intrinsic::experimental_deoptimize:
  5991. LowerDeoptimizeCall(&I);
  5992. return;
  5993. case Intrinsic::experimental_vector_reduce_v2_fadd:
  5994. case Intrinsic::experimental_vector_reduce_v2_fmul:
  5995. case Intrinsic::experimental_vector_reduce_add:
  5996. case Intrinsic::experimental_vector_reduce_mul:
  5997. case Intrinsic::experimental_vector_reduce_and:
  5998. case Intrinsic::experimental_vector_reduce_or:
  5999. case Intrinsic::experimental_vector_reduce_xor:
  6000. case Intrinsic::experimental_vector_reduce_smax:
  6001. case Intrinsic::experimental_vector_reduce_smin:
  6002. case Intrinsic::experimental_vector_reduce_umax:
  6003. case Intrinsic::experimental_vector_reduce_umin:
  6004. case Intrinsic::experimental_vector_reduce_fmax:
  6005. case Intrinsic::experimental_vector_reduce_fmin:
  6006. visitVectorReduce(I, Intrinsic);
  6007. return;
  6008. case Intrinsic::icall_branch_funnel: {
  6009. SmallVector<SDValue, 16> Ops;
  6010. Ops.push_back(getValue(I.getArgOperand(0)));
  6011. int64_t Offset;
  6012. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6013. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  6014. if (!Base)
  6015. report_fatal_error(
  6016. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6017. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  6018. struct BranchFunnelTarget {
  6019. int64_t Offset;
  6020. SDValue Target;
  6021. };
  6022. SmallVector<BranchFunnelTarget, 8> Targets;
  6023. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  6024. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6025. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6026. if (ElemBase != Base)
  6027. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6028. "to the same GlobalValue");
  6029. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6030. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6031. if (!GA)
  6032. report_fatal_error(
  6033. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6034. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6035. GA->getGlobal(), getCurSDLoc(),
  6036. Val.getValueType(), GA->getOffset())});
  6037. }
  6038. llvm::sort(Targets,
  6039. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6040. return T1.Offset < T2.Offset;
  6041. });
  6042. for (auto &T : Targets) {
  6043. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  6044. Ops.push_back(T.Target);
  6045. }
  6046. Ops.push_back(DAG.getRoot()); // Chain
  6047. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  6048. getCurSDLoc(), MVT::Other, Ops),
  6049. 0);
  6050. DAG.setRoot(N);
  6051. setValue(&I, N);
  6052. HasTailCall = true;
  6053. return;
  6054. }
  6055. case Intrinsic::wasm_landingpad_index:
  6056. // Information this intrinsic contained has been transferred to
  6057. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6058. // delete it now.
  6059. return;
  6060. case Intrinsic::aarch64_settag:
  6061. case Intrinsic::aarch64_settag_zero: {
  6062. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6063. bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
  6064. SDValue Val = TSI.EmitTargetCodeForSetTag(
  6065. DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
  6066. getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
  6067. ZeroMemory);
  6068. DAG.setRoot(Val);
  6069. setValue(&I, Val);
  6070. return;
  6071. }
  6072. case Intrinsic::ptrmask: {
  6073. SDValue Ptr = getValue(I.getOperand(0));
  6074. SDValue Const = getValue(I.getOperand(1));
  6075. EVT DestVT =
  6076. EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6077. setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
  6078. DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
  6079. return;
  6080. }
  6081. }
  6082. }
  6083. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6084. const ConstrainedFPIntrinsic &FPI) {
  6085. SDLoc sdl = getCurSDLoc();
  6086. unsigned Opcode;
  6087. switch (FPI.getIntrinsicID()) {
  6088. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6089. case Intrinsic::experimental_constrained_fadd:
  6090. Opcode = ISD::STRICT_FADD;
  6091. break;
  6092. case Intrinsic::experimental_constrained_fsub:
  6093. Opcode = ISD::STRICT_FSUB;
  6094. break;
  6095. case Intrinsic::experimental_constrained_fmul:
  6096. Opcode = ISD::STRICT_FMUL;
  6097. break;
  6098. case Intrinsic::experimental_constrained_fdiv:
  6099. Opcode = ISD::STRICT_FDIV;
  6100. break;
  6101. case Intrinsic::experimental_constrained_frem:
  6102. Opcode = ISD::STRICT_FREM;
  6103. break;
  6104. case Intrinsic::experimental_constrained_fma:
  6105. Opcode = ISD::STRICT_FMA;
  6106. break;
  6107. case Intrinsic::experimental_constrained_fptosi:
  6108. Opcode = ISD::STRICT_FP_TO_SINT;
  6109. break;
  6110. case Intrinsic::experimental_constrained_fptoui:
  6111. Opcode = ISD::STRICT_FP_TO_UINT;
  6112. break;
  6113. case Intrinsic::experimental_constrained_fptrunc:
  6114. Opcode = ISD::STRICT_FP_ROUND;
  6115. break;
  6116. case Intrinsic::experimental_constrained_fpext:
  6117. Opcode = ISD::STRICT_FP_EXTEND;
  6118. break;
  6119. case Intrinsic::experimental_constrained_sqrt:
  6120. Opcode = ISD::STRICT_FSQRT;
  6121. break;
  6122. case Intrinsic::experimental_constrained_pow:
  6123. Opcode = ISD::STRICT_FPOW;
  6124. break;
  6125. case Intrinsic::experimental_constrained_powi:
  6126. Opcode = ISD::STRICT_FPOWI;
  6127. break;
  6128. case Intrinsic::experimental_constrained_sin:
  6129. Opcode = ISD::STRICT_FSIN;
  6130. break;
  6131. case Intrinsic::experimental_constrained_cos:
  6132. Opcode = ISD::STRICT_FCOS;
  6133. break;
  6134. case Intrinsic::experimental_constrained_exp:
  6135. Opcode = ISD::STRICT_FEXP;
  6136. break;
  6137. case Intrinsic::experimental_constrained_exp2:
  6138. Opcode = ISD::STRICT_FEXP2;
  6139. break;
  6140. case Intrinsic::experimental_constrained_log:
  6141. Opcode = ISD::STRICT_FLOG;
  6142. break;
  6143. case Intrinsic::experimental_constrained_log10:
  6144. Opcode = ISD::STRICT_FLOG10;
  6145. break;
  6146. case Intrinsic::experimental_constrained_log2:
  6147. Opcode = ISD::STRICT_FLOG2;
  6148. break;
  6149. case Intrinsic::experimental_constrained_rint:
  6150. Opcode = ISD::STRICT_FRINT;
  6151. break;
  6152. case Intrinsic::experimental_constrained_nearbyint:
  6153. Opcode = ISD::STRICT_FNEARBYINT;
  6154. break;
  6155. case Intrinsic::experimental_constrained_maxnum:
  6156. Opcode = ISD::STRICT_FMAXNUM;
  6157. break;
  6158. case Intrinsic::experimental_constrained_minnum:
  6159. Opcode = ISD::STRICT_FMINNUM;
  6160. break;
  6161. case Intrinsic::experimental_constrained_ceil:
  6162. Opcode = ISD::STRICT_FCEIL;
  6163. break;
  6164. case Intrinsic::experimental_constrained_floor:
  6165. Opcode = ISD::STRICT_FFLOOR;
  6166. break;
  6167. case Intrinsic::experimental_constrained_round:
  6168. Opcode = ISD::STRICT_FROUND;
  6169. break;
  6170. case Intrinsic::experimental_constrained_trunc:
  6171. Opcode = ISD::STRICT_FTRUNC;
  6172. break;
  6173. }
  6174. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6175. SDValue Chain = getRoot();
  6176. SmallVector<EVT, 4> ValueVTs;
  6177. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6178. ValueVTs.push_back(MVT::Other); // Out chain
  6179. SDVTList VTs = DAG.getVTList(ValueVTs);
  6180. SDValue Result;
  6181. if (Opcode == ISD::STRICT_FP_ROUND)
  6182. Result = DAG.getNode(Opcode, sdl, VTs,
  6183. { Chain, getValue(FPI.getArgOperand(0)),
  6184. DAG.getTargetConstant(0, sdl,
  6185. TLI.getPointerTy(DAG.getDataLayout())) });
  6186. else if (FPI.isUnaryOp())
  6187. Result = DAG.getNode(Opcode, sdl, VTs,
  6188. { Chain, getValue(FPI.getArgOperand(0)) });
  6189. else if (FPI.isTernaryOp())
  6190. Result = DAG.getNode(Opcode, sdl, VTs,
  6191. { Chain, getValue(FPI.getArgOperand(0)),
  6192. getValue(FPI.getArgOperand(1)),
  6193. getValue(FPI.getArgOperand(2)) });
  6194. else
  6195. Result = DAG.getNode(Opcode, sdl, VTs,
  6196. { Chain, getValue(FPI.getArgOperand(0)),
  6197. getValue(FPI.getArgOperand(1)) });
  6198. if (FPI.getExceptionBehavior() !=
  6199. ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
  6200. SDNodeFlags Flags;
  6201. Flags.setFPExcept(true);
  6202. Result->setFlags(Flags);
  6203. }
  6204. assert(Result.getNode()->getNumValues() == 2);
  6205. SDValue OutChain = Result.getValue(1);
  6206. DAG.setRoot(OutChain);
  6207. SDValue FPResult = Result.getValue(0);
  6208. setValue(&FPI, FPResult);
  6209. }
  6210. std::pair<SDValue, SDValue>
  6211. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6212. const BasicBlock *EHPadBB) {
  6213. MachineFunction &MF = DAG.getMachineFunction();
  6214. MachineModuleInfo &MMI = MF.getMMI();
  6215. MCSymbol *BeginLabel = nullptr;
  6216. if (EHPadBB) {
  6217. // Insert a label before the invoke call to mark the try range. This can be
  6218. // used to detect deletion of the invoke via the MachineModuleInfo.
  6219. BeginLabel = MMI.getContext().createTempSymbol();
  6220. // For SjLj, keep track of which landing pads go with which invokes
  6221. // so as to maintain the ordering of pads in the LSDA.
  6222. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6223. if (CallSiteIndex) {
  6224. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6225. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6226. // Now that the call site is handled, stop tracking it.
  6227. MMI.setCurrentCallSite(0);
  6228. }
  6229. // Both PendingLoads and PendingExports must be flushed here;
  6230. // this call might not return.
  6231. (void)getRoot();
  6232. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6233. CLI.setChain(getRoot());
  6234. }
  6235. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6236. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6237. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6238. "Non-null chain expected with non-tail call!");
  6239. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6240. "Null value expected with tail call!");
  6241. if (!Result.second.getNode()) {
  6242. // As a special case, a null chain means that a tail call has been emitted
  6243. // and the DAG root is already updated.
  6244. HasTailCall = true;
  6245. // Since there's no actual continuation from this block, nothing can be
  6246. // relying on us setting vregs for them.
  6247. PendingExports.clear();
  6248. } else {
  6249. DAG.setRoot(Result.second);
  6250. }
  6251. if (EHPadBB) {
  6252. // Insert a label at the end of the invoke call to mark the try range. This
  6253. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6254. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6255. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6256. // Inform MachineModuleInfo of range.
  6257. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6258. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6259. // actually use outlined funclets and their LSDA info style.
  6260. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6261. assert(CLI.CS);
  6262. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6263. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6264. BeginLabel, EndLabel);
  6265. } else if (!isScopedEHPersonality(Pers)) {
  6266. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6267. }
  6268. }
  6269. return Result;
  6270. }
  6271. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6272. bool isTailCall,
  6273. const BasicBlock *EHPadBB) {
  6274. auto &DL = DAG.getDataLayout();
  6275. FunctionType *FTy = CS.getFunctionType();
  6276. Type *RetTy = CS.getType();
  6277. TargetLowering::ArgListTy Args;
  6278. Args.reserve(CS.arg_size());
  6279. const Value *SwiftErrorVal = nullptr;
  6280. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6281. // We can't tail call inside a function with a swifterror argument. Lowering
  6282. // does not support this yet. It would have to move into the swifterror
  6283. // register before the call.
  6284. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6285. if (TLI.supportSwiftError() &&
  6286. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6287. isTailCall = false;
  6288. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6289. i != e; ++i) {
  6290. TargetLowering::ArgListEntry Entry;
  6291. const Value *V = *i;
  6292. // Skip empty types
  6293. if (V->getType()->isEmptyTy())
  6294. continue;
  6295. SDValue ArgNode = getValue(V);
  6296. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6297. Entry.setAttributes(&CS, i - CS.arg_begin());
  6298. // Use swifterror virtual register as input to the call.
  6299. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6300. SwiftErrorVal = V;
  6301. // We find the virtual register for the actual swifterror argument.
  6302. // Instead of using the Value, we use the virtual register instead.
  6303. Entry.Node = DAG.getRegister(
  6304. SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
  6305. EVT(TLI.getPointerTy(DL)));
  6306. }
  6307. Args.push_back(Entry);
  6308. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6309. // might point to function-local memory), we can't meaningfully tail-call.
  6310. if (Entry.IsSRet && isa<Instruction>(V))
  6311. isTailCall = false;
  6312. }
  6313. // Check if target-independent constraints permit a tail call here.
  6314. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6315. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6316. isTailCall = false;
  6317. // Disable tail calls if there is an swifterror argument. Targets have not
  6318. // been updated to support tail calls.
  6319. if (TLI.supportSwiftError() && SwiftErrorVal)
  6320. isTailCall = false;
  6321. TargetLowering::CallLoweringInfo CLI(DAG);
  6322. CLI.setDebugLoc(getCurSDLoc())
  6323. .setChain(getRoot())
  6324. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6325. .setTailCall(isTailCall)
  6326. .setConvergent(CS.isConvergent());
  6327. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6328. if (Result.first.getNode()) {
  6329. const Instruction *Inst = CS.getInstruction();
  6330. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6331. setValue(Inst, Result.first);
  6332. }
  6333. // The last element of CLI.InVals has the SDValue for swifterror return.
  6334. // Here we copy it to a virtual register and update SwiftErrorMap for
  6335. // book-keeping.
  6336. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6337. // Get the last element of InVals.
  6338. SDValue Src = CLI.InVals.back();
  6339. Register VReg = SwiftError.getOrCreateVRegDefAt(
  6340. CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
  6341. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6342. DAG.setRoot(CopyNode);
  6343. }
  6344. }
  6345. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6346. SelectionDAGBuilder &Builder) {
  6347. // Check to see if this load can be trivially constant folded, e.g. if the
  6348. // input is from a string literal.
  6349. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6350. // Cast pointer to the type we really want to load.
  6351. Type *LoadTy =
  6352. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6353. if (LoadVT.isVector())
  6354. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6355. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6356. PointerType::getUnqual(LoadTy));
  6357. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6358. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6359. return Builder.getValue(LoadCst);
  6360. }
  6361. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6362. // still constant memory, the input chain can be the entry node.
  6363. SDValue Root;
  6364. bool ConstantMemory = false;
  6365. // Do not serialize (non-volatile) loads of constant memory with anything.
  6366. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6367. Root = Builder.DAG.getEntryNode();
  6368. ConstantMemory = true;
  6369. } else {
  6370. // Do not serialize non-volatile loads against each other.
  6371. Root = Builder.DAG.getRoot();
  6372. }
  6373. SDValue Ptr = Builder.getValue(PtrVal);
  6374. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6375. Ptr, MachinePointerInfo(PtrVal),
  6376. /* Alignment = */ 1);
  6377. if (!ConstantMemory)
  6378. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6379. return LoadVal;
  6380. }
  6381. /// Record the value for an instruction that produces an integer result,
  6382. /// converting the type where necessary.
  6383. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6384. SDValue Value,
  6385. bool IsSigned) {
  6386. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6387. I.getType(), true);
  6388. if (IsSigned)
  6389. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6390. else
  6391. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6392. setValue(&I, Value);
  6393. }
  6394. /// See if we can lower a memcmp call into an optimized form. If so, return
  6395. /// true and lower it. Otherwise return false, and it will be lowered like a
  6396. /// normal call.
  6397. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6398. /// correct prototype.
  6399. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6400. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6401. const Value *Size = I.getArgOperand(2);
  6402. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6403. if (CSize && CSize->getZExtValue() == 0) {
  6404. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6405. I.getType(), true);
  6406. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6407. return true;
  6408. }
  6409. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6410. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6411. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6412. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6413. if (Res.first.getNode()) {
  6414. processIntegerCallValue(I, Res.first, true);
  6415. PendingLoads.push_back(Res.second);
  6416. return true;
  6417. }
  6418. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6419. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6420. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6421. return false;
  6422. // If the target has a fast compare for the given size, it will return a
  6423. // preferred load type for that size. Require that the load VT is legal and
  6424. // that the target supports unaligned loads of that type. Otherwise, return
  6425. // INVALID.
  6426. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6427. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6428. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6429. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6430. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6431. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6432. // TODO: Check alignment of src and dest ptrs.
  6433. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6434. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6435. if (!TLI.isTypeLegal(LVT) ||
  6436. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6437. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6438. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6439. }
  6440. return LVT;
  6441. };
  6442. // This turns into unaligned loads. We only do this if the target natively
  6443. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6444. // we'll only produce a small number of byte loads.
  6445. MVT LoadVT;
  6446. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6447. switch (NumBitsToCompare) {
  6448. default:
  6449. return false;
  6450. case 16:
  6451. LoadVT = MVT::i16;
  6452. break;
  6453. case 32:
  6454. LoadVT = MVT::i32;
  6455. break;
  6456. case 64:
  6457. case 128:
  6458. case 256:
  6459. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6460. break;
  6461. }
  6462. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6463. return false;
  6464. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6465. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6466. // Bitcast to a wide integer type if the loads are vectors.
  6467. if (LoadVT.isVector()) {
  6468. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6469. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6470. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6471. }
  6472. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6473. processIntegerCallValue(I, Cmp, false);
  6474. return true;
  6475. }
  6476. /// See if we can lower a memchr call into an optimized form. If so, return
  6477. /// true and lower it. Otherwise return false, and it will be lowered like a
  6478. /// normal call.
  6479. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6480. /// correct prototype.
  6481. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6482. const Value *Src = I.getArgOperand(0);
  6483. const Value *Char = I.getArgOperand(1);
  6484. const Value *Length = I.getArgOperand(2);
  6485. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6486. std::pair<SDValue, SDValue> Res =
  6487. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6488. getValue(Src), getValue(Char), getValue(Length),
  6489. MachinePointerInfo(Src));
  6490. if (Res.first.getNode()) {
  6491. setValue(&I, Res.first);
  6492. PendingLoads.push_back(Res.second);
  6493. return true;
  6494. }
  6495. return false;
  6496. }
  6497. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6498. /// true and lower it. Otherwise return false, and it will be lowered like a
  6499. /// normal call.
  6500. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6501. /// correct prototype.
  6502. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6503. SDValue Dst = getValue(I.getArgOperand(0));
  6504. SDValue Src = getValue(I.getArgOperand(1));
  6505. SDValue Size = getValue(I.getArgOperand(2));
  6506. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6507. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6508. unsigned Align = std::min(DstAlign, SrcAlign);
  6509. if (Align == 0) // Alignment of one or both could not be inferred.
  6510. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6511. bool isVol = false;
  6512. SDLoc sdl = getCurSDLoc();
  6513. // In the mempcpy context we need to pass in a false value for isTailCall
  6514. // because the return pointer needs to be adjusted by the size of
  6515. // the copied memory.
  6516. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6517. false, /*isTailCall=*/false,
  6518. MachinePointerInfo(I.getArgOperand(0)),
  6519. MachinePointerInfo(I.getArgOperand(1)));
  6520. assert(MC.getNode() != nullptr &&
  6521. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6522. DAG.setRoot(MC);
  6523. // Check if Size needs to be truncated or extended.
  6524. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6525. // Adjust return pointer to point just past the last dst byte.
  6526. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6527. Dst, Size);
  6528. setValue(&I, DstPlusSize);
  6529. return true;
  6530. }
  6531. /// See if we can lower a strcpy call into an optimized form. If so, return
  6532. /// true and lower it, otherwise return false and it will be lowered like a
  6533. /// normal call.
  6534. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6535. /// correct prototype.
  6536. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6537. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6538. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6539. std::pair<SDValue, SDValue> Res =
  6540. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6541. getValue(Arg0), getValue(Arg1),
  6542. MachinePointerInfo(Arg0),
  6543. MachinePointerInfo(Arg1), isStpcpy);
  6544. if (Res.first.getNode()) {
  6545. setValue(&I, Res.first);
  6546. DAG.setRoot(Res.second);
  6547. return true;
  6548. }
  6549. return false;
  6550. }
  6551. /// See if we can lower a strcmp call into an optimized form. If so, return
  6552. /// true and lower it, otherwise return false and it will be lowered like a
  6553. /// normal call.
  6554. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6555. /// correct prototype.
  6556. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6557. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6558. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6559. std::pair<SDValue, SDValue> Res =
  6560. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6561. getValue(Arg0), getValue(Arg1),
  6562. MachinePointerInfo(Arg0),
  6563. MachinePointerInfo(Arg1));
  6564. if (Res.first.getNode()) {
  6565. processIntegerCallValue(I, Res.first, true);
  6566. PendingLoads.push_back(Res.second);
  6567. return true;
  6568. }
  6569. return false;
  6570. }
  6571. /// See if we can lower a strlen call into an optimized form. If so, return
  6572. /// true and lower it, otherwise return false and it will be lowered like a
  6573. /// normal call.
  6574. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6575. /// correct prototype.
  6576. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6577. const Value *Arg0 = I.getArgOperand(0);
  6578. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6579. std::pair<SDValue, SDValue> Res =
  6580. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6581. getValue(Arg0), MachinePointerInfo(Arg0));
  6582. if (Res.first.getNode()) {
  6583. processIntegerCallValue(I, Res.first, false);
  6584. PendingLoads.push_back(Res.second);
  6585. return true;
  6586. }
  6587. return false;
  6588. }
  6589. /// See if we can lower a strnlen call into an optimized form. If so, return
  6590. /// true and lower it, otherwise return false and it will be lowered like a
  6591. /// normal call.
  6592. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6593. /// correct prototype.
  6594. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6595. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6596. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6597. std::pair<SDValue, SDValue> Res =
  6598. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6599. getValue(Arg0), getValue(Arg1),
  6600. MachinePointerInfo(Arg0));
  6601. if (Res.first.getNode()) {
  6602. processIntegerCallValue(I, Res.first, false);
  6603. PendingLoads.push_back(Res.second);
  6604. return true;
  6605. }
  6606. return false;
  6607. }
  6608. /// See if we can lower a unary floating-point operation into an SDNode with
  6609. /// the specified Opcode. If so, return true and lower it, otherwise return
  6610. /// false and it will be lowered like a normal call.
  6611. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6612. /// correct prototype.
  6613. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6614. unsigned Opcode) {
  6615. // We already checked this call's prototype; verify it doesn't modify errno.
  6616. if (!I.onlyReadsMemory())
  6617. return false;
  6618. SDValue Tmp = getValue(I.getArgOperand(0));
  6619. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6620. return true;
  6621. }
  6622. /// See if we can lower a binary floating-point operation into an SDNode with
  6623. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6624. /// false, and it will be lowered like a normal call.
  6625. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6626. /// correct prototype.
  6627. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6628. unsigned Opcode) {
  6629. // We already checked this call's prototype; verify it doesn't modify errno.
  6630. if (!I.onlyReadsMemory())
  6631. return false;
  6632. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6633. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6634. EVT VT = Tmp0.getValueType();
  6635. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6636. return true;
  6637. }
  6638. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6639. // Handle inline assembly differently.
  6640. if (isa<InlineAsm>(I.getCalledValue())) {
  6641. visitInlineAsm(&I);
  6642. return;
  6643. }
  6644. if (Function *F = I.getCalledFunction()) {
  6645. if (F->isDeclaration()) {
  6646. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6647. unsigned IID = F->getIntrinsicID();
  6648. if (!IID)
  6649. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6650. IID = II->getIntrinsicID(F);
  6651. if (IID) {
  6652. visitIntrinsicCall(I, IID);
  6653. return;
  6654. }
  6655. }
  6656. // Check for well-known libc/libm calls. If the function is internal, it
  6657. // can't be a library call. Don't do the check if marked as nobuiltin for
  6658. // some reason or the call site requires strict floating point semantics.
  6659. LibFunc Func;
  6660. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6661. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6662. LibInfo->hasOptimizedCodeGen(Func)) {
  6663. switch (Func) {
  6664. default: break;
  6665. case LibFunc_copysign:
  6666. case LibFunc_copysignf:
  6667. case LibFunc_copysignl:
  6668. // We already checked this call's prototype; verify it doesn't modify
  6669. // errno.
  6670. if (I.onlyReadsMemory()) {
  6671. SDValue LHS = getValue(I.getArgOperand(0));
  6672. SDValue RHS = getValue(I.getArgOperand(1));
  6673. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6674. LHS.getValueType(), LHS, RHS));
  6675. return;
  6676. }
  6677. break;
  6678. case LibFunc_fabs:
  6679. case LibFunc_fabsf:
  6680. case LibFunc_fabsl:
  6681. if (visitUnaryFloatCall(I, ISD::FABS))
  6682. return;
  6683. break;
  6684. case LibFunc_fmin:
  6685. case LibFunc_fminf:
  6686. case LibFunc_fminl:
  6687. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6688. return;
  6689. break;
  6690. case LibFunc_fmax:
  6691. case LibFunc_fmaxf:
  6692. case LibFunc_fmaxl:
  6693. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6694. return;
  6695. break;
  6696. case LibFunc_sin:
  6697. case LibFunc_sinf:
  6698. case LibFunc_sinl:
  6699. if (visitUnaryFloatCall(I, ISD::FSIN))
  6700. return;
  6701. break;
  6702. case LibFunc_cos:
  6703. case LibFunc_cosf:
  6704. case LibFunc_cosl:
  6705. if (visitUnaryFloatCall(I, ISD::FCOS))
  6706. return;
  6707. break;
  6708. case LibFunc_sqrt:
  6709. case LibFunc_sqrtf:
  6710. case LibFunc_sqrtl:
  6711. case LibFunc_sqrt_finite:
  6712. case LibFunc_sqrtf_finite:
  6713. case LibFunc_sqrtl_finite:
  6714. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6715. return;
  6716. break;
  6717. case LibFunc_floor:
  6718. case LibFunc_floorf:
  6719. case LibFunc_floorl:
  6720. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6721. return;
  6722. break;
  6723. case LibFunc_nearbyint:
  6724. case LibFunc_nearbyintf:
  6725. case LibFunc_nearbyintl:
  6726. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6727. return;
  6728. break;
  6729. case LibFunc_ceil:
  6730. case LibFunc_ceilf:
  6731. case LibFunc_ceill:
  6732. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6733. return;
  6734. break;
  6735. case LibFunc_rint:
  6736. case LibFunc_rintf:
  6737. case LibFunc_rintl:
  6738. if (visitUnaryFloatCall(I, ISD::FRINT))
  6739. return;
  6740. break;
  6741. case LibFunc_round:
  6742. case LibFunc_roundf:
  6743. case LibFunc_roundl:
  6744. if (visitUnaryFloatCall(I, ISD::FROUND))
  6745. return;
  6746. break;
  6747. case LibFunc_trunc:
  6748. case LibFunc_truncf:
  6749. case LibFunc_truncl:
  6750. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6751. return;
  6752. break;
  6753. case LibFunc_log2:
  6754. case LibFunc_log2f:
  6755. case LibFunc_log2l:
  6756. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6757. return;
  6758. break;
  6759. case LibFunc_exp2:
  6760. case LibFunc_exp2f:
  6761. case LibFunc_exp2l:
  6762. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6763. return;
  6764. break;
  6765. case LibFunc_memcmp:
  6766. if (visitMemCmpCall(I))
  6767. return;
  6768. break;
  6769. case LibFunc_mempcpy:
  6770. if (visitMemPCpyCall(I))
  6771. return;
  6772. break;
  6773. case LibFunc_memchr:
  6774. if (visitMemChrCall(I))
  6775. return;
  6776. break;
  6777. case LibFunc_strcpy:
  6778. if (visitStrCpyCall(I, false))
  6779. return;
  6780. break;
  6781. case LibFunc_stpcpy:
  6782. if (visitStrCpyCall(I, true))
  6783. return;
  6784. break;
  6785. case LibFunc_strcmp:
  6786. if (visitStrCmpCall(I))
  6787. return;
  6788. break;
  6789. case LibFunc_strlen:
  6790. if (visitStrLenCall(I))
  6791. return;
  6792. break;
  6793. case LibFunc_strnlen:
  6794. if (visitStrNLenCall(I))
  6795. return;
  6796. break;
  6797. }
  6798. }
  6799. }
  6800. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6801. // have to do anything here to lower funclet bundles.
  6802. assert(!I.hasOperandBundlesOtherThan(
  6803. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6804. "Cannot lower calls with arbitrary operand bundles!");
  6805. SDValue Callee = getValue(I.getCalledValue());
  6806. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6807. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6808. else
  6809. // Check if we can potentially perform a tail call. More detailed checking
  6810. // is be done within LowerCallTo, after more information about the call is
  6811. // known.
  6812. LowerCallTo(&I, Callee, I.isTailCall());
  6813. }
  6814. namespace {
  6815. /// AsmOperandInfo - This contains information for each constraint that we are
  6816. /// lowering.
  6817. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6818. public:
  6819. /// CallOperand - If this is the result output operand or a clobber
  6820. /// this is null, otherwise it is the incoming operand to the CallInst.
  6821. /// This gets modified as the asm is processed.
  6822. SDValue CallOperand;
  6823. /// AssignedRegs - If this is a register or register class operand, this
  6824. /// contains the set of register corresponding to the operand.
  6825. RegsForValue AssignedRegs;
  6826. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6827. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6828. }
  6829. /// Whether or not this operand accesses memory
  6830. bool hasMemory(const TargetLowering &TLI) const {
  6831. // Indirect operand accesses access memory.
  6832. if (isIndirect)
  6833. return true;
  6834. for (const auto &Code : Codes)
  6835. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6836. return true;
  6837. return false;
  6838. }
  6839. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6840. /// corresponds to. If there is no Value* for this operand, it returns
  6841. /// MVT::Other.
  6842. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6843. const DataLayout &DL) const {
  6844. if (!CallOperandVal) return MVT::Other;
  6845. if (isa<BasicBlock>(CallOperandVal))
  6846. return TLI.getPointerTy(DL);
  6847. llvm::Type *OpTy = CallOperandVal->getType();
  6848. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6849. // If this is an indirect operand, the operand is a pointer to the
  6850. // accessed type.
  6851. if (isIndirect) {
  6852. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6853. if (!PtrTy)
  6854. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6855. OpTy = PtrTy->getElementType();
  6856. }
  6857. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6858. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6859. if (STy->getNumElements() == 1)
  6860. OpTy = STy->getElementType(0);
  6861. // If OpTy is not a single value, it may be a struct/union that we
  6862. // can tile with integers.
  6863. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6864. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6865. switch (BitSize) {
  6866. default: break;
  6867. case 1:
  6868. case 8:
  6869. case 16:
  6870. case 32:
  6871. case 64:
  6872. case 128:
  6873. OpTy = IntegerType::get(Context, BitSize);
  6874. break;
  6875. }
  6876. }
  6877. return TLI.getValueType(DL, OpTy, true);
  6878. }
  6879. };
  6880. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6881. } // end anonymous namespace
  6882. /// Make sure that the output operand \p OpInfo and its corresponding input
  6883. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6884. /// out).
  6885. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6886. SDISelAsmOperandInfo &MatchingOpInfo,
  6887. SelectionDAG &DAG) {
  6888. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6889. return;
  6890. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6891. const auto &TLI = DAG.getTargetLoweringInfo();
  6892. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6893. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6894. OpInfo.ConstraintVT);
  6895. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6896. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6897. MatchingOpInfo.ConstraintVT);
  6898. if ((OpInfo.ConstraintVT.isInteger() !=
  6899. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6900. (MatchRC.second != InputRC.second)) {
  6901. // FIXME: error out in a more elegant fashion
  6902. report_fatal_error("Unsupported asm: input constraint"
  6903. " with a matching output constraint of"
  6904. " incompatible type!");
  6905. }
  6906. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6907. }
  6908. /// Get a direct memory input to behave well as an indirect operand.
  6909. /// This may introduce stores, hence the need for a \p Chain.
  6910. /// \return The (possibly updated) chain.
  6911. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6912. SDISelAsmOperandInfo &OpInfo,
  6913. SelectionDAG &DAG) {
  6914. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6915. // If we don't have an indirect input, put it in the constpool if we can,
  6916. // otherwise spill it to a stack slot.
  6917. // TODO: This isn't quite right. We need to handle these according to
  6918. // the addressing mode that the constraint wants. Also, this may take
  6919. // an additional register for the computation and we don't want that
  6920. // either.
  6921. // If the operand is a float, integer, or vector constant, spill to a
  6922. // constant pool entry to get its address.
  6923. const Value *OpVal = OpInfo.CallOperandVal;
  6924. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6925. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6926. OpInfo.CallOperand = DAG.getConstantPool(
  6927. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6928. return Chain;
  6929. }
  6930. // Otherwise, create a stack slot and emit a store to it before the asm.
  6931. Type *Ty = OpVal->getType();
  6932. auto &DL = DAG.getDataLayout();
  6933. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6934. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6935. MachineFunction &MF = DAG.getMachineFunction();
  6936. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6937. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6938. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6939. MachinePointerInfo::getFixedStack(MF, SSFI),
  6940. TLI.getMemValueType(DL, Ty));
  6941. OpInfo.CallOperand = StackSlot;
  6942. return Chain;
  6943. }
  6944. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6945. /// specified operand. We prefer to assign virtual registers, to allow the
  6946. /// register allocator to handle the assignment process. However, if the asm
  6947. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6948. /// allocation. This produces generally horrible, but correct, code.
  6949. ///
  6950. /// OpInfo describes the operand
  6951. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6952. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6953. SDISelAsmOperandInfo &OpInfo,
  6954. SDISelAsmOperandInfo &RefOpInfo) {
  6955. LLVMContext &Context = *DAG.getContext();
  6956. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6957. MachineFunction &MF = DAG.getMachineFunction();
  6958. SmallVector<unsigned, 4> Regs;
  6959. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6960. // No work to do for memory operations.
  6961. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6962. return;
  6963. // If this is a constraint for a single physreg, or a constraint for a
  6964. // register class, find it.
  6965. unsigned AssignedReg;
  6966. const TargetRegisterClass *RC;
  6967. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6968. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6969. // RC is unset only on failure. Return immediately.
  6970. if (!RC)
  6971. return;
  6972. // Get the actual register value type. This is important, because the user
  6973. // may have asked for (e.g.) the AX register in i32 type. We need to
  6974. // remember that AX is actually i16 to get the right extension.
  6975. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6976. if (OpInfo.ConstraintVT != MVT::Other) {
  6977. // If this is an FP operand in an integer register (or visa versa), or more
  6978. // generally if the operand value disagrees with the register class we plan
  6979. // to stick it in, fix the operand type.
  6980. //
  6981. // If this is an input value, the bitcast to the new type is done now.
  6982. // Bitcast for output value is done at the end of visitInlineAsm().
  6983. if ((OpInfo.Type == InlineAsm::isOutput ||
  6984. OpInfo.Type == InlineAsm::isInput) &&
  6985. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  6986. // Try to convert to the first EVT that the reg class contains. If the
  6987. // types are identical size, use a bitcast to convert (e.g. two differing
  6988. // vector types). Note: output bitcast is done at the end of
  6989. // visitInlineAsm().
  6990. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  6991. // Exclude indirect inputs while they are unsupported because the code
  6992. // to perform the load is missing and thus OpInfo.CallOperand still
  6993. // refers to the input address rather than the pointed-to value.
  6994. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  6995. OpInfo.CallOperand =
  6996. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6997. OpInfo.ConstraintVT = RegVT;
  6998. // If the operand is an FP value and we want it in integer registers,
  6999. // use the corresponding integer type. This turns an f64 value into
  7000. // i64, which can be passed with two i32 values on a 32-bit machine.
  7001. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  7002. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  7003. if (OpInfo.Type == InlineAsm::isInput)
  7004. OpInfo.CallOperand =
  7005. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  7006. OpInfo.ConstraintVT = VT;
  7007. }
  7008. }
  7009. }
  7010. // No need to allocate a matching input constraint since the constraint it's
  7011. // matching to has already been allocated.
  7012. if (OpInfo.isMatchingInputConstraint())
  7013. return;
  7014. EVT ValueVT = OpInfo.ConstraintVT;
  7015. if (OpInfo.ConstraintVT == MVT::Other)
  7016. ValueVT = RegVT;
  7017. // Initialize NumRegs.
  7018. unsigned NumRegs = 1;
  7019. if (OpInfo.ConstraintVT != MVT::Other)
  7020. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  7021. // If this is a constraint for a specific physical register, like {r17},
  7022. // assign it now.
  7023. // If this associated to a specific register, initialize iterator to correct
  7024. // place. If virtual, make sure we have enough registers
  7025. // Initialize iterator if necessary
  7026. TargetRegisterClass::iterator I = RC->begin();
  7027. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  7028. // Do not check for single registers.
  7029. if (AssignedReg) {
  7030. for (; *I != AssignedReg; ++I)
  7031. assert(I != RC->end() && "AssignedReg should be member of RC");
  7032. }
  7033. for (; NumRegs; --NumRegs, ++I) {
  7034. assert(I != RC->end() && "Ran out of registers to allocate!");
  7035. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  7036. Regs.push_back(R);
  7037. }
  7038. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  7039. }
  7040. static unsigned
  7041. findMatchingInlineAsmOperand(unsigned OperandNo,
  7042. const std::vector<SDValue> &AsmNodeOperands) {
  7043. // Scan until we find the definition we already emitted of this operand.
  7044. unsigned CurOp = InlineAsm::Op_FirstOperand;
  7045. for (; OperandNo; --OperandNo) {
  7046. // Advance to the next operand.
  7047. unsigned OpFlag =
  7048. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7049. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7050. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7051. InlineAsm::isMemKind(OpFlag)) &&
  7052. "Skipped past definitions?");
  7053. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7054. }
  7055. return CurOp;
  7056. }
  7057. namespace {
  7058. class ExtraFlags {
  7059. unsigned Flags = 0;
  7060. public:
  7061. explicit ExtraFlags(ImmutableCallSite CS) {
  7062. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7063. if (IA->hasSideEffects())
  7064. Flags |= InlineAsm::Extra_HasSideEffects;
  7065. if (IA->isAlignStack())
  7066. Flags |= InlineAsm::Extra_IsAlignStack;
  7067. if (CS.isConvergent())
  7068. Flags |= InlineAsm::Extra_IsConvergent;
  7069. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7070. }
  7071. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7072. // Ideally, we would only check against memory constraints. However, the
  7073. // meaning of an Other constraint can be target-specific and we can't easily
  7074. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7075. // for Other constraints as well.
  7076. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7077. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7078. if (OpInfo.Type == InlineAsm::isInput)
  7079. Flags |= InlineAsm::Extra_MayLoad;
  7080. else if (OpInfo.Type == InlineAsm::isOutput)
  7081. Flags |= InlineAsm::Extra_MayStore;
  7082. else if (OpInfo.Type == InlineAsm::isClobber)
  7083. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7084. }
  7085. }
  7086. unsigned get() const { return Flags; }
  7087. };
  7088. } // end anonymous namespace
  7089. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7090. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  7091. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7092. /// ConstraintOperands - Information about all of the constraints.
  7093. SDISelAsmOperandInfoVector ConstraintOperands;
  7094. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7095. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7096. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  7097. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7098. // AsmDialect, MayLoad, MayStore).
  7099. bool HasSideEffect = IA->hasSideEffects();
  7100. ExtraFlags ExtraInfo(CS);
  7101. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7102. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7103. for (auto &T : TargetConstraints) {
  7104. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7105. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7106. // Compute the value type for each operand.
  7107. if (OpInfo.Type == InlineAsm::isInput ||
  7108. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  7109. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  7110. // Process the call argument. BasicBlocks are labels, currently appearing
  7111. // only in asm's.
  7112. const Instruction *I = CS.getInstruction();
  7113. if (isa<CallBrInst>(I) &&
  7114. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  7115. cast<CallBrInst>(I)->getNumIndirectDests())) {
  7116. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  7117. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7118. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7119. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7120. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7121. } else {
  7122. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7123. }
  7124. OpInfo.ConstraintVT =
  7125. OpInfo
  7126. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  7127. .getSimpleVT();
  7128. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7129. // The return value of the call is this value. As such, there is no
  7130. // corresponding argument.
  7131. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7132. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7133. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7134. DAG.getDataLayout(), STy->getElementType(ResNo));
  7135. } else {
  7136. assert(ResNo == 0 && "Asm only has one result!");
  7137. OpInfo.ConstraintVT =
  7138. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7139. }
  7140. ++ResNo;
  7141. } else {
  7142. OpInfo.ConstraintVT = MVT::Other;
  7143. }
  7144. if (!HasSideEffect)
  7145. HasSideEffect = OpInfo.hasMemory(TLI);
  7146. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7147. // FIXME: Could we compute this on OpInfo rather than T?
  7148. // Compute the constraint code and ConstraintType to use.
  7149. TLI.ComputeConstraintToUse(T, SDValue());
  7150. if (T.ConstraintType == TargetLowering::C_Immediate &&
  7151. OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
  7152. // We've delayed emitting a diagnostic like the "n" constraint because
  7153. // inlining could cause an integer showing up.
  7154. return emitInlineAsmError(
  7155. CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
  7156. "integer constant expression");
  7157. ExtraInfo.update(T);
  7158. }
  7159. // We won't need to flush pending loads if this asm doesn't touch
  7160. // memory and is nonvolatile.
  7161. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7162. bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
  7163. if (IsCallBr) {
  7164. // If this is a callbr we need to flush pending exports since inlineasm_br
  7165. // is a terminator. We need to do this before nodes are glued to
  7166. // the inlineasm_br node.
  7167. Chain = getControlRoot();
  7168. }
  7169. // Second pass over the constraints: compute which constraint option to use.
  7170. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7171. // If this is an output operand with a matching input operand, look up the
  7172. // matching input. If their types mismatch, e.g. one is an integer, the
  7173. // other is floating point, or their sizes are different, flag it as an
  7174. // error.
  7175. if (OpInfo.hasMatchingInput()) {
  7176. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7177. patchMatchingInput(OpInfo, Input, DAG);
  7178. }
  7179. // Compute the constraint code and ConstraintType to use.
  7180. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7181. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7182. OpInfo.Type == InlineAsm::isClobber)
  7183. continue;
  7184. // If this is a memory input, and if the operand is not indirect, do what we
  7185. // need to provide an address for the memory input.
  7186. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7187. !OpInfo.isIndirect) {
  7188. assert((OpInfo.isMultipleAlternative ||
  7189. (OpInfo.Type == InlineAsm::isInput)) &&
  7190. "Can only indirectify direct input operands!");
  7191. // Memory operands really want the address of the value.
  7192. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7193. // There is no longer a Value* corresponding to this operand.
  7194. OpInfo.CallOperandVal = nullptr;
  7195. // It is now an indirect operand.
  7196. OpInfo.isIndirect = true;
  7197. }
  7198. }
  7199. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7200. std::vector<SDValue> AsmNodeOperands;
  7201. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7202. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7203. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7204. // If we have a !srcloc metadata node associated with it, we want to attach
  7205. // this to the ultimately generated inline asm machineinstr. To do this, we
  7206. // pass in the third operand as this (potentially null) inline asm MDNode.
  7207. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7208. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7209. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7210. // bits as operand 3.
  7211. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7212. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7213. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7214. // this, assign virtual and physical registers for inputs and otput.
  7215. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7216. // Assign Registers.
  7217. SDISelAsmOperandInfo &RefOpInfo =
  7218. OpInfo.isMatchingInputConstraint()
  7219. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7220. : OpInfo;
  7221. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7222. switch (OpInfo.Type) {
  7223. case InlineAsm::isOutput:
  7224. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7225. ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7226. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7227. OpInfo.isIndirect)) {
  7228. unsigned ConstraintID =
  7229. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7230. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7231. "Failed to convert memory constraint code to constraint id.");
  7232. // Add information to the INLINEASM node to know about this output.
  7233. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7234. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7235. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7236. MVT::i32));
  7237. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7238. break;
  7239. } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7240. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7241. !OpInfo.isIndirect) ||
  7242. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7243. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7244. // Otherwise, this outputs to a register (directly for C_Register /
  7245. // C_RegisterClass, and a target-defined fashion for
  7246. // C_Immediate/C_Other). Find a register that we can use.
  7247. if (OpInfo.AssignedRegs.Regs.empty()) {
  7248. emitInlineAsmError(
  7249. CS, "couldn't allocate output register for constraint '" +
  7250. Twine(OpInfo.ConstraintCode) + "'");
  7251. return;
  7252. }
  7253. // Add information to the INLINEASM node to know that this register is
  7254. // set.
  7255. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7256. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7257. : InlineAsm::Kind_RegDef,
  7258. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7259. }
  7260. break;
  7261. case InlineAsm::isInput: {
  7262. SDValue InOperandVal = OpInfo.CallOperand;
  7263. if (OpInfo.isMatchingInputConstraint()) {
  7264. // If this is required to match an output register we have already set,
  7265. // just use its register.
  7266. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7267. AsmNodeOperands);
  7268. unsigned OpFlag =
  7269. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7270. if (InlineAsm::isRegDefKind(OpFlag) ||
  7271. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7272. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7273. if (OpInfo.isIndirect) {
  7274. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7275. emitInlineAsmError(CS, "inline asm not supported yet:"
  7276. " don't know how to handle tied "
  7277. "indirect register inputs");
  7278. return;
  7279. }
  7280. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7281. SmallVector<unsigned, 4> Regs;
  7282. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7283. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7284. MachineRegisterInfo &RegInfo =
  7285. DAG.getMachineFunction().getRegInfo();
  7286. for (unsigned i = 0; i != NumRegs; ++i)
  7287. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7288. } else {
  7289. emitInlineAsmError(CS, "inline asm error: This value type register "
  7290. "class is not natively supported!");
  7291. return;
  7292. }
  7293. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7294. SDLoc dl = getCurSDLoc();
  7295. // Use the produced MatchedRegs object to
  7296. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7297. CS.getInstruction());
  7298. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7299. true, OpInfo.getMatchedOperand(), dl,
  7300. DAG, AsmNodeOperands);
  7301. break;
  7302. }
  7303. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7304. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7305. "Unexpected number of operands");
  7306. // Add information to the INLINEASM node to know about this input.
  7307. // See InlineAsm.h isUseOperandTiedToDef.
  7308. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7309. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7310. OpInfo.getMatchedOperand());
  7311. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7312. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7313. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7314. break;
  7315. }
  7316. // Treat indirect 'X' constraint as memory.
  7317. if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7318. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7319. OpInfo.isIndirect)
  7320. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7321. if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7322. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7323. std::vector<SDValue> Ops;
  7324. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7325. Ops, DAG);
  7326. if (Ops.empty()) {
  7327. if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
  7328. if (isa<ConstantSDNode>(InOperandVal)) {
  7329. emitInlineAsmError(CS, "value out of range for constraint '" +
  7330. Twine(OpInfo.ConstraintCode) + "'");
  7331. return;
  7332. }
  7333. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7334. Twine(OpInfo.ConstraintCode) + "'");
  7335. return;
  7336. }
  7337. // Add information to the INLINEASM node to know about this input.
  7338. unsigned ResOpType =
  7339. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7340. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7341. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7342. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7343. break;
  7344. }
  7345. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7346. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7347. assert(InOperandVal.getValueType() ==
  7348. TLI.getPointerTy(DAG.getDataLayout()) &&
  7349. "Memory operands expect pointer values");
  7350. unsigned ConstraintID =
  7351. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7352. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7353. "Failed to convert memory constraint code to constraint id.");
  7354. // Add information to the INLINEASM node to know about this input.
  7355. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7356. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7357. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7358. getCurSDLoc(),
  7359. MVT::i32));
  7360. AsmNodeOperands.push_back(InOperandVal);
  7361. break;
  7362. }
  7363. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7364. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7365. OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
  7366. "Unknown constraint type!");
  7367. // TODO: Support this.
  7368. if (OpInfo.isIndirect) {
  7369. emitInlineAsmError(
  7370. CS, "Don't know how to handle indirect register inputs yet "
  7371. "for constraint '" +
  7372. Twine(OpInfo.ConstraintCode) + "'");
  7373. return;
  7374. }
  7375. // Copy the input into the appropriate registers.
  7376. if (OpInfo.AssignedRegs.Regs.empty()) {
  7377. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7378. Twine(OpInfo.ConstraintCode) + "'");
  7379. return;
  7380. }
  7381. SDLoc dl = getCurSDLoc();
  7382. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7383. Chain, &Flag, CS.getInstruction());
  7384. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7385. dl, DAG, AsmNodeOperands);
  7386. break;
  7387. }
  7388. case InlineAsm::isClobber:
  7389. // Add the clobbered value to the operand list, so that the register
  7390. // allocator is aware that the physreg got clobbered.
  7391. if (!OpInfo.AssignedRegs.Regs.empty())
  7392. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7393. false, 0, getCurSDLoc(), DAG,
  7394. AsmNodeOperands);
  7395. break;
  7396. }
  7397. }
  7398. // Finish up input operands. Set the input chain and add the flag last.
  7399. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7400. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7401. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7402. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7403. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7404. Flag = Chain.getValue(1);
  7405. // Do additional work to generate outputs.
  7406. SmallVector<EVT, 1> ResultVTs;
  7407. SmallVector<SDValue, 1> ResultValues;
  7408. SmallVector<SDValue, 8> OutChains;
  7409. llvm::Type *CSResultType = CS.getType();
  7410. ArrayRef<Type *> ResultTypes;
  7411. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7412. ResultTypes = StructResult->elements();
  7413. else if (!CSResultType->isVoidTy())
  7414. ResultTypes = makeArrayRef(CSResultType);
  7415. auto CurResultType = ResultTypes.begin();
  7416. auto handleRegAssign = [&](SDValue V) {
  7417. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7418. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7419. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7420. ++CurResultType;
  7421. // If the type of the inline asm call site return value is different but has
  7422. // same size as the type of the asm output bitcast it. One example of this
  7423. // is for vectors with different width / number of elements. This can
  7424. // happen for register classes that can contain multiple different value
  7425. // types. The preg or vreg allocated may not have the same VT as was
  7426. // expected.
  7427. //
  7428. // This can also happen for a return value that disagrees with the register
  7429. // class it is put in, eg. a double in a general-purpose register on a
  7430. // 32-bit machine.
  7431. if (ResultVT != V.getValueType() &&
  7432. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7433. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7434. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7435. V.getValueType().isInteger()) {
  7436. // If a result value was tied to an input value, the computed result
  7437. // may have a wider width than the expected result. Extract the
  7438. // relevant portion.
  7439. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7440. }
  7441. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7442. ResultVTs.push_back(ResultVT);
  7443. ResultValues.push_back(V);
  7444. };
  7445. // Deal with output operands.
  7446. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7447. if (OpInfo.Type == InlineAsm::isOutput) {
  7448. SDValue Val;
  7449. // Skip trivial output operands.
  7450. if (OpInfo.AssignedRegs.Regs.empty())
  7451. continue;
  7452. switch (OpInfo.ConstraintType) {
  7453. case TargetLowering::C_Register:
  7454. case TargetLowering::C_RegisterClass:
  7455. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7456. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7457. break;
  7458. case TargetLowering::C_Immediate:
  7459. case TargetLowering::C_Other:
  7460. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7461. OpInfo, DAG);
  7462. break;
  7463. case TargetLowering::C_Memory:
  7464. break; // Already handled.
  7465. case TargetLowering::C_Unknown:
  7466. assert(false && "Unexpected unknown constraint");
  7467. }
  7468. // Indirect output manifest as stores. Record output chains.
  7469. if (OpInfo.isIndirect) {
  7470. const Value *Ptr = OpInfo.CallOperandVal;
  7471. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7472. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7473. MachinePointerInfo(Ptr));
  7474. OutChains.push_back(Store);
  7475. } else {
  7476. // generate CopyFromRegs to associated registers.
  7477. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7478. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7479. for (const SDValue &V : Val->op_values())
  7480. handleRegAssign(V);
  7481. } else
  7482. handleRegAssign(Val);
  7483. }
  7484. }
  7485. }
  7486. // Set results.
  7487. if (!ResultValues.empty()) {
  7488. assert(CurResultType == ResultTypes.end() &&
  7489. "Mismatch in number of ResultTypes");
  7490. assert(ResultValues.size() == ResultTypes.size() &&
  7491. "Mismatch in number of output operands in asm result");
  7492. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7493. DAG.getVTList(ResultVTs), ResultValues);
  7494. setValue(CS.getInstruction(), V);
  7495. }
  7496. // Collect store chains.
  7497. if (!OutChains.empty())
  7498. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7499. // Only Update Root if inline assembly has a memory effect.
  7500. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
  7501. DAG.setRoot(Chain);
  7502. }
  7503. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7504. const Twine &Message) {
  7505. LLVMContext &Ctx = *DAG.getContext();
  7506. Ctx.emitError(CS.getInstruction(), Message);
  7507. // Make sure we leave the DAG in a valid state
  7508. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7509. SmallVector<EVT, 1> ValueVTs;
  7510. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7511. if (ValueVTs.empty())
  7512. return;
  7513. SmallVector<SDValue, 1> Ops;
  7514. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7515. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7516. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7517. }
  7518. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7519. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7520. MVT::Other, getRoot(),
  7521. getValue(I.getArgOperand(0)),
  7522. DAG.getSrcValue(I.getArgOperand(0))));
  7523. }
  7524. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7525. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7526. const DataLayout &DL = DAG.getDataLayout();
  7527. SDValue V = DAG.getVAArg(
  7528. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  7529. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  7530. DL.getABITypeAlignment(I.getType()));
  7531. DAG.setRoot(V.getValue(1));
  7532. if (I.getType()->isPointerTy())
  7533. V = DAG.getPtrExtOrTrunc(
  7534. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  7535. setValue(&I, V);
  7536. }
  7537. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7538. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7539. MVT::Other, getRoot(),
  7540. getValue(I.getArgOperand(0)),
  7541. DAG.getSrcValue(I.getArgOperand(0))));
  7542. }
  7543. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7544. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7545. MVT::Other, getRoot(),
  7546. getValue(I.getArgOperand(0)),
  7547. getValue(I.getArgOperand(1)),
  7548. DAG.getSrcValue(I.getArgOperand(0)),
  7549. DAG.getSrcValue(I.getArgOperand(1))));
  7550. }
  7551. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7552. const Instruction &I,
  7553. SDValue Op) {
  7554. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7555. if (!Range)
  7556. return Op;
  7557. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7558. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7559. return Op;
  7560. APInt Lo = CR.getUnsignedMin();
  7561. if (!Lo.isMinValue())
  7562. return Op;
  7563. APInt Hi = CR.getUnsignedMax();
  7564. unsigned Bits = std::max(Hi.getActiveBits(),
  7565. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7566. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7567. SDLoc SL = getCurSDLoc();
  7568. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7569. DAG.getValueType(SmallVT));
  7570. unsigned NumVals = Op.getNode()->getNumValues();
  7571. if (NumVals == 1)
  7572. return ZExt;
  7573. SmallVector<SDValue, 4> Ops;
  7574. Ops.push_back(ZExt);
  7575. for (unsigned I = 1; I != NumVals; ++I)
  7576. Ops.push_back(Op.getValue(I));
  7577. return DAG.getMergeValues(Ops, SL);
  7578. }
  7579. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7580. /// the call being lowered.
  7581. ///
  7582. /// This is a helper for lowering intrinsics that follow a target calling
  7583. /// convention or require stack pointer adjustment. Only a subset of the
  7584. /// intrinsic's operands need to participate in the calling convention.
  7585. void SelectionDAGBuilder::populateCallLoweringInfo(
  7586. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7587. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7588. bool IsPatchPoint) {
  7589. TargetLowering::ArgListTy Args;
  7590. Args.reserve(NumArgs);
  7591. // Populate the argument list.
  7592. // Attributes for args start at offset 1, after the return attribute.
  7593. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7594. ArgI != ArgE; ++ArgI) {
  7595. const Value *V = Call->getOperand(ArgI);
  7596. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7597. TargetLowering::ArgListEntry Entry;
  7598. Entry.Node = getValue(V);
  7599. Entry.Ty = V->getType();
  7600. Entry.setAttributes(Call, ArgI);
  7601. Args.push_back(Entry);
  7602. }
  7603. CLI.setDebugLoc(getCurSDLoc())
  7604. .setChain(getRoot())
  7605. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7606. .setDiscardResult(Call->use_empty())
  7607. .setIsPatchPoint(IsPatchPoint);
  7608. }
  7609. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7610. /// or patchpoint target node's operand list.
  7611. ///
  7612. /// Constants are converted to TargetConstants purely as an optimization to
  7613. /// avoid constant materialization and register allocation.
  7614. ///
  7615. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7616. /// generate addess computation nodes, and so FinalizeISel can convert the
  7617. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7618. /// address materialization and register allocation, but may also be required
  7619. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7620. /// alloca in the entry block, then the runtime may assume that the alloca's
  7621. /// StackMap location can be read immediately after compilation and that the
  7622. /// location is valid at any point during execution (this is similar to the
  7623. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7624. /// only available in a register, then the runtime would need to trap when
  7625. /// execution reaches the StackMap in order to read the alloca's location.
  7626. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7627. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7628. SelectionDAGBuilder &Builder) {
  7629. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7630. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7631. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7632. Ops.push_back(
  7633. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7634. Ops.push_back(
  7635. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7636. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7637. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7638. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7639. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7640. } else
  7641. Ops.push_back(OpVal);
  7642. }
  7643. }
  7644. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7645. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7646. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7647. // [live variables...])
  7648. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7649. SDValue Chain, InFlag, Callee, NullPtr;
  7650. SmallVector<SDValue, 32> Ops;
  7651. SDLoc DL = getCurSDLoc();
  7652. Callee = getValue(CI.getCalledValue());
  7653. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7654. // The stackmap intrinsic only records the live variables (the arguemnts
  7655. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7656. // intrinsic, this won't be lowered to a function call. This means we don't
  7657. // have to worry about calling conventions and target specific lowering code.
  7658. // Instead we perform the call lowering right here.
  7659. //
  7660. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7661. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7662. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7663. //
  7664. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7665. InFlag = Chain.getValue(1);
  7666. // Add the <id> and <numBytes> constants.
  7667. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7668. Ops.push_back(DAG.getTargetConstant(
  7669. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7670. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7671. Ops.push_back(DAG.getTargetConstant(
  7672. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7673. MVT::i32));
  7674. // Push live variables for the stack map.
  7675. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7676. // We are not pushing any register mask info here on the operands list,
  7677. // because the stackmap doesn't clobber anything.
  7678. // Push the chain and the glue flag.
  7679. Ops.push_back(Chain);
  7680. Ops.push_back(InFlag);
  7681. // Create the STACKMAP node.
  7682. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7683. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7684. Chain = SDValue(SM, 0);
  7685. InFlag = Chain.getValue(1);
  7686. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7687. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7688. // Set the root to the target-lowered call chain.
  7689. DAG.setRoot(Chain);
  7690. // Inform the Frame Information that we have a stackmap in this function.
  7691. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7692. }
  7693. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7694. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7695. const BasicBlock *EHPadBB) {
  7696. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7697. // i32 <numBytes>,
  7698. // i8* <target>,
  7699. // i32 <numArgs>,
  7700. // [Args...],
  7701. // [live variables...])
  7702. CallingConv::ID CC = CS.getCallingConv();
  7703. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7704. bool HasDef = !CS->getType()->isVoidTy();
  7705. SDLoc dl = getCurSDLoc();
  7706. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7707. // Handle immediate and symbolic callees.
  7708. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7709. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7710. /*isTarget=*/true);
  7711. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7712. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7713. SDLoc(SymbolicCallee),
  7714. SymbolicCallee->getValueType(0));
  7715. // Get the real number of arguments participating in the call <numArgs>
  7716. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7717. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7718. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7719. // Intrinsics include all meta-operands up to but not including CC.
  7720. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7721. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7722. "Not enough arguments provided to the patchpoint intrinsic");
  7723. // For AnyRegCC the arguments are lowered later on manually.
  7724. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7725. Type *ReturnTy =
  7726. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7727. TargetLowering::CallLoweringInfo CLI(DAG);
  7728. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7729. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7730. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7731. SDNode *CallEnd = Result.second.getNode();
  7732. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7733. CallEnd = CallEnd->getOperand(0).getNode();
  7734. /// Get a call instruction from the call sequence chain.
  7735. /// Tail calls are not allowed.
  7736. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7737. "Expected a callseq node.");
  7738. SDNode *Call = CallEnd->getOperand(0).getNode();
  7739. bool HasGlue = Call->getGluedNode();
  7740. // Replace the target specific call node with the patchable intrinsic.
  7741. SmallVector<SDValue, 8> Ops;
  7742. // Add the <id> and <numBytes> constants.
  7743. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7744. Ops.push_back(DAG.getTargetConstant(
  7745. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7746. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7747. Ops.push_back(DAG.getTargetConstant(
  7748. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7749. MVT::i32));
  7750. // Add the callee.
  7751. Ops.push_back(Callee);
  7752. // Adjust <numArgs> to account for any arguments that have been passed on the
  7753. // stack instead.
  7754. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7755. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7756. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7757. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7758. // Add the calling convention
  7759. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7760. // Add the arguments we omitted previously. The register allocator should
  7761. // place these in any free register.
  7762. if (IsAnyRegCC)
  7763. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7764. Ops.push_back(getValue(CS.getArgument(i)));
  7765. // Push the arguments from the call instruction up to the register mask.
  7766. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7767. Ops.append(Call->op_begin() + 2, e);
  7768. // Push live variables for the stack map.
  7769. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7770. // Push the register mask info.
  7771. if (HasGlue)
  7772. Ops.push_back(*(Call->op_end()-2));
  7773. else
  7774. Ops.push_back(*(Call->op_end()-1));
  7775. // Push the chain (this is originally the first operand of the call, but
  7776. // becomes now the last or second to last operand).
  7777. Ops.push_back(*(Call->op_begin()));
  7778. // Push the glue flag (last operand).
  7779. if (HasGlue)
  7780. Ops.push_back(*(Call->op_end()-1));
  7781. SDVTList NodeTys;
  7782. if (IsAnyRegCC && HasDef) {
  7783. // Create the return types based on the intrinsic definition
  7784. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7785. SmallVector<EVT, 3> ValueVTs;
  7786. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7787. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7788. // There is always a chain and a glue type at the end
  7789. ValueVTs.push_back(MVT::Other);
  7790. ValueVTs.push_back(MVT::Glue);
  7791. NodeTys = DAG.getVTList(ValueVTs);
  7792. } else
  7793. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7794. // Replace the target specific call node with a PATCHPOINT node.
  7795. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7796. dl, NodeTys, Ops);
  7797. // Update the NodeMap.
  7798. if (HasDef) {
  7799. if (IsAnyRegCC)
  7800. setValue(CS.getInstruction(), SDValue(MN, 0));
  7801. else
  7802. setValue(CS.getInstruction(), Result.first);
  7803. }
  7804. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7805. // call sequence. Furthermore the location of the chain and glue can change
  7806. // when the AnyReg calling convention is used and the intrinsic returns a
  7807. // value.
  7808. if (IsAnyRegCC && HasDef) {
  7809. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7810. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7811. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7812. } else
  7813. DAG.ReplaceAllUsesWith(Call, MN);
  7814. DAG.DeleteNode(Call);
  7815. // Inform the Frame Information that we have a patchpoint in this function.
  7816. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7817. }
  7818. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7819. unsigned Intrinsic) {
  7820. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7821. SDValue Op1 = getValue(I.getArgOperand(0));
  7822. SDValue Op2;
  7823. if (I.getNumArgOperands() > 1)
  7824. Op2 = getValue(I.getArgOperand(1));
  7825. SDLoc dl = getCurSDLoc();
  7826. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7827. SDValue Res;
  7828. FastMathFlags FMF;
  7829. if (isa<FPMathOperator>(I))
  7830. FMF = I.getFastMathFlags();
  7831. switch (Intrinsic) {
  7832. case Intrinsic::experimental_vector_reduce_v2_fadd:
  7833. if (FMF.allowReassoc())
  7834. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  7835. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
  7836. else
  7837. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7838. break;
  7839. case Intrinsic::experimental_vector_reduce_v2_fmul:
  7840. if (FMF.allowReassoc())
  7841. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  7842. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
  7843. else
  7844. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7845. break;
  7846. case Intrinsic::experimental_vector_reduce_add:
  7847. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7848. break;
  7849. case Intrinsic::experimental_vector_reduce_mul:
  7850. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7851. break;
  7852. case Intrinsic::experimental_vector_reduce_and:
  7853. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7854. break;
  7855. case Intrinsic::experimental_vector_reduce_or:
  7856. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7857. break;
  7858. case Intrinsic::experimental_vector_reduce_xor:
  7859. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7860. break;
  7861. case Intrinsic::experimental_vector_reduce_smax:
  7862. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7863. break;
  7864. case Intrinsic::experimental_vector_reduce_smin:
  7865. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7866. break;
  7867. case Intrinsic::experimental_vector_reduce_umax:
  7868. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7869. break;
  7870. case Intrinsic::experimental_vector_reduce_umin:
  7871. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7872. break;
  7873. case Intrinsic::experimental_vector_reduce_fmax:
  7874. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7875. break;
  7876. case Intrinsic::experimental_vector_reduce_fmin:
  7877. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7878. break;
  7879. default:
  7880. llvm_unreachable("Unhandled vector reduce intrinsic");
  7881. }
  7882. setValue(&I, Res);
  7883. }
  7884. /// Returns an AttributeList representing the attributes applied to the return
  7885. /// value of the given call.
  7886. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7887. SmallVector<Attribute::AttrKind, 2> Attrs;
  7888. if (CLI.RetSExt)
  7889. Attrs.push_back(Attribute::SExt);
  7890. if (CLI.RetZExt)
  7891. Attrs.push_back(Attribute::ZExt);
  7892. if (CLI.IsInReg)
  7893. Attrs.push_back(Attribute::InReg);
  7894. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7895. Attrs);
  7896. }
  7897. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7898. /// implementation, which just calls LowerCall.
  7899. /// FIXME: When all targets are
  7900. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7901. std::pair<SDValue, SDValue>
  7902. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7903. // Handle the incoming return values from the call.
  7904. CLI.Ins.clear();
  7905. Type *OrigRetTy = CLI.RetTy;
  7906. SmallVector<EVT, 4> RetTys;
  7907. SmallVector<uint64_t, 4> Offsets;
  7908. auto &DL = CLI.DAG.getDataLayout();
  7909. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7910. if (CLI.IsPostTypeLegalization) {
  7911. // If we are lowering a libcall after legalization, split the return type.
  7912. SmallVector<EVT, 4> OldRetTys;
  7913. SmallVector<uint64_t, 4> OldOffsets;
  7914. RetTys.swap(OldRetTys);
  7915. Offsets.swap(OldOffsets);
  7916. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7917. EVT RetVT = OldRetTys[i];
  7918. uint64_t Offset = OldOffsets[i];
  7919. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7920. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7921. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7922. RetTys.append(NumRegs, RegisterVT);
  7923. for (unsigned j = 0; j != NumRegs; ++j)
  7924. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7925. }
  7926. }
  7927. SmallVector<ISD::OutputArg, 4> Outs;
  7928. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7929. bool CanLowerReturn =
  7930. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7931. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7932. SDValue DemoteStackSlot;
  7933. int DemoteStackIdx = -100;
  7934. if (!CanLowerReturn) {
  7935. // FIXME: equivalent assert?
  7936. // assert(!CS.hasInAllocaArgument() &&
  7937. // "sret demotion is incompatible with inalloca");
  7938. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7939. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7940. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7941. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7942. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7943. DL.getAllocaAddrSpace());
  7944. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7945. ArgListEntry Entry;
  7946. Entry.Node = DemoteStackSlot;
  7947. Entry.Ty = StackSlotPtrType;
  7948. Entry.IsSExt = false;
  7949. Entry.IsZExt = false;
  7950. Entry.IsInReg = false;
  7951. Entry.IsSRet = true;
  7952. Entry.IsNest = false;
  7953. Entry.IsByVal = false;
  7954. Entry.IsReturned = false;
  7955. Entry.IsSwiftSelf = false;
  7956. Entry.IsSwiftError = false;
  7957. Entry.Alignment = Align;
  7958. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7959. CLI.NumFixedArgs += 1;
  7960. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7961. // sret demotion isn't compatible with tail-calls, since the sret argument
  7962. // points into the callers stack frame.
  7963. CLI.IsTailCall = false;
  7964. } else {
  7965. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7966. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  7967. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7968. ISD::ArgFlagsTy Flags;
  7969. if (NeedsRegBlock) {
  7970. Flags.setInConsecutiveRegs();
  7971. if (I == RetTys.size() - 1)
  7972. Flags.setInConsecutiveRegsLast();
  7973. }
  7974. EVT VT = RetTys[I];
  7975. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7976. CLI.CallConv, VT);
  7977. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7978. CLI.CallConv, VT);
  7979. for (unsigned i = 0; i != NumRegs; ++i) {
  7980. ISD::InputArg MyFlags;
  7981. MyFlags.Flags = Flags;
  7982. MyFlags.VT = RegisterVT;
  7983. MyFlags.ArgVT = VT;
  7984. MyFlags.Used = CLI.IsReturnValueUsed;
  7985. if (CLI.RetTy->isPointerTy()) {
  7986. MyFlags.Flags.setPointer();
  7987. MyFlags.Flags.setPointerAddrSpace(
  7988. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  7989. }
  7990. if (CLI.RetSExt)
  7991. MyFlags.Flags.setSExt();
  7992. if (CLI.RetZExt)
  7993. MyFlags.Flags.setZExt();
  7994. if (CLI.IsInReg)
  7995. MyFlags.Flags.setInReg();
  7996. CLI.Ins.push_back(MyFlags);
  7997. }
  7998. }
  7999. }
  8000. // We push in swifterror return as the last element of CLI.Ins.
  8001. ArgListTy &Args = CLI.getArgs();
  8002. if (supportSwiftError()) {
  8003. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8004. if (Args[i].IsSwiftError) {
  8005. ISD::InputArg MyFlags;
  8006. MyFlags.VT = getPointerTy(DL);
  8007. MyFlags.ArgVT = EVT(getPointerTy(DL));
  8008. MyFlags.Flags.setSwiftError();
  8009. CLI.Ins.push_back(MyFlags);
  8010. }
  8011. }
  8012. }
  8013. // Handle all of the outgoing arguments.
  8014. CLI.Outs.clear();
  8015. CLI.OutVals.clear();
  8016. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8017. SmallVector<EVT, 4> ValueVTs;
  8018. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  8019. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  8020. Type *FinalType = Args[i].Ty;
  8021. if (Args[i].IsByVal)
  8022. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  8023. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8024. FinalType, CLI.CallConv, CLI.IsVarArg);
  8025. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  8026. ++Value) {
  8027. EVT VT = ValueVTs[Value];
  8028. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  8029. SDValue Op = SDValue(Args[i].Node.getNode(),
  8030. Args[i].Node.getResNo() + Value);
  8031. ISD::ArgFlagsTy Flags;
  8032. // Certain targets (such as MIPS), may have a different ABI alignment
  8033. // for a type depending on the context. Give the target a chance to
  8034. // specify the alignment it wants.
  8035. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  8036. if (Args[i].Ty->isPointerTy()) {
  8037. Flags.setPointer();
  8038. Flags.setPointerAddrSpace(
  8039. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  8040. }
  8041. if (Args[i].IsZExt)
  8042. Flags.setZExt();
  8043. if (Args[i].IsSExt)
  8044. Flags.setSExt();
  8045. if (Args[i].IsInReg) {
  8046. // If we are using vectorcall calling convention, a structure that is
  8047. // passed InReg - is surely an HVA
  8048. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  8049. isa<StructType>(FinalType)) {
  8050. // The first value of a structure is marked
  8051. if (0 == Value)
  8052. Flags.setHvaStart();
  8053. Flags.setHva();
  8054. }
  8055. // Set InReg Flag
  8056. Flags.setInReg();
  8057. }
  8058. if (Args[i].IsSRet)
  8059. Flags.setSRet();
  8060. if (Args[i].IsSwiftSelf)
  8061. Flags.setSwiftSelf();
  8062. if (Args[i].IsSwiftError)
  8063. Flags.setSwiftError();
  8064. if (Args[i].IsByVal)
  8065. Flags.setByVal();
  8066. if (Args[i].IsInAlloca) {
  8067. Flags.setInAlloca();
  8068. // Set the byval flag for CCAssignFn callbacks that don't know about
  8069. // inalloca. This way we can know how many bytes we should've allocated
  8070. // and how many bytes a callee cleanup function will pop. If we port
  8071. // inalloca to more targets, we'll have to add custom inalloca handling
  8072. // in the various CC lowering callbacks.
  8073. Flags.setByVal();
  8074. }
  8075. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  8076. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  8077. Type *ElementTy = Ty->getElementType();
  8078. unsigned FrameSize = DL.getTypeAllocSize(
  8079. Args[i].ByValType ? Args[i].ByValType : ElementTy);
  8080. Flags.setByValSize(FrameSize);
  8081. // info is not there but there are cases it cannot get right.
  8082. unsigned FrameAlign;
  8083. if (Args[i].Alignment)
  8084. FrameAlign = Args[i].Alignment;
  8085. else
  8086. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  8087. Flags.setByValAlign(FrameAlign);
  8088. }
  8089. if (Args[i].IsNest)
  8090. Flags.setNest();
  8091. if (NeedsRegBlock)
  8092. Flags.setInConsecutiveRegs();
  8093. Flags.setOrigAlign(OriginalAlignment);
  8094. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8095. CLI.CallConv, VT);
  8096. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8097. CLI.CallConv, VT);
  8098. SmallVector<SDValue, 4> Parts(NumParts);
  8099. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8100. if (Args[i].IsSExt)
  8101. ExtendKind = ISD::SIGN_EXTEND;
  8102. else if (Args[i].IsZExt)
  8103. ExtendKind = ISD::ZERO_EXTEND;
  8104. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8105. // for now.
  8106. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8107. CanLowerReturn) {
  8108. assert((CLI.RetTy == Args[i].Ty ||
  8109. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8110. CLI.RetTy->getPointerAddressSpace() ==
  8111. Args[i].Ty->getPointerAddressSpace())) &&
  8112. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8113. // Before passing 'returned' to the target lowering code, ensure that
  8114. // either the register MVT and the actual EVT are the same size or that
  8115. // the return value and argument are extended in the same way; in these
  8116. // cases it's safe to pass the argument register value unchanged as the
  8117. // return register value (although it's at the target's option whether
  8118. // to do so)
  8119. // TODO: allow code generation to take advantage of partially preserved
  8120. // registers rather than clobbering the entire register when the
  8121. // parameter extension method is not compatible with the return
  8122. // extension method
  8123. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8124. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8125. CLI.RetZExt == Args[i].IsZExt))
  8126. Flags.setReturned();
  8127. }
  8128. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  8129. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  8130. for (unsigned j = 0; j != NumParts; ++j) {
  8131. // if it isn't first piece, alignment must be 1
  8132. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  8133. i < CLI.NumFixedArgs,
  8134. i, j*Parts[j].getValueType().getStoreSize());
  8135. if (NumParts > 1 && j == 0)
  8136. MyFlags.Flags.setSplit();
  8137. else if (j != 0) {
  8138. MyFlags.Flags.setOrigAlign(1);
  8139. if (j == NumParts - 1)
  8140. MyFlags.Flags.setSplitEnd();
  8141. }
  8142. CLI.Outs.push_back(MyFlags);
  8143. CLI.OutVals.push_back(Parts[j]);
  8144. }
  8145. if (NeedsRegBlock && Value == NumValues - 1)
  8146. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8147. }
  8148. }
  8149. SmallVector<SDValue, 4> InVals;
  8150. CLI.Chain = LowerCall(CLI, InVals);
  8151. // Update CLI.InVals to use outside of this function.
  8152. CLI.InVals = InVals;
  8153. // Verify that the target's LowerCall behaved as expected.
  8154. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8155. "LowerCall didn't return a valid chain!");
  8156. assert((!CLI.IsTailCall || InVals.empty()) &&
  8157. "LowerCall emitted a return value for a tail call!");
  8158. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8159. "LowerCall didn't emit the correct number of values!");
  8160. // For a tail call, the return value is merely live-out and there aren't
  8161. // any nodes in the DAG representing it. Return a special value to
  8162. // indicate that a tail call has been emitted and no more Instructions
  8163. // should be processed in the current block.
  8164. if (CLI.IsTailCall) {
  8165. CLI.DAG.setRoot(CLI.Chain);
  8166. return std::make_pair(SDValue(), SDValue());
  8167. }
  8168. #ifndef NDEBUG
  8169. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8170. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8171. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8172. "LowerCall emitted a value with the wrong type!");
  8173. }
  8174. #endif
  8175. SmallVector<SDValue, 4> ReturnValues;
  8176. if (!CanLowerReturn) {
  8177. // The instruction result is the result of loading from the
  8178. // hidden sret parameter.
  8179. SmallVector<EVT, 1> PVTs;
  8180. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8181. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8182. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8183. EVT PtrVT = PVTs[0];
  8184. unsigned NumValues = RetTys.size();
  8185. ReturnValues.resize(NumValues);
  8186. SmallVector<SDValue, 4> Chains(NumValues);
  8187. // An aggregate return value cannot wrap around the address space, so
  8188. // offsets to its parts don't wrap either.
  8189. SDNodeFlags Flags;
  8190. Flags.setNoUnsignedWrap(true);
  8191. for (unsigned i = 0; i < NumValues; ++i) {
  8192. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8193. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8194. PtrVT), Flags);
  8195. SDValue L = CLI.DAG.getLoad(
  8196. RetTys[i], CLI.DL, CLI.Chain, Add,
  8197. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8198. DemoteStackIdx, Offsets[i]),
  8199. /* Alignment = */ 1);
  8200. ReturnValues[i] = L;
  8201. Chains[i] = L.getValue(1);
  8202. }
  8203. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8204. } else {
  8205. // Collect the legal value parts into potentially illegal values
  8206. // that correspond to the original function's return values.
  8207. Optional<ISD::NodeType> AssertOp;
  8208. if (CLI.RetSExt)
  8209. AssertOp = ISD::AssertSext;
  8210. else if (CLI.RetZExt)
  8211. AssertOp = ISD::AssertZext;
  8212. unsigned CurReg = 0;
  8213. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8214. EVT VT = RetTys[I];
  8215. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8216. CLI.CallConv, VT);
  8217. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8218. CLI.CallConv, VT);
  8219. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8220. NumRegs, RegisterVT, VT, nullptr,
  8221. CLI.CallConv, AssertOp));
  8222. CurReg += NumRegs;
  8223. }
  8224. // For a function returning void, there is no return value. We can't create
  8225. // such a node, so we just return a null return value in that case. In
  8226. // that case, nothing will actually look at the value.
  8227. if (ReturnValues.empty())
  8228. return std::make_pair(SDValue(), CLI.Chain);
  8229. }
  8230. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8231. CLI.DAG.getVTList(RetTys), ReturnValues);
  8232. return std::make_pair(Res, CLI.Chain);
  8233. }
  8234. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8235. SmallVectorImpl<SDValue> &Results,
  8236. SelectionDAG &DAG) const {
  8237. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8238. Results.push_back(Res);
  8239. }
  8240. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8241. llvm_unreachable("LowerOperation not implemented for this target!");
  8242. }
  8243. void
  8244. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8245. SDValue Op = getNonRegisterValue(V);
  8246. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8247. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8248. "Copy from a reg to the same reg!");
  8249. assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
  8250. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8251. // If this is an InlineAsm we have to match the registers required, not the
  8252. // notional registers required by the type.
  8253. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8254. None); // This is not an ABI copy.
  8255. SDValue Chain = DAG.getEntryNode();
  8256. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8257. FuncInfo.PreferredExtendType.end())
  8258. ? ISD::ANY_EXTEND
  8259. : FuncInfo.PreferredExtendType[V];
  8260. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8261. PendingExports.push_back(Chain);
  8262. }
  8263. #include "llvm/CodeGen/SelectionDAGISel.h"
  8264. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8265. /// entry block, return true. This includes arguments used by switches, since
  8266. /// the switch may expand into multiple basic blocks.
  8267. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8268. // With FastISel active, we may be splitting blocks, so force creation
  8269. // of virtual registers for all non-dead arguments.
  8270. if (FastISel)
  8271. return A->use_empty();
  8272. const BasicBlock &Entry = A->getParent()->front();
  8273. for (const User *U : A->users())
  8274. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8275. return false; // Use not in entry block.
  8276. return true;
  8277. }
  8278. using ArgCopyElisionMapTy =
  8279. DenseMap<const Argument *,
  8280. std::pair<const AllocaInst *, const StoreInst *>>;
  8281. /// Scan the entry block of the function in FuncInfo for arguments that look
  8282. /// like copies into a local alloca. Record any copied arguments in
  8283. /// ArgCopyElisionCandidates.
  8284. static void
  8285. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8286. FunctionLoweringInfo *FuncInfo,
  8287. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8288. // Record the state of every static alloca used in the entry block. Argument
  8289. // allocas are all used in the entry block, so we need approximately as many
  8290. // entries as we have arguments.
  8291. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8292. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8293. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8294. StaticAllocas.reserve(NumArgs * 2);
  8295. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8296. if (!V)
  8297. return nullptr;
  8298. V = V->stripPointerCasts();
  8299. const auto *AI = dyn_cast<AllocaInst>(V);
  8300. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8301. return nullptr;
  8302. auto Iter = StaticAllocas.insert({AI, Unknown});
  8303. return &Iter.first->second;
  8304. };
  8305. // Look for stores of arguments to static allocas. Look through bitcasts and
  8306. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8307. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8308. // unanalyzed store might write it.
  8309. // FIXME: Handle structs initialized with multiple stores.
  8310. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8311. // Look for stores, and handle non-store uses conservatively.
  8312. const auto *SI = dyn_cast<StoreInst>(&I);
  8313. if (!SI) {
  8314. // We will look through cast uses, so ignore them completely.
  8315. if (I.isCast())
  8316. continue;
  8317. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8318. if (isa<DbgInfoIntrinsic>(I))
  8319. continue;
  8320. // This is an unknown instruction. Assume it escapes or writes to all
  8321. // static alloca operands.
  8322. for (const Use &U : I.operands()) {
  8323. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8324. *Info = StaticAllocaInfo::Clobbered;
  8325. }
  8326. continue;
  8327. }
  8328. // If the stored value is a static alloca, mark it as escaped.
  8329. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8330. *Info = StaticAllocaInfo::Clobbered;
  8331. // Check if the destination is a static alloca.
  8332. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8333. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8334. if (!Info)
  8335. continue;
  8336. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8337. // Skip allocas that have been initialized or clobbered.
  8338. if (*Info != StaticAllocaInfo::Unknown)
  8339. continue;
  8340. // Check if the stored value is an argument, and that this store fully
  8341. // initializes the alloca. Don't elide copies from the same argument twice.
  8342. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8343. const auto *Arg = dyn_cast<Argument>(Val);
  8344. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8345. Arg->getType()->isEmptyTy() ||
  8346. DL.getTypeStoreSize(Arg->getType()) !=
  8347. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8348. ArgCopyElisionCandidates.count(Arg)) {
  8349. *Info = StaticAllocaInfo::Clobbered;
  8350. continue;
  8351. }
  8352. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8353. << '\n');
  8354. // Mark this alloca and store for argument copy elision.
  8355. *Info = StaticAllocaInfo::Elidable;
  8356. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8357. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8358. // builds, which is useful, because -O0 builds have large entry blocks and
  8359. // many allocas.
  8360. if (ArgCopyElisionCandidates.size() == NumArgs)
  8361. break;
  8362. }
  8363. }
  8364. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8365. /// ArgVal is a load from a suitable fixed stack object.
  8366. static void tryToElideArgumentCopy(
  8367. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8368. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8369. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8370. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8371. SDValue ArgVal, bool &ArgHasUses) {
  8372. // Check if this is a load from a fixed stack object.
  8373. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8374. if (!LNode)
  8375. return;
  8376. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8377. if (!FINode)
  8378. return;
  8379. // Check that the fixed stack object is the right size and alignment.
  8380. // Look at the alignment that the user wrote on the alloca instead of looking
  8381. // at the stack object.
  8382. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8383. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8384. const AllocaInst *AI = ArgCopyIter->second.first;
  8385. int FixedIndex = FINode->getIndex();
  8386. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8387. int OldIndex = AllocaIndex;
  8388. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8389. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8390. LLVM_DEBUG(
  8391. dbgs() << " argument copy elision failed due to bad fixed stack "
  8392. "object size\n");
  8393. return;
  8394. }
  8395. unsigned RequiredAlignment = AI->getAlignment();
  8396. if (!RequiredAlignment) {
  8397. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8398. AI->getAllocatedType());
  8399. }
  8400. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8401. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8402. "greater than stack argument alignment ("
  8403. << RequiredAlignment << " vs "
  8404. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8405. return;
  8406. }
  8407. // Perform the elision. Delete the old stack object and replace its only use
  8408. // in the variable info map. Mark the stack object as mutable.
  8409. LLVM_DEBUG({
  8410. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8411. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8412. << '\n';
  8413. });
  8414. MFI.RemoveStackObject(OldIndex);
  8415. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8416. AllocaIndex = FixedIndex;
  8417. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8418. Chains.push_back(ArgVal.getValue(1));
  8419. // Avoid emitting code for the store implementing the copy.
  8420. const StoreInst *SI = ArgCopyIter->second.second;
  8421. ElidedArgCopyInstrs.insert(SI);
  8422. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8423. // if it is't used by anything other than the store.
  8424. for (const Value *U : Arg.users()) {
  8425. if (U != SI) {
  8426. ArgHasUses = true;
  8427. break;
  8428. }
  8429. }
  8430. }
  8431. void SelectionDAGISel::LowerArguments(const Function &F) {
  8432. SelectionDAG &DAG = SDB->DAG;
  8433. SDLoc dl = SDB->getCurSDLoc();
  8434. const DataLayout &DL = DAG.getDataLayout();
  8435. SmallVector<ISD::InputArg, 16> Ins;
  8436. if (!FuncInfo->CanLowerReturn) {
  8437. // Put in an sret pointer parameter before all the other parameters.
  8438. SmallVector<EVT, 1> ValueVTs;
  8439. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8440. F.getReturnType()->getPointerTo(
  8441. DAG.getDataLayout().getAllocaAddrSpace()),
  8442. ValueVTs);
  8443. // NOTE: Assuming that a pointer will never break down to more than one VT
  8444. // or one register.
  8445. ISD::ArgFlagsTy Flags;
  8446. Flags.setSRet();
  8447. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8448. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8449. ISD::InputArg::NoArgIndex, 0);
  8450. Ins.push_back(RetArg);
  8451. }
  8452. // Look for stores of arguments to static allocas. Mark such arguments with a
  8453. // flag to ask the target to give us the memory location of that argument if
  8454. // available.
  8455. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8456. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8457. // Set up the incoming argument description vector.
  8458. for (const Argument &Arg : F.args()) {
  8459. unsigned ArgNo = Arg.getArgNo();
  8460. SmallVector<EVT, 4> ValueVTs;
  8461. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8462. bool isArgValueUsed = !Arg.use_empty();
  8463. unsigned PartBase = 0;
  8464. Type *FinalType = Arg.getType();
  8465. if (Arg.hasAttribute(Attribute::ByVal))
  8466. FinalType = Arg.getParamByValType();
  8467. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8468. FinalType, F.getCallingConv(), F.isVarArg());
  8469. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8470. Value != NumValues; ++Value) {
  8471. EVT VT = ValueVTs[Value];
  8472. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8473. ISD::ArgFlagsTy Flags;
  8474. // Certain targets (such as MIPS), may have a different ABI alignment
  8475. // for a type depending on the context. Give the target a chance to
  8476. // specify the alignment it wants.
  8477. unsigned OriginalAlignment =
  8478. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8479. if (Arg.getType()->isPointerTy()) {
  8480. Flags.setPointer();
  8481. Flags.setPointerAddrSpace(
  8482. cast<PointerType>(Arg.getType())->getAddressSpace());
  8483. }
  8484. if (Arg.hasAttribute(Attribute::ZExt))
  8485. Flags.setZExt();
  8486. if (Arg.hasAttribute(Attribute::SExt))
  8487. Flags.setSExt();
  8488. if (Arg.hasAttribute(Attribute::InReg)) {
  8489. // If we are using vectorcall calling convention, a structure that is
  8490. // passed InReg - is surely an HVA
  8491. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8492. isa<StructType>(Arg.getType())) {
  8493. // The first value of a structure is marked
  8494. if (0 == Value)
  8495. Flags.setHvaStart();
  8496. Flags.setHva();
  8497. }
  8498. // Set InReg Flag
  8499. Flags.setInReg();
  8500. }
  8501. if (Arg.hasAttribute(Attribute::StructRet))
  8502. Flags.setSRet();
  8503. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8504. Flags.setSwiftSelf();
  8505. if (Arg.hasAttribute(Attribute::SwiftError))
  8506. Flags.setSwiftError();
  8507. if (Arg.hasAttribute(Attribute::ByVal))
  8508. Flags.setByVal();
  8509. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8510. Flags.setInAlloca();
  8511. // Set the byval flag for CCAssignFn callbacks that don't know about
  8512. // inalloca. This way we can know how many bytes we should've allocated
  8513. // and how many bytes a callee cleanup function will pop. If we port
  8514. // inalloca to more targets, we'll have to add custom inalloca handling
  8515. // in the various CC lowering callbacks.
  8516. Flags.setByVal();
  8517. }
  8518. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8519. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8520. if (ArgNo == 0)
  8521. Flags.setByVal();
  8522. }
  8523. if (Flags.isByVal() || Flags.isInAlloca()) {
  8524. Type *ElementTy = Arg.getParamByValType();
  8525. // For ByVal, size and alignment should be passed from FE. BE will
  8526. // guess if this info is not there but there are cases it cannot get
  8527. // right.
  8528. unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
  8529. Flags.setByValSize(FrameSize);
  8530. unsigned FrameAlign;
  8531. if (Arg.getParamAlignment())
  8532. FrameAlign = Arg.getParamAlignment();
  8533. else
  8534. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8535. Flags.setByValAlign(FrameAlign);
  8536. }
  8537. if (Arg.hasAttribute(Attribute::Nest))
  8538. Flags.setNest();
  8539. if (NeedsRegBlock)
  8540. Flags.setInConsecutiveRegs();
  8541. Flags.setOrigAlign(OriginalAlignment);
  8542. if (ArgCopyElisionCandidates.count(&Arg))
  8543. Flags.setCopyElisionCandidate();
  8544. if (Arg.hasAttribute(Attribute::Returned))
  8545. Flags.setReturned();
  8546. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8547. *CurDAG->getContext(), F.getCallingConv(), VT);
  8548. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8549. *CurDAG->getContext(), F.getCallingConv(), VT);
  8550. for (unsigned i = 0; i != NumRegs; ++i) {
  8551. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8552. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8553. if (NumRegs > 1 && i == 0)
  8554. MyFlags.Flags.setSplit();
  8555. // if it isn't first piece, alignment must be 1
  8556. else if (i > 0) {
  8557. MyFlags.Flags.setOrigAlign(1);
  8558. if (i == NumRegs - 1)
  8559. MyFlags.Flags.setSplitEnd();
  8560. }
  8561. Ins.push_back(MyFlags);
  8562. }
  8563. if (NeedsRegBlock && Value == NumValues - 1)
  8564. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8565. PartBase += VT.getStoreSize();
  8566. }
  8567. }
  8568. // Call the target to set up the argument values.
  8569. SmallVector<SDValue, 8> InVals;
  8570. SDValue NewRoot = TLI->LowerFormalArguments(
  8571. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8572. // Verify that the target's LowerFormalArguments behaved as expected.
  8573. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8574. "LowerFormalArguments didn't return a valid chain!");
  8575. assert(InVals.size() == Ins.size() &&
  8576. "LowerFormalArguments didn't emit the correct number of values!");
  8577. LLVM_DEBUG({
  8578. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8579. assert(InVals[i].getNode() &&
  8580. "LowerFormalArguments emitted a null value!");
  8581. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8582. "LowerFormalArguments emitted a value with the wrong type!");
  8583. }
  8584. });
  8585. // Update the DAG with the new chain value resulting from argument lowering.
  8586. DAG.setRoot(NewRoot);
  8587. // Set up the argument values.
  8588. unsigned i = 0;
  8589. if (!FuncInfo->CanLowerReturn) {
  8590. // Create a virtual register for the sret pointer, and put in a copy
  8591. // from the sret argument into it.
  8592. SmallVector<EVT, 1> ValueVTs;
  8593. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8594. F.getReturnType()->getPointerTo(
  8595. DAG.getDataLayout().getAllocaAddrSpace()),
  8596. ValueVTs);
  8597. MVT VT = ValueVTs[0].getSimpleVT();
  8598. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8599. Optional<ISD::NodeType> AssertOp = None;
  8600. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8601. nullptr, F.getCallingConv(), AssertOp);
  8602. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8603. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8604. Register SRetReg =
  8605. RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8606. FuncInfo->DemoteRegister = SRetReg;
  8607. NewRoot =
  8608. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8609. DAG.setRoot(NewRoot);
  8610. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8611. ++i;
  8612. }
  8613. SmallVector<SDValue, 4> Chains;
  8614. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8615. for (const Argument &Arg : F.args()) {
  8616. SmallVector<SDValue, 4> ArgValues;
  8617. SmallVector<EVT, 4> ValueVTs;
  8618. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8619. unsigned NumValues = ValueVTs.size();
  8620. if (NumValues == 0)
  8621. continue;
  8622. bool ArgHasUses = !Arg.use_empty();
  8623. // Elide the copying store if the target loaded this argument from a
  8624. // suitable fixed stack object.
  8625. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8626. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8627. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8628. InVals[i], ArgHasUses);
  8629. }
  8630. // If this argument is unused then remember its value. It is used to generate
  8631. // debugging information.
  8632. bool isSwiftErrorArg =
  8633. TLI->supportSwiftError() &&
  8634. Arg.hasAttribute(Attribute::SwiftError);
  8635. if (!ArgHasUses && !isSwiftErrorArg) {
  8636. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8637. // Also remember any frame index for use in FastISel.
  8638. if (FrameIndexSDNode *FI =
  8639. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8640. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8641. }
  8642. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8643. EVT VT = ValueVTs[Val];
  8644. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8645. F.getCallingConv(), VT);
  8646. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8647. *CurDAG->getContext(), F.getCallingConv(), VT);
  8648. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8649. // we do generate a copy for it that can be used on return from the
  8650. // function.
  8651. if (ArgHasUses || isSwiftErrorArg) {
  8652. Optional<ISD::NodeType> AssertOp;
  8653. if (Arg.hasAttribute(Attribute::SExt))
  8654. AssertOp = ISD::AssertSext;
  8655. else if (Arg.hasAttribute(Attribute::ZExt))
  8656. AssertOp = ISD::AssertZext;
  8657. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8658. PartVT, VT, nullptr,
  8659. F.getCallingConv(), AssertOp));
  8660. }
  8661. i += NumParts;
  8662. }
  8663. // We don't need to do anything else for unused arguments.
  8664. if (ArgValues.empty())
  8665. continue;
  8666. // Note down frame index.
  8667. if (FrameIndexSDNode *FI =
  8668. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8669. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8670. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8671. SDB->getCurSDLoc());
  8672. SDB->setValue(&Arg, Res);
  8673. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8674. // We want to associate the argument with the frame index, among
  8675. // involved operands, that correspond to the lowest address. The
  8676. // getCopyFromParts function, called earlier, is swapping the order of
  8677. // the operands to BUILD_PAIR depending on endianness. The result of
  8678. // that swapping is that the least significant bits of the argument will
  8679. // be in the first operand of the BUILD_PAIR node, and the most
  8680. // significant bits will be in the second operand.
  8681. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8682. if (LoadSDNode *LNode =
  8683. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8684. if (FrameIndexSDNode *FI =
  8685. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8686. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8687. }
  8688. // Analyses past this point are naive and don't expect an assertion.
  8689. if (Res.getOpcode() == ISD::AssertZext)
  8690. Res = Res.getOperand(0);
  8691. // Update the SwiftErrorVRegDefMap.
  8692. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8693. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8694. if (Register::isVirtualRegister(Reg))
  8695. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  8696. Reg);
  8697. }
  8698. // If this argument is live outside of the entry block, insert a copy from
  8699. // wherever we got it to the vreg that other BB's will reference it as.
  8700. if (Res.getOpcode() == ISD::CopyFromReg) {
  8701. // If we can, though, try to skip creating an unnecessary vreg.
  8702. // FIXME: This isn't very clean... it would be nice to make this more
  8703. // general.
  8704. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8705. if (Register::isVirtualRegister(Reg)) {
  8706. FuncInfo->ValueMap[&Arg] = Reg;
  8707. continue;
  8708. }
  8709. }
  8710. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8711. FuncInfo->InitializeRegForValue(&Arg);
  8712. SDB->CopyToExportRegsIfNeeded(&Arg);
  8713. }
  8714. }
  8715. if (!Chains.empty()) {
  8716. Chains.push_back(NewRoot);
  8717. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8718. }
  8719. DAG.setRoot(NewRoot);
  8720. assert(i == InVals.size() && "Argument register count mismatch!");
  8721. // If any argument copy elisions occurred and we have debug info, update the
  8722. // stale frame indices used in the dbg.declare variable info table.
  8723. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8724. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8725. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8726. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8727. if (I != ArgCopyElisionFrameIndexMap.end())
  8728. VI.Slot = I->second;
  8729. }
  8730. }
  8731. // Finally, if the target has anything special to do, allow it to do so.
  8732. EmitFunctionEntryCode();
  8733. }
  8734. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8735. /// ensure constants are generated when needed. Remember the virtual registers
  8736. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8737. /// directly add them, because expansion might result in multiple MBB's for one
  8738. /// BB. As such, the start of the BB might correspond to a different MBB than
  8739. /// the end.
  8740. void
  8741. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8742. const Instruction *TI = LLVMBB->getTerminator();
  8743. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8744. // Check PHI nodes in successors that expect a value to be available from this
  8745. // block.
  8746. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8747. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8748. if (!isa<PHINode>(SuccBB->begin())) continue;
  8749. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8750. // If this terminator has multiple identical successors (common for
  8751. // switches), only handle each succ once.
  8752. if (!SuccsHandled.insert(SuccMBB).second)
  8753. continue;
  8754. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8755. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8756. // nodes and Machine PHI nodes, but the incoming operands have not been
  8757. // emitted yet.
  8758. for (const PHINode &PN : SuccBB->phis()) {
  8759. // Ignore dead phi's.
  8760. if (PN.use_empty())
  8761. continue;
  8762. // Skip empty types
  8763. if (PN.getType()->isEmptyTy())
  8764. continue;
  8765. unsigned Reg;
  8766. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8767. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8768. unsigned &RegOut = ConstantsOut[C];
  8769. if (RegOut == 0) {
  8770. RegOut = FuncInfo.CreateRegs(C);
  8771. CopyValueToVirtualRegister(C, RegOut);
  8772. }
  8773. Reg = RegOut;
  8774. } else {
  8775. DenseMap<const Value *, unsigned>::iterator I =
  8776. FuncInfo.ValueMap.find(PHIOp);
  8777. if (I != FuncInfo.ValueMap.end())
  8778. Reg = I->second;
  8779. else {
  8780. assert(isa<AllocaInst>(PHIOp) &&
  8781. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8782. "Didn't codegen value into a register!??");
  8783. Reg = FuncInfo.CreateRegs(PHIOp);
  8784. CopyValueToVirtualRegister(PHIOp, Reg);
  8785. }
  8786. }
  8787. // Remember that this register needs to added to the machine PHI node as
  8788. // the input for this MBB.
  8789. SmallVector<EVT, 4> ValueVTs;
  8790. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8791. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8792. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8793. EVT VT = ValueVTs[vti];
  8794. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8795. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8796. FuncInfo.PHINodesToUpdate.push_back(
  8797. std::make_pair(&*MBBI++, Reg + i));
  8798. Reg += NumRegisters;
  8799. }
  8800. }
  8801. }
  8802. ConstantsOut.clear();
  8803. }
  8804. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8805. /// is 0.
  8806. MachineBasicBlock *
  8807. SelectionDAGBuilder::StackProtectorDescriptor::
  8808. AddSuccessorMBB(const BasicBlock *BB,
  8809. MachineBasicBlock *ParentMBB,
  8810. bool IsLikely,
  8811. MachineBasicBlock *SuccMBB) {
  8812. // If SuccBB has not been created yet, create it.
  8813. if (!SuccMBB) {
  8814. MachineFunction *MF = ParentMBB->getParent();
  8815. MachineFunction::iterator BBI(ParentMBB);
  8816. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8817. MF->insert(++BBI, SuccMBB);
  8818. }
  8819. // Add it as a successor of ParentMBB.
  8820. ParentMBB->addSuccessor(
  8821. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8822. return SuccMBB;
  8823. }
  8824. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8825. MachineFunction::iterator I(MBB);
  8826. if (++I == FuncInfo.MF->end())
  8827. return nullptr;
  8828. return &*I;
  8829. }
  8830. /// During lowering new call nodes can be created (such as memset, etc.).
  8831. /// Those will become new roots of the current DAG, but complications arise
  8832. /// when they are tail calls. In such cases, the call lowering will update
  8833. /// the root, but the builder still needs to know that a tail call has been
  8834. /// lowered in order to avoid generating an additional return.
  8835. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8836. // If the node is null, we do have a tail call.
  8837. if (MaybeTC.getNode() != nullptr)
  8838. DAG.setRoot(MaybeTC);
  8839. else
  8840. HasTailCall = true;
  8841. }
  8842. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8843. MachineBasicBlock *SwitchMBB,
  8844. MachineBasicBlock *DefaultMBB) {
  8845. MachineFunction *CurMF = FuncInfo.MF;
  8846. MachineBasicBlock *NextMBB = nullptr;
  8847. MachineFunction::iterator BBI(W.MBB);
  8848. if (++BBI != FuncInfo.MF->end())
  8849. NextMBB = &*BBI;
  8850. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8851. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8852. if (Size == 2 && W.MBB == SwitchMBB) {
  8853. // If any two of the cases has the same destination, and if one value
  8854. // is the same as the other, but has one bit unset that the other has set,
  8855. // use bit manipulation to do two compares at once. For example:
  8856. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8857. // TODO: This could be extended to merge any 2 cases in switches with 3
  8858. // cases.
  8859. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8860. CaseCluster &Small = *W.FirstCluster;
  8861. CaseCluster &Big = *W.LastCluster;
  8862. if (Small.Low == Small.High && Big.Low == Big.High &&
  8863. Small.MBB == Big.MBB) {
  8864. const APInt &SmallValue = Small.Low->getValue();
  8865. const APInt &BigValue = Big.Low->getValue();
  8866. // Check that there is only one bit different.
  8867. APInt CommonBit = BigValue ^ SmallValue;
  8868. if (CommonBit.isPowerOf2()) {
  8869. SDValue CondLHS = getValue(Cond);
  8870. EVT VT = CondLHS.getValueType();
  8871. SDLoc DL = getCurSDLoc();
  8872. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8873. DAG.getConstant(CommonBit, DL, VT));
  8874. SDValue Cond = DAG.getSetCC(
  8875. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8876. ISD::SETEQ);
  8877. // Update successor info.
  8878. // Both Small and Big will jump to Small.BB, so we sum up the
  8879. // probabilities.
  8880. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8881. if (BPI)
  8882. addSuccessorWithProb(
  8883. SwitchMBB, DefaultMBB,
  8884. // The default destination is the first successor in IR.
  8885. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8886. else
  8887. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8888. // Insert the true branch.
  8889. SDValue BrCond =
  8890. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8891. DAG.getBasicBlock(Small.MBB));
  8892. // Insert the false branch.
  8893. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8894. DAG.getBasicBlock(DefaultMBB));
  8895. DAG.setRoot(BrCond);
  8896. return;
  8897. }
  8898. }
  8899. }
  8900. if (TM.getOptLevel() != CodeGenOpt::None) {
  8901. // Here, we order cases by probability so the most likely case will be
  8902. // checked first. However, two clusters can have the same probability in
  8903. // which case their relative ordering is non-deterministic. So we use Low
  8904. // as a tie-breaker as clusters are guaranteed to never overlap.
  8905. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  8906. [](const CaseCluster &a, const CaseCluster &b) {
  8907. return a.Prob != b.Prob ?
  8908. a.Prob > b.Prob :
  8909. a.Low->getValue().slt(b.Low->getValue());
  8910. });
  8911. // Rearrange the case blocks so that the last one falls through if possible
  8912. // without changing the order of probabilities.
  8913. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8914. --I;
  8915. if (I->Prob > W.LastCluster->Prob)
  8916. break;
  8917. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8918. std::swap(*I, *W.LastCluster);
  8919. break;
  8920. }
  8921. }
  8922. }
  8923. // Compute total probability.
  8924. BranchProbability DefaultProb = W.DefaultProb;
  8925. BranchProbability UnhandledProbs = DefaultProb;
  8926. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8927. UnhandledProbs += I->Prob;
  8928. MachineBasicBlock *CurMBB = W.MBB;
  8929. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8930. bool FallthroughUnreachable = false;
  8931. MachineBasicBlock *Fallthrough;
  8932. if (I == W.LastCluster) {
  8933. // For the last cluster, fall through to the default destination.
  8934. Fallthrough = DefaultMBB;
  8935. FallthroughUnreachable = isa<UnreachableInst>(
  8936. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  8937. } else {
  8938. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8939. CurMF->insert(BBI, Fallthrough);
  8940. // Put Cond in a virtual register to make it available from the new blocks.
  8941. ExportFromCurrentBlock(Cond);
  8942. }
  8943. UnhandledProbs -= I->Prob;
  8944. switch (I->Kind) {
  8945. case CC_JumpTable: {
  8946. // FIXME: Optimize away range check based on pivot comparisons.
  8947. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  8948. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  8949. // The jump block hasn't been inserted yet; insert it here.
  8950. MachineBasicBlock *JumpMBB = JT->MBB;
  8951. CurMF->insert(BBI, JumpMBB);
  8952. auto JumpProb = I->Prob;
  8953. auto FallthroughProb = UnhandledProbs;
  8954. // If the default statement is a target of the jump table, we evenly
  8955. // distribute the default probability to successors of CurMBB. Also
  8956. // update the probability on the edge from JumpMBB to Fallthrough.
  8957. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8958. SE = JumpMBB->succ_end();
  8959. SI != SE; ++SI) {
  8960. if (*SI == DefaultMBB) {
  8961. JumpProb += DefaultProb / 2;
  8962. FallthroughProb -= DefaultProb / 2;
  8963. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8964. JumpMBB->normalizeSuccProbs();
  8965. break;
  8966. }
  8967. }
  8968. if (FallthroughUnreachable) {
  8969. // Skip the range check if the fallthrough block is unreachable.
  8970. JTH->OmitRangeCheck = true;
  8971. }
  8972. if (!JTH->OmitRangeCheck)
  8973. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8974. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8975. CurMBB->normalizeSuccProbs();
  8976. // The jump table header will be inserted in our current block, do the
  8977. // range check, and fall through to our fallthrough block.
  8978. JTH->HeaderBB = CurMBB;
  8979. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8980. // If we're in the right place, emit the jump table header right now.
  8981. if (CurMBB == SwitchMBB) {
  8982. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8983. JTH->Emitted = true;
  8984. }
  8985. break;
  8986. }
  8987. case CC_BitTests: {
  8988. // FIXME: Optimize away range check based on pivot comparisons.
  8989. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  8990. // The bit test blocks haven't been inserted yet; insert them here.
  8991. for (BitTestCase &BTC : BTB->Cases)
  8992. CurMF->insert(BBI, BTC.ThisBB);
  8993. // Fill in fields of the BitTestBlock.
  8994. BTB->Parent = CurMBB;
  8995. BTB->Default = Fallthrough;
  8996. BTB->DefaultProb = UnhandledProbs;
  8997. // If the cases in bit test don't form a contiguous range, we evenly
  8998. // distribute the probability on the edge to Fallthrough to two
  8999. // successors of CurMBB.
  9000. if (!BTB->ContiguousRange) {
  9001. BTB->Prob += DefaultProb / 2;
  9002. BTB->DefaultProb -= DefaultProb / 2;
  9003. }
  9004. if (FallthroughUnreachable) {
  9005. // Skip the range check if the fallthrough block is unreachable.
  9006. BTB->OmitRangeCheck = true;
  9007. }
  9008. // If we're in the right place, emit the bit test header right now.
  9009. if (CurMBB == SwitchMBB) {
  9010. visitBitTestHeader(*BTB, SwitchMBB);
  9011. BTB->Emitted = true;
  9012. }
  9013. break;
  9014. }
  9015. case CC_Range: {
  9016. const Value *RHS, *LHS, *MHS;
  9017. ISD::CondCode CC;
  9018. if (I->Low == I->High) {
  9019. // Check Cond == I->Low.
  9020. CC = ISD::SETEQ;
  9021. LHS = Cond;
  9022. RHS=I->Low;
  9023. MHS = nullptr;
  9024. } else {
  9025. // Check I->Low <= Cond <= I->High.
  9026. CC = ISD::SETLE;
  9027. LHS = I->Low;
  9028. MHS = Cond;
  9029. RHS = I->High;
  9030. }
  9031. // If Fallthrough is unreachable, fold away the comparison.
  9032. if (FallthroughUnreachable)
  9033. CC = ISD::SETTRUE;
  9034. // The false probability is the sum of all unhandled cases.
  9035. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9036. getCurSDLoc(), I->Prob, UnhandledProbs);
  9037. if (CurMBB == SwitchMBB)
  9038. visitSwitchCase(CB, SwitchMBB);
  9039. else
  9040. SL->SwitchCases.push_back(CB);
  9041. break;
  9042. }
  9043. }
  9044. CurMBB = Fallthrough;
  9045. }
  9046. }
  9047. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9048. CaseClusterIt First,
  9049. CaseClusterIt Last) {
  9050. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9051. if (X.Prob != CC.Prob)
  9052. return X.Prob > CC.Prob;
  9053. // Ties are broken by comparing the case value.
  9054. return X.Low->getValue().slt(CC.Low->getValue());
  9055. });
  9056. }
  9057. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9058. const SwitchWorkListItem &W,
  9059. Value *Cond,
  9060. MachineBasicBlock *SwitchMBB) {
  9061. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9062. "Clusters not sorted?");
  9063. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9064. // Balance the tree based on branch probabilities to create a near-optimal (in
  9065. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9066. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9067. CaseClusterIt LastLeft = W.FirstCluster;
  9068. CaseClusterIt FirstRight = W.LastCluster;
  9069. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9070. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9071. // Move LastLeft and FirstRight towards each other from opposite directions to
  9072. // find a partitioning of the clusters which balances the probability on both
  9073. // sides. If LeftProb and RightProb are equal, alternate which side is
  9074. // taken to ensure 0-probability nodes are distributed evenly.
  9075. unsigned I = 0;
  9076. while (LastLeft + 1 < FirstRight) {
  9077. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9078. LeftProb += (++LastLeft)->Prob;
  9079. else
  9080. RightProb += (--FirstRight)->Prob;
  9081. I++;
  9082. }
  9083. while (true) {
  9084. // Our binary search tree differs from a typical BST in that ours can have up
  9085. // to three values in each leaf. The pivot selection above doesn't take that
  9086. // into account, which means the tree might require more nodes and be less
  9087. // efficient. We compensate for this here.
  9088. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9089. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9090. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9091. // If one side has less than 3 clusters, and the other has more than 3,
  9092. // consider taking a cluster from the other side.
  9093. if (NumLeft < NumRight) {
  9094. // Consider moving the first cluster on the right to the left side.
  9095. CaseCluster &CC = *FirstRight;
  9096. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9097. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9098. if (LeftSideRank <= RightSideRank) {
  9099. // Moving the cluster to the left does not demote it.
  9100. ++LastLeft;
  9101. ++FirstRight;
  9102. continue;
  9103. }
  9104. } else {
  9105. assert(NumRight < NumLeft);
  9106. // Consider moving the last element on the left to the right side.
  9107. CaseCluster &CC = *LastLeft;
  9108. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9109. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9110. if (RightSideRank <= LeftSideRank) {
  9111. // Moving the cluster to the right does not demot it.
  9112. --LastLeft;
  9113. --FirstRight;
  9114. continue;
  9115. }
  9116. }
  9117. }
  9118. break;
  9119. }
  9120. assert(LastLeft + 1 == FirstRight);
  9121. assert(LastLeft >= W.FirstCluster);
  9122. assert(FirstRight <= W.LastCluster);
  9123. // Use the first element on the right as pivot since we will make less-than
  9124. // comparisons against it.
  9125. CaseClusterIt PivotCluster = FirstRight;
  9126. assert(PivotCluster > W.FirstCluster);
  9127. assert(PivotCluster <= W.LastCluster);
  9128. CaseClusterIt FirstLeft = W.FirstCluster;
  9129. CaseClusterIt LastRight = W.LastCluster;
  9130. const ConstantInt *Pivot = PivotCluster->Low;
  9131. // New blocks will be inserted immediately after the current one.
  9132. MachineFunction::iterator BBI(W.MBB);
  9133. ++BBI;
  9134. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9135. // we can branch to its destination directly if it's squeezed exactly in
  9136. // between the known lower bound and Pivot - 1.
  9137. MachineBasicBlock *LeftMBB;
  9138. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9139. FirstLeft->Low == W.GE &&
  9140. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9141. LeftMBB = FirstLeft->MBB;
  9142. } else {
  9143. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9144. FuncInfo.MF->insert(BBI, LeftMBB);
  9145. WorkList.push_back(
  9146. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9147. // Put Cond in a virtual register to make it available from the new blocks.
  9148. ExportFromCurrentBlock(Cond);
  9149. }
  9150. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9151. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9152. // directly if RHS.High equals the current upper bound.
  9153. MachineBasicBlock *RightMBB;
  9154. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9155. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9156. RightMBB = FirstRight->MBB;
  9157. } else {
  9158. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9159. FuncInfo.MF->insert(BBI, RightMBB);
  9160. WorkList.push_back(
  9161. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9162. // Put Cond in a virtual register to make it available from the new blocks.
  9163. ExportFromCurrentBlock(Cond);
  9164. }
  9165. // Create the CaseBlock record that will be used to lower the branch.
  9166. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9167. getCurSDLoc(), LeftProb, RightProb);
  9168. if (W.MBB == SwitchMBB)
  9169. visitSwitchCase(CB, SwitchMBB);
  9170. else
  9171. SL->SwitchCases.push_back(CB);
  9172. }
  9173. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9174. // from the swith statement.
  9175. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9176. BranchProbability PeeledCaseProb) {
  9177. if (PeeledCaseProb == BranchProbability::getOne())
  9178. return BranchProbability::getZero();
  9179. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9180. uint32_t Numerator = CaseProb.getNumerator();
  9181. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9182. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9183. }
  9184. // Try to peel the top probability case if it exceeds the threshold.
  9185. // Return current MachineBasicBlock for the switch statement if the peeling
  9186. // does not occur.
  9187. // If the peeling is performed, return the newly created MachineBasicBlock
  9188. // for the peeled switch statement. Also update Clusters to remove the peeled
  9189. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9190. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9191. const SwitchInst &SI, CaseClusterVector &Clusters,
  9192. BranchProbability &PeeledCaseProb) {
  9193. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9194. // Don't perform if there is only one cluster or optimizing for size.
  9195. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9196. TM.getOptLevel() == CodeGenOpt::None ||
  9197. SwitchMBB->getParent()->getFunction().hasMinSize())
  9198. return SwitchMBB;
  9199. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9200. unsigned PeeledCaseIndex = 0;
  9201. bool SwitchPeeled = false;
  9202. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9203. CaseCluster &CC = Clusters[Index];
  9204. if (CC.Prob < TopCaseProb)
  9205. continue;
  9206. TopCaseProb = CC.Prob;
  9207. PeeledCaseIndex = Index;
  9208. SwitchPeeled = true;
  9209. }
  9210. if (!SwitchPeeled)
  9211. return SwitchMBB;
  9212. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9213. << TopCaseProb << "\n");
  9214. // Record the MBB for the peeled switch statement.
  9215. MachineFunction::iterator BBI(SwitchMBB);
  9216. ++BBI;
  9217. MachineBasicBlock *PeeledSwitchMBB =
  9218. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9219. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9220. ExportFromCurrentBlock(SI.getCondition());
  9221. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9222. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9223. nullptr, nullptr, TopCaseProb.getCompl()};
  9224. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9225. Clusters.erase(PeeledCaseIt);
  9226. for (CaseCluster &CC : Clusters) {
  9227. LLVM_DEBUG(
  9228. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9229. << CC.Prob << "\n");
  9230. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9231. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9232. }
  9233. PeeledCaseProb = TopCaseProb;
  9234. return PeeledSwitchMBB;
  9235. }
  9236. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9237. // Extract cases from the switch.
  9238. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9239. CaseClusterVector Clusters;
  9240. Clusters.reserve(SI.getNumCases());
  9241. for (auto I : SI.cases()) {
  9242. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9243. const ConstantInt *CaseVal = I.getCaseValue();
  9244. BranchProbability Prob =
  9245. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9246. : BranchProbability(1, SI.getNumCases() + 1);
  9247. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9248. }
  9249. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9250. // Cluster adjacent cases with the same destination. We do this at all
  9251. // optimization levels because it's cheap to do and will make codegen faster
  9252. // if there are many clusters.
  9253. sortAndRangeify(Clusters);
  9254. // The branch probablity of the peeled case.
  9255. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9256. MachineBasicBlock *PeeledSwitchMBB =
  9257. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9258. // If there is only the default destination, jump there directly.
  9259. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9260. if (Clusters.empty()) {
  9261. assert(PeeledSwitchMBB == SwitchMBB);
  9262. SwitchMBB->addSuccessor(DefaultMBB);
  9263. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9264. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9265. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9266. }
  9267. return;
  9268. }
  9269. SL->findJumpTables(Clusters, &SI, DefaultMBB);
  9270. SL->findBitTestClusters(Clusters, &SI);
  9271. LLVM_DEBUG({
  9272. dbgs() << "Case clusters: ";
  9273. for (const CaseCluster &C : Clusters) {
  9274. if (C.Kind == CC_JumpTable)
  9275. dbgs() << "JT:";
  9276. if (C.Kind == CC_BitTests)
  9277. dbgs() << "BT:";
  9278. C.Low->getValue().print(dbgs(), true);
  9279. if (C.Low != C.High) {
  9280. dbgs() << '-';
  9281. C.High->getValue().print(dbgs(), true);
  9282. }
  9283. dbgs() << ' ';
  9284. }
  9285. dbgs() << '\n';
  9286. });
  9287. assert(!Clusters.empty());
  9288. SwitchWorkList WorkList;
  9289. CaseClusterIt First = Clusters.begin();
  9290. CaseClusterIt Last = Clusters.end() - 1;
  9291. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9292. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9293. // DefaultMBB is not replaced.
  9294. if (PeeledCaseProb != BranchProbability::getZero() &&
  9295. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9296. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9297. WorkList.push_back(
  9298. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9299. while (!WorkList.empty()) {
  9300. SwitchWorkListItem W = WorkList.back();
  9301. WorkList.pop_back();
  9302. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9303. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9304. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9305. // For optimized builds, lower large range as a balanced binary tree.
  9306. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9307. continue;
  9308. }
  9309. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9310. }
  9311. }