SelectionDAGBuilder.cpp 410 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544
  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.getMetadata(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 Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2305. DAG.getConstant(B.First, dl, VT));
  2306. // Check range
  2307. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2308. SDValue RangeCmp = DAG.getSetCC(
  2309. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2310. Sub.getValueType()),
  2311. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2312. // Determine the type of the test operands.
  2313. bool UsePtrType = false;
  2314. if (!TLI.isTypeLegal(VT))
  2315. UsePtrType = true;
  2316. else {
  2317. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2318. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2319. // Switch table case range are encoded into series of masks.
  2320. // Just use pointer type, it's guaranteed to fit.
  2321. UsePtrType = true;
  2322. break;
  2323. }
  2324. }
  2325. if (UsePtrType) {
  2326. VT = TLI.getPointerTy(DAG.getDataLayout());
  2327. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2328. }
  2329. B.RegVT = VT.getSimpleVT();
  2330. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2331. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2332. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2333. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2334. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2335. SwitchBB->normalizeSuccProbs();
  2336. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2337. MVT::Other, CopyTo, RangeCmp,
  2338. DAG.getBasicBlock(B.Default));
  2339. // Avoid emitting unnecessary branches to the next block.
  2340. if (MBB != NextBlock(SwitchBB))
  2341. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2342. DAG.getBasicBlock(MBB));
  2343. DAG.setRoot(BrRange);
  2344. }
  2345. /// visitBitTestCase - this function produces one "bit test"
  2346. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2347. MachineBasicBlock* NextMBB,
  2348. BranchProbability BranchProbToNext,
  2349. unsigned Reg,
  2350. BitTestCase &B,
  2351. MachineBasicBlock *SwitchBB) {
  2352. SDLoc dl = getCurSDLoc();
  2353. MVT VT = BB.RegVT;
  2354. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2355. SDValue Cmp;
  2356. unsigned PopCount = countPopulation(B.Mask);
  2357. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2358. if (PopCount == 1) {
  2359. // Testing for a single bit; just compare the shift count with what it
  2360. // would need to be to shift a 1 bit in that position.
  2361. Cmp = DAG.getSetCC(
  2362. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2363. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2364. ISD::SETEQ);
  2365. } else if (PopCount == BB.Range) {
  2366. // There is only one zero bit in the range, test for it directly.
  2367. Cmp = DAG.getSetCC(
  2368. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2369. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2370. ISD::SETNE);
  2371. } else {
  2372. // Make desired shift
  2373. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2374. DAG.getConstant(1, dl, VT), ShiftOp);
  2375. // Emit bit tests and jumps
  2376. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2377. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2378. Cmp = DAG.getSetCC(
  2379. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2380. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2381. }
  2382. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2383. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2384. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2385. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2386. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2387. // one as they are relative probabilities (and thus work more like weights),
  2388. // and hence we need to normalize them to let the sum of them become one.
  2389. SwitchBB->normalizeSuccProbs();
  2390. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2391. MVT::Other, getControlRoot(),
  2392. Cmp, DAG.getBasicBlock(B.TargetBB));
  2393. // Avoid emitting unnecessary branches to the next block.
  2394. if (NextMBB != NextBlock(SwitchBB))
  2395. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2396. DAG.getBasicBlock(NextMBB));
  2397. DAG.setRoot(BrAnd);
  2398. }
  2399. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2400. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2401. // Retrieve successors. Look through artificial IR level blocks like
  2402. // catchswitch for successors.
  2403. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2404. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2405. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2406. // have to do anything here to lower funclet bundles.
  2407. assert(!I.hasOperandBundlesOtherThan(
  2408. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2409. "Cannot lower invokes with arbitrary operand bundles yet!");
  2410. const Value *Callee(I.getCalledValue());
  2411. const Function *Fn = dyn_cast<Function>(Callee);
  2412. if (isa<InlineAsm>(Callee))
  2413. visitInlineAsm(&I);
  2414. else if (Fn && Fn->isIntrinsic()) {
  2415. switch (Fn->getIntrinsicID()) {
  2416. default:
  2417. llvm_unreachable("Cannot invoke this intrinsic");
  2418. case Intrinsic::donothing:
  2419. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2420. break;
  2421. case Intrinsic::experimental_patchpoint_void:
  2422. case Intrinsic::experimental_patchpoint_i64:
  2423. visitPatchpoint(&I, EHPadBB);
  2424. break;
  2425. case Intrinsic::experimental_gc_statepoint:
  2426. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2427. break;
  2428. case Intrinsic::wasm_rethrow_in_catch: {
  2429. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2430. // special because it can be invoked, so we manually lower it to a DAG
  2431. // node here.
  2432. SmallVector<SDValue, 8> Ops;
  2433. Ops.push_back(getRoot()); // inchain
  2434. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2435. Ops.push_back(
  2436. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2437. TLI.getPointerTy(DAG.getDataLayout())));
  2438. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2439. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2440. break;
  2441. }
  2442. }
  2443. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2444. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2445. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2446. // intrinsic, and right now there are no plans to support other intrinsics
  2447. // with deopt state.
  2448. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2449. } else {
  2450. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2451. }
  2452. // If the value of the invoke is used outside of its defining block, make it
  2453. // available as a virtual register.
  2454. // We already took care of the exported value for the statepoint instruction
  2455. // during call to the LowerStatepoint.
  2456. if (!isStatepoint(I)) {
  2457. CopyToExportRegsIfNeeded(&I);
  2458. }
  2459. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2460. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2461. BranchProbability EHPadBBProb =
  2462. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2463. : BranchProbability::getZero();
  2464. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2465. // Update successor info.
  2466. addSuccessorWithProb(InvokeMBB, Return);
  2467. for (auto &UnwindDest : UnwindDests) {
  2468. UnwindDest.first->setIsEHPad();
  2469. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2470. }
  2471. InvokeMBB->normalizeSuccProbs();
  2472. // Drop into normal successor.
  2473. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2474. DAG.getBasicBlock(Return)));
  2475. }
  2476. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2477. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2478. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2479. // have to do anything here to lower funclet bundles.
  2480. assert(!I.hasOperandBundlesOtherThan(
  2481. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2482. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2483. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2484. "Only know how to handle inlineasm callbr");
  2485. visitInlineAsm(&I);
  2486. // Retrieve successors.
  2487. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2488. // Update successor info.
  2489. addSuccessorWithProb(CallBrMBB, Return);
  2490. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2491. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2492. addSuccessorWithProb(CallBrMBB, Target);
  2493. }
  2494. CallBrMBB->normalizeSuccProbs();
  2495. // Drop into default successor.
  2496. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2497. MVT::Other, getControlRoot(),
  2498. DAG.getBasicBlock(Return)));
  2499. }
  2500. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2501. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2502. }
  2503. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2504. assert(FuncInfo.MBB->isEHPad() &&
  2505. "Call to landingpad not in landing pad!");
  2506. // If there aren't registers to copy the values into (e.g., during SjLj
  2507. // exceptions), then don't bother to create these DAG nodes.
  2508. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2509. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2510. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2511. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2512. return;
  2513. // If landingpad's return type is token type, we don't create DAG nodes
  2514. // for its exception pointer and selector value. The extraction of exception
  2515. // pointer or selector value from token type landingpads is not currently
  2516. // supported.
  2517. if (LP.getType()->isTokenTy())
  2518. return;
  2519. SmallVector<EVT, 2> ValueVTs;
  2520. SDLoc dl = getCurSDLoc();
  2521. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2522. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2523. // Get the two live-in registers as SDValues. The physregs have already been
  2524. // copied into virtual registers.
  2525. SDValue Ops[2];
  2526. if (FuncInfo.ExceptionPointerVirtReg) {
  2527. Ops[0] = DAG.getZExtOrTrunc(
  2528. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2529. FuncInfo.ExceptionPointerVirtReg,
  2530. TLI.getPointerTy(DAG.getDataLayout())),
  2531. dl, ValueVTs[0]);
  2532. } else {
  2533. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2534. }
  2535. Ops[1] = DAG.getZExtOrTrunc(
  2536. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2537. FuncInfo.ExceptionSelectorVirtReg,
  2538. TLI.getPointerTy(DAG.getDataLayout())),
  2539. dl, ValueVTs[1]);
  2540. // Merge into one.
  2541. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2542. DAG.getVTList(ValueVTs), Ops);
  2543. setValue(&LP, Res);
  2544. }
  2545. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2546. MachineBasicBlock *Last) {
  2547. // Update JTCases.
  2548. for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
  2549. if (SL->JTCases[i].first.HeaderBB == First)
  2550. SL->JTCases[i].first.HeaderBB = Last;
  2551. // Update BitTestCases.
  2552. for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
  2553. if (SL->BitTestCases[i].Parent == First)
  2554. SL->BitTestCases[i].Parent = Last;
  2555. }
  2556. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2557. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2558. // Update machine-CFG edges with unique successors.
  2559. SmallSet<BasicBlock*, 32> Done;
  2560. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2561. BasicBlock *BB = I.getSuccessor(i);
  2562. bool Inserted = Done.insert(BB).second;
  2563. if (!Inserted)
  2564. continue;
  2565. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2566. addSuccessorWithProb(IndirectBrMBB, Succ);
  2567. }
  2568. IndirectBrMBB->normalizeSuccProbs();
  2569. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2570. MVT::Other, getControlRoot(),
  2571. getValue(I.getAddress())));
  2572. }
  2573. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2574. if (!DAG.getTarget().Options.TrapUnreachable)
  2575. return;
  2576. // We may be able to ignore unreachable behind a noreturn call.
  2577. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2578. const BasicBlock &BB = *I.getParent();
  2579. if (&I != &BB.front()) {
  2580. BasicBlock::const_iterator PredI =
  2581. std::prev(BasicBlock::const_iterator(&I));
  2582. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2583. if (Call->doesNotReturn())
  2584. return;
  2585. }
  2586. }
  2587. }
  2588. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2589. }
  2590. void SelectionDAGBuilder::visitFSub(const User &I) {
  2591. // -0.0 - X --> fneg
  2592. Type *Ty = I.getType();
  2593. if (isa<Constant>(I.getOperand(0)) &&
  2594. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2595. SDValue Op2 = getValue(I.getOperand(1));
  2596. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2597. Op2.getValueType(), Op2));
  2598. return;
  2599. }
  2600. visitBinary(I, ISD::FSUB);
  2601. }
  2602. /// Checks if the given instruction performs a vector reduction, in which case
  2603. /// we have the freedom to alter the elements in the result as long as the
  2604. /// reduction of them stays unchanged.
  2605. static bool isVectorReductionOp(const User *I) {
  2606. const Instruction *Inst = dyn_cast<Instruction>(I);
  2607. if (!Inst || !Inst->getType()->isVectorTy())
  2608. return false;
  2609. auto OpCode = Inst->getOpcode();
  2610. switch (OpCode) {
  2611. case Instruction::Add:
  2612. case Instruction::Mul:
  2613. case Instruction::And:
  2614. case Instruction::Or:
  2615. case Instruction::Xor:
  2616. break;
  2617. case Instruction::FAdd:
  2618. case Instruction::FMul:
  2619. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2620. if (FPOp->getFastMathFlags().isFast())
  2621. break;
  2622. LLVM_FALLTHROUGH;
  2623. default:
  2624. return false;
  2625. }
  2626. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2627. // Ensure the reduction size is a power of 2.
  2628. if (!isPowerOf2_32(ElemNum))
  2629. return false;
  2630. unsigned ElemNumToReduce = ElemNum;
  2631. // Do DFS search on the def-use chain from the given instruction. We only
  2632. // allow four kinds of operations during the search until we reach the
  2633. // instruction that extracts the first element from the vector:
  2634. //
  2635. // 1. The reduction operation of the same opcode as the given instruction.
  2636. //
  2637. // 2. PHI node.
  2638. //
  2639. // 3. ShuffleVector instruction together with a reduction operation that
  2640. // does a partial reduction.
  2641. //
  2642. // 4. ExtractElement that extracts the first element from the vector, and we
  2643. // stop searching the def-use chain here.
  2644. //
  2645. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2646. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2647. // a reduction operation if we meet any other instructions other than those
  2648. // listed above.
  2649. SmallVector<const User *, 16> UsersToVisit{Inst};
  2650. SmallPtrSet<const User *, 16> Visited;
  2651. bool ReduxExtracted = false;
  2652. while (!UsersToVisit.empty()) {
  2653. auto User = UsersToVisit.back();
  2654. UsersToVisit.pop_back();
  2655. if (!Visited.insert(User).second)
  2656. continue;
  2657. for (const auto &U : User->users()) {
  2658. auto Inst = dyn_cast<Instruction>(U);
  2659. if (!Inst)
  2660. return false;
  2661. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2662. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2663. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2664. return false;
  2665. UsersToVisit.push_back(U);
  2666. } else if (const ShuffleVectorInst *ShufInst =
  2667. dyn_cast<ShuffleVectorInst>(U)) {
  2668. // Detect the following pattern: A ShuffleVector instruction together
  2669. // with a reduction that do partial reduction on the first and second
  2670. // ElemNumToReduce / 2 elements, and store the result in
  2671. // ElemNumToReduce / 2 elements in another vector.
  2672. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2673. if (ResultElements < ElemNum)
  2674. return false;
  2675. if (ElemNumToReduce == 1)
  2676. return false;
  2677. if (!isa<UndefValue>(U->getOperand(1)))
  2678. return false;
  2679. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2680. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2681. return false;
  2682. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2683. if (ShufInst->getMaskValue(i) != -1)
  2684. return false;
  2685. // There is only one user of this ShuffleVector instruction, which
  2686. // must be a reduction operation.
  2687. if (!U->hasOneUse())
  2688. return false;
  2689. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2690. if (!U2 || U2->getOpcode() != OpCode)
  2691. return false;
  2692. // Check operands of the reduction operation.
  2693. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2694. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2695. UsersToVisit.push_back(U2);
  2696. ElemNumToReduce /= 2;
  2697. } else
  2698. return false;
  2699. } else if (isa<ExtractElementInst>(U)) {
  2700. // At this moment we should have reduced all elements in the vector.
  2701. if (ElemNumToReduce != 1)
  2702. return false;
  2703. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2704. if (!Val || !Val->isZero())
  2705. return false;
  2706. ReduxExtracted = true;
  2707. } else
  2708. return false;
  2709. }
  2710. }
  2711. return ReduxExtracted;
  2712. }
  2713. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2714. SDNodeFlags Flags;
  2715. SDValue Op = getValue(I.getOperand(0));
  2716. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2717. Op, Flags);
  2718. setValue(&I, UnNodeValue);
  2719. }
  2720. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2721. SDNodeFlags Flags;
  2722. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2723. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2724. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2725. }
  2726. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2727. Flags.setExact(ExactOp->isExact());
  2728. }
  2729. if (isVectorReductionOp(&I)) {
  2730. Flags.setVectorReduction(true);
  2731. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2732. }
  2733. SDValue Op1 = getValue(I.getOperand(0));
  2734. SDValue Op2 = getValue(I.getOperand(1));
  2735. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2736. Op1, Op2, Flags);
  2737. setValue(&I, BinNodeValue);
  2738. }
  2739. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2740. SDValue Op1 = getValue(I.getOperand(0));
  2741. SDValue Op2 = getValue(I.getOperand(1));
  2742. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2743. Op1.getValueType(), DAG.getDataLayout());
  2744. // Coerce the shift amount to the right type if we can.
  2745. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2746. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2747. unsigned Op2Size = Op2.getValueSizeInBits();
  2748. SDLoc DL = getCurSDLoc();
  2749. // If the operand is smaller than the shift count type, promote it.
  2750. if (ShiftSize > Op2Size)
  2751. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2752. // If the operand is larger than the shift count type but the shift
  2753. // count type has enough bits to represent any shift value, truncate
  2754. // it now. This is a common case and it exposes the truncate to
  2755. // optimization early.
  2756. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2757. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2758. // Otherwise we'll need to temporarily settle for some other convenient
  2759. // type. Type legalization will make adjustments once the shiftee is split.
  2760. else
  2761. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2762. }
  2763. bool nuw = false;
  2764. bool nsw = false;
  2765. bool exact = false;
  2766. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2767. if (const OverflowingBinaryOperator *OFBinOp =
  2768. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2769. nuw = OFBinOp->hasNoUnsignedWrap();
  2770. nsw = OFBinOp->hasNoSignedWrap();
  2771. }
  2772. if (const PossiblyExactOperator *ExactOp =
  2773. dyn_cast<const PossiblyExactOperator>(&I))
  2774. exact = ExactOp->isExact();
  2775. }
  2776. SDNodeFlags Flags;
  2777. Flags.setExact(exact);
  2778. Flags.setNoSignedWrap(nsw);
  2779. Flags.setNoUnsignedWrap(nuw);
  2780. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2781. Flags);
  2782. setValue(&I, Res);
  2783. }
  2784. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2785. SDValue Op1 = getValue(I.getOperand(0));
  2786. SDValue Op2 = getValue(I.getOperand(1));
  2787. SDNodeFlags Flags;
  2788. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2789. cast<PossiblyExactOperator>(&I)->isExact());
  2790. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2791. Op2, Flags));
  2792. }
  2793. void SelectionDAGBuilder::visitICmp(const User &I) {
  2794. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2795. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2796. predicate = IC->getPredicate();
  2797. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2798. predicate = ICmpInst::Predicate(IC->getPredicate());
  2799. SDValue Op1 = getValue(I.getOperand(0));
  2800. SDValue Op2 = getValue(I.getOperand(1));
  2801. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2802. auto &TLI = DAG.getTargetLoweringInfo();
  2803. EVT MemVT =
  2804. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2805. // If a pointer's DAG type is larger than its memory type then the DAG values
  2806. // are zero-extended. This breaks signed comparisons so truncate back to the
  2807. // underlying type before doing the compare.
  2808. if (Op1.getValueType() != MemVT) {
  2809. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2810. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2811. }
  2812. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2813. I.getType());
  2814. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2815. }
  2816. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2817. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2818. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2819. predicate = FC->getPredicate();
  2820. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2821. predicate = FCmpInst::Predicate(FC->getPredicate());
  2822. SDValue Op1 = getValue(I.getOperand(0));
  2823. SDValue Op2 = getValue(I.getOperand(1));
  2824. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2825. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2826. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2827. Condition = getFCmpCodeWithoutNaN(Condition);
  2828. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2829. I.getType());
  2830. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2831. }
  2832. // Check if the condition of the select has one use or two users that are both
  2833. // selects with the same condition.
  2834. static bool hasOnlySelectUsers(const Value *Cond) {
  2835. return llvm::all_of(Cond->users(), [](const Value *V) {
  2836. return isa<SelectInst>(V);
  2837. });
  2838. }
  2839. void SelectionDAGBuilder::visitSelect(const User &I) {
  2840. SmallVector<EVT, 4> ValueVTs;
  2841. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2842. ValueVTs);
  2843. unsigned NumValues = ValueVTs.size();
  2844. if (NumValues == 0) return;
  2845. SmallVector<SDValue, 4> Values(NumValues);
  2846. SDValue Cond = getValue(I.getOperand(0));
  2847. SDValue LHSVal = getValue(I.getOperand(1));
  2848. SDValue RHSVal = getValue(I.getOperand(2));
  2849. auto BaseOps = {Cond};
  2850. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2851. ISD::VSELECT : ISD::SELECT;
  2852. bool IsUnaryAbs = false;
  2853. // Min/max matching is only viable if all output VTs are the same.
  2854. if (is_splat(ValueVTs)) {
  2855. EVT VT = ValueVTs[0];
  2856. LLVMContext &Ctx = *DAG.getContext();
  2857. auto &TLI = DAG.getTargetLoweringInfo();
  2858. // We care about the legality of the operation after it has been type
  2859. // legalized.
  2860. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2861. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2862. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2863. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2864. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2865. // min/max is legal on the scalar type.
  2866. bool UseScalarMinMax = VT.isVector() &&
  2867. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2868. Value *LHS, *RHS;
  2869. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2870. ISD::NodeType Opc = ISD::DELETED_NODE;
  2871. switch (SPR.Flavor) {
  2872. case SPF_UMAX: Opc = ISD::UMAX; break;
  2873. case SPF_UMIN: Opc = ISD::UMIN; break;
  2874. case SPF_SMAX: Opc = ISD::SMAX; break;
  2875. case SPF_SMIN: Opc = ISD::SMIN; break;
  2876. case SPF_FMINNUM:
  2877. switch (SPR.NaNBehavior) {
  2878. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2879. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2880. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2881. case SPNB_RETURNS_ANY: {
  2882. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2883. Opc = ISD::FMINNUM;
  2884. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2885. Opc = ISD::FMINIMUM;
  2886. else if (UseScalarMinMax)
  2887. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2888. ISD::FMINNUM : ISD::FMINIMUM;
  2889. break;
  2890. }
  2891. }
  2892. break;
  2893. case SPF_FMAXNUM:
  2894. switch (SPR.NaNBehavior) {
  2895. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2896. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2897. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2898. case SPNB_RETURNS_ANY:
  2899. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2900. Opc = ISD::FMAXNUM;
  2901. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2902. Opc = ISD::FMAXIMUM;
  2903. else if (UseScalarMinMax)
  2904. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2905. ISD::FMAXNUM : ISD::FMAXIMUM;
  2906. break;
  2907. }
  2908. break;
  2909. case SPF_ABS:
  2910. IsUnaryAbs = true;
  2911. Opc = ISD::ABS;
  2912. break;
  2913. case SPF_NABS:
  2914. // TODO: we need to produce sub(0, abs(X)).
  2915. default: break;
  2916. }
  2917. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2918. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2919. (UseScalarMinMax &&
  2920. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2921. // If the underlying comparison instruction is used by any other
  2922. // instruction, the consumed instructions won't be destroyed, so it is
  2923. // not profitable to convert to a min/max.
  2924. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2925. OpCode = Opc;
  2926. LHSVal = getValue(LHS);
  2927. RHSVal = getValue(RHS);
  2928. BaseOps = {};
  2929. }
  2930. if (IsUnaryAbs) {
  2931. OpCode = Opc;
  2932. LHSVal = getValue(LHS);
  2933. BaseOps = {};
  2934. }
  2935. }
  2936. if (IsUnaryAbs) {
  2937. for (unsigned i = 0; i != NumValues; ++i) {
  2938. Values[i] =
  2939. DAG.getNode(OpCode, getCurSDLoc(),
  2940. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2941. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2942. }
  2943. } else {
  2944. for (unsigned i = 0; i != NumValues; ++i) {
  2945. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2946. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2947. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2948. Values[i] = DAG.getNode(
  2949. OpCode, getCurSDLoc(),
  2950. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2951. }
  2952. }
  2953. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2954. DAG.getVTList(ValueVTs), Values));
  2955. }
  2956. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2957. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2958. SDValue N = getValue(I.getOperand(0));
  2959. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2960. I.getType());
  2961. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2962. }
  2963. void SelectionDAGBuilder::visitZExt(const User &I) {
  2964. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2965. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2966. SDValue N = getValue(I.getOperand(0));
  2967. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2968. I.getType());
  2969. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2970. }
  2971. void SelectionDAGBuilder::visitSExt(const User &I) {
  2972. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2973. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2974. SDValue N = getValue(I.getOperand(0));
  2975. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2976. I.getType());
  2977. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2978. }
  2979. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2980. // FPTrunc is never a no-op cast, no need to check
  2981. SDValue N = getValue(I.getOperand(0));
  2982. SDLoc dl = getCurSDLoc();
  2983. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2984. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2985. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2986. DAG.getTargetConstant(
  2987. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2988. }
  2989. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2990. // FPExt is never a no-op cast, no need to check
  2991. SDValue N = getValue(I.getOperand(0));
  2992. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2993. I.getType());
  2994. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2995. }
  2996. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2997. // FPToUI is never a no-op cast, no need to check
  2998. SDValue N = getValue(I.getOperand(0));
  2999. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3000. I.getType());
  3001. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3002. }
  3003. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3004. // FPToSI is never a no-op cast, no need to check
  3005. SDValue N = getValue(I.getOperand(0));
  3006. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3007. I.getType());
  3008. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3009. }
  3010. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3011. // UIToFP is never a no-op cast, no need to check
  3012. SDValue N = getValue(I.getOperand(0));
  3013. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3014. I.getType());
  3015. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3016. }
  3017. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3018. // SIToFP is never a no-op cast, no need to check
  3019. SDValue N = getValue(I.getOperand(0));
  3020. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3021. I.getType());
  3022. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3023. }
  3024. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3025. // What to do depends on the size of the integer and the size of the pointer.
  3026. // We can either truncate, zero extend, or no-op, accordingly.
  3027. SDValue N = getValue(I.getOperand(0));
  3028. auto &TLI = DAG.getTargetLoweringInfo();
  3029. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3030. I.getType());
  3031. EVT PtrMemVT =
  3032. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3033. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3034. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3035. setValue(&I, N);
  3036. }
  3037. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3038. // What to do depends on the size of the integer and the size of the pointer.
  3039. // We can either truncate, zero extend, or no-op, accordingly.
  3040. SDValue N = getValue(I.getOperand(0));
  3041. auto &TLI = DAG.getTargetLoweringInfo();
  3042. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3043. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3044. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3045. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3046. setValue(&I, N);
  3047. }
  3048. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3049. SDValue N = getValue(I.getOperand(0));
  3050. SDLoc dl = getCurSDLoc();
  3051. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3052. I.getType());
  3053. // BitCast assures us that source and destination are the same size so this is
  3054. // either a BITCAST or a no-op.
  3055. if (DestVT != N.getValueType())
  3056. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3057. DestVT, N)); // convert types.
  3058. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3059. // might fold any kind of constant expression to an integer constant and that
  3060. // is not what we are looking for. Only recognize a bitcast of a genuine
  3061. // constant integer as an opaque constant.
  3062. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3063. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3064. /*isOpaque*/true));
  3065. else
  3066. setValue(&I, N); // noop cast.
  3067. }
  3068. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3069. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3070. const Value *SV = I.getOperand(0);
  3071. SDValue N = getValue(SV);
  3072. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3073. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3074. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3075. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3076. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3077. setValue(&I, N);
  3078. }
  3079. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3080. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3081. SDValue InVec = getValue(I.getOperand(0));
  3082. SDValue InVal = getValue(I.getOperand(1));
  3083. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3084. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3085. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3086. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3087. InVec, InVal, InIdx));
  3088. }
  3089. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3090. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3091. SDValue InVec = getValue(I.getOperand(0));
  3092. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3093. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3094. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3095. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3096. InVec, InIdx));
  3097. }
  3098. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3099. SDValue Src1 = getValue(I.getOperand(0));
  3100. SDValue Src2 = getValue(I.getOperand(1));
  3101. SDLoc DL = getCurSDLoc();
  3102. SmallVector<int, 8> Mask;
  3103. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3104. unsigned MaskNumElts = Mask.size();
  3105. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3106. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3107. EVT SrcVT = Src1.getValueType();
  3108. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3109. if (SrcNumElts == MaskNumElts) {
  3110. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3111. return;
  3112. }
  3113. // Normalize the shuffle vector since mask and vector length don't match.
  3114. if (SrcNumElts < MaskNumElts) {
  3115. // Mask is longer than the source vectors. We can use concatenate vector to
  3116. // make the mask and vectors lengths match.
  3117. if (MaskNumElts % SrcNumElts == 0) {
  3118. // Mask length is a multiple of the source vector length.
  3119. // Check if the shuffle is some kind of concatenation of the input
  3120. // vectors.
  3121. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3122. bool IsConcat = true;
  3123. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3124. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3125. int Idx = Mask[i];
  3126. if (Idx < 0)
  3127. continue;
  3128. // Ensure the indices in each SrcVT sized piece are sequential and that
  3129. // the same source is used for the whole piece.
  3130. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3131. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3132. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3133. IsConcat = false;
  3134. break;
  3135. }
  3136. // Remember which source this index came from.
  3137. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3138. }
  3139. // The shuffle is concatenating multiple vectors together. Just emit
  3140. // a CONCAT_VECTORS operation.
  3141. if (IsConcat) {
  3142. SmallVector<SDValue, 8> ConcatOps;
  3143. for (auto Src : ConcatSrcs) {
  3144. if (Src < 0)
  3145. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3146. else if (Src == 0)
  3147. ConcatOps.push_back(Src1);
  3148. else
  3149. ConcatOps.push_back(Src2);
  3150. }
  3151. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3152. return;
  3153. }
  3154. }
  3155. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3156. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3157. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3158. PaddedMaskNumElts);
  3159. // Pad both vectors with undefs to make them the same length as the mask.
  3160. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3161. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3162. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3163. MOps1[0] = Src1;
  3164. MOps2[0] = Src2;
  3165. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3166. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3167. // Readjust mask for new input vector length.
  3168. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3169. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3170. int Idx = Mask[i];
  3171. if (Idx >= (int)SrcNumElts)
  3172. Idx -= SrcNumElts - PaddedMaskNumElts;
  3173. MappedOps[i] = Idx;
  3174. }
  3175. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3176. // If the concatenated vector was padded, extract a subvector with the
  3177. // correct number of elements.
  3178. if (MaskNumElts != PaddedMaskNumElts)
  3179. Result = DAG.getNode(
  3180. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3181. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3182. setValue(&I, Result);
  3183. return;
  3184. }
  3185. if (SrcNumElts > MaskNumElts) {
  3186. // Analyze the access pattern of the vector to see if we can extract
  3187. // two subvectors and do the shuffle.
  3188. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3189. bool CanExtract = true;
  3190. for (int Idx : Mask) {
  3191. unsigned Input = 0;
  3192. if (Idx < 0)
  3193. continue;
  3194. if (Idx >= (int)SrcNumElts) {
  3195. Input = 1;
  3196. Idx -= SrcNumElts;
  3197. }
  3198. // If all the indices come from the same MaskNumElts sized portion of
  3199. // the sources we can use extract. Also make sure the extract wouldn't
  3200. // extract past the end of the source.
  3201. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3202. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3203. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3204. CanExtract = false;
  3205. // Make sure we always update StartIdx as we use it to track if all
  3206. // elements are undef.
  3207. StartIdx[Input] = NewStartIdx;
  3208. }
  3209. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3210. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3211. return;
  3212. }
  3213. if (CanExtract) {
  3214. // Extract appropriate subvector and generate a vector shuffle
  3215. for (unsigned Input = 0; Input < 2; ++Input) {
  3216. SDValue &Src = Input == 0 ? Src1 : Src2;
  3217. if (StartIdx[Input] < 0)
  3218. Src = DAG.getUNDEF(VT);
  3219. else {
  3220. Src = DAG.getNode(
  3221. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3222. DAG.getConstant(StartIdx[Input], DL,
  3223. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3224. }
  3225. }
  3226. // Calculate new mask.
  3227. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3228. for (int &Idx : MappedOps) {
  3229. if (Idx >= (int)SrcNumElts)
  3230. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3231. else if (Idx >= 0)
  3232. Idx -= StartIdx[0];
  3233. }
  3234. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3235. return;
  3236. }
  3237. }
  3238. // We can't use either concat vectors or extract subvectors so fall back to
  3239. // replacing the shuffle with extract and build vector.
  3240. // to insert and build vector.
  3241. EVT EltVT = VT.getVectorElementType();
  3242. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3243. SmallVector<SDValue,8> Ops;
  3244. for (int Idx : Mask) {
  3245. SDValue Res;
  3246. if (Idx < 0) {
  3247. Res = DAG.getUNDEF(EltVT);
  3248. } else {
  3249. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3250. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3251. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3252. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3253. }
  3254. Ops.push_back(Res);
  3255. }
  3256. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3257. }
  3258. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3259. ArrayRef<unsigned> Indices;
  3260. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3261. Indices = IV->getIndices();
  3262. else
  3263. Indices = cast<ConstantExpr>(&I)->getIndices();
  3264. const Value *Op0 = I.getOperand(0);
  3265. const Value *Op1 = I.getOperand(1);
  3266. Type *AggTy = I.getType();
  3267. Type *ValTy = Op1->getType();
  3268. bool IntoUndef = isa<UndefValue>(Op0);
  3269. bool FromUndef = isa<UndefValue>(Op1);
  3270. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3271. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3272. SmallVector<EVT, 4> AggValueVTs;
  3273. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3274. SmallVector<EVT, 4> ValValueVTs;
  3275. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3276. unsigned NumAggValues = AggValueVTs.size();
  3277. unsigned NumValValues = ValValueVTs.size();
  3278. SmallVector<SDValue, 4> Values(NumAggValues);
  3279. // Ignore an insertvalue that produces an empty object
  3280. if (!NumAggValues) {
  3281. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3282. return;
  3283. }
  3284. SDValue Agg = getValue(Op0);
  3285. unsigned i = 0;
  3286. // Copy the beginning value(s) from the original aggregate.
  3287. for (; i != LinearIndex; ++i)
  3288. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3289. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3290. // Copy values from the inserted value(s).
  3291. if (NumValValues) {
  3292. SDValue Val = getValue(Op1);
  3293. for (; i != LinearIndex + NumValValues; ++i)
  3294. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3295. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3296. }
  3297. // Copy remaining value(s) from the original aggregate.
  3298. for (; i != NumAggValues; ++i)
  3299. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3300. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3301. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3302. DAG.getVTList(AggValueVTs), Values));
  3303. }
  3304. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3305. ArrayRef<unsigned> Indices;
  3306. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3307. Indices = EV->getIndices();
  3308. else
  3309. Indices = cast<ConstantExpr>(&I)->getIndices();
  3310. const Value *Op0 = I.getOperand(0);
  3311. Type *AggTy = Op0->getType();
  3312. Type *ValTy = I.getType();
  3313. bool OutOfUndef = isa<UndefValue>(Op0);
  3314. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3315. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3316. SmallVector<EVT, 4> ValValueVTs;
  3317. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3318. unsigned NumValValues = ValValueVTs.size();
  3319. // Ignore a extractvalue that produces an empty object
  3320. if (!NumValValues) {
  3321. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3322. return;
  3323. }
  3324. SmallVector<SDValue, 4> Values(NumValValues);
  3325. SDValue Agg = getValue(Op0);
  3326. // Copy out the selected value(s).
  3327. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3328. Values[i - LinearIndex] =
  3329. OutOfUndef ?
  3330. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3331. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3332. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3333. DAG.getVTList(ValValueVTs), Values));
  3334. }
  3335. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3336. Value *Op0 = I.getOperand(0);
  3337. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3338. // element which holds a pointer.
  3339. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3340. SDValue N = getValue(Op0);
  3341. SDLoc dl = getCurSDLoc();
  3342. auto &TLI = DAG.getTargetLoweringInfo();
  3343. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3344. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3345. // Normalize Vector GEP - all scalar operands should be converted to the
  3346. // splat vector.
  3347. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3348. I.getType()->getVectorNumElements() : 0;
  3349. if (VectorWidth && !N.getValueType().isVector()) {
  3350. LLVMContext &Context = *DAG.getContext();
  3351. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3352. N = DAG.getSplatBuildVector(VT, dl, N);
  3353. }
  3354. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3355. GTI != E; ++GTI) {
  3356. const Value *Idx = GTI.getOperand();
  3357. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3358. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3359. if (Field) {
  3360. // N = N + Offset
  3361. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3362. // In an inbounds GEP with an offset that is nonnegative even when
  3363. // interpreted as signed, assume there is no unsigned overflow.
  3364. SDNodeFlags Flags;
  3365. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3366. Flags.setNoUnsignedWrap(true);
  3367. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3368. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3369. }
  3370. } else {
  3371. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3372. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3373. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3374. // If this is a scalar constant or a splat vector of constants,
  3375. // handle it quickly.
  3376. const auto *C = dyn_cast<Constant>(Idx);
  3377. if (C && isa<VectorType>(C->getType()))
  3378. C = C->getSplatValue();
  3379. if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
  3380. if (CI->isZero())
  3381. continue;
  3382. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3383. LLVMContext &Context = *DAG.getContext();
  3384. SDValue OffsVal = VectorWidth ?
  3385. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3386. DAG.getConstant(Offs, dl, IdxTy);
  3387. // In an inbounds GEP with an offset that is nonnegative even when
  3388. // interpreted as signed, assume there is no unsigned overflow.
  3389. SDNodeFlags Flags;
  3390. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3391. Flags.setNoUnsignedWrap(true);
  3392. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3393. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3394. continue;
  3395. }
  3396. // N = N + Idx * ElementSize;
  3397. SDValue IdxN = getValue(Idx);
  3398. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3399. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3400. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3401. }
  3402. // If the index is smaller or larger than intptr_t, truncate or extend
  3403. // it.
  3404. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3405. // If this is a multiply by a power of two, turn it into a shl
  3406. // immediately. This is a very common case.
  3407. if (ElementSize != 1) {
  3408. if (ElementSize.isPowerOf2()) {
  3409. unsigned Amt = ElementSize.logBase2();
  3410. IdxN = DAG.getNode(ISD::SHL, dl,
  3411. N.getValueType(), IdxN,
  3412. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3413. } else {
  3414. SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
  3415. IdxN.getValueType());
  3416. IdxN = DAG.getNode(ISD::MUL, dl,
  3417. N.getValueType(), IdxN, Scale);
  3418. }
  3419. }
  3420. N = DAG.getNode(ISD::ADD, dl,
  3421. N.getValueType(), N, IdxN);
  3422. }
  3423. }
  3424. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3425. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3426. setValue(&I, N);
  3427. }
  3428. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3429. // If this is a fixed sized alloca in the entry block of the function,
  3430. // allocate it statically on the stack.
  3431. if (FuncInfo.StaticAllocaMap.count(&I))
  3432. return; // getValue will auto-populate this.
  3433. SDLoc dl = getCurSDLoc();
  3434. Type *Ty = I.getAllocatedType();
  3435. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3436. auto &DL = DAG.getDataLayout();
  3437. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3438. unsigned Align =
  3439. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3440. SDValue AllocSize = getValue(I.getArraySize());
  3441. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3442. if (AllocSize.getValueType() != IntPtr)
  3443. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3444. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3445. AllocSize,
  3446. DAG.getConstant(TySize, dl, IntPtr));
  3447. // Handle alignment. If the requested alignment is less than or equal to
  3448. // the stack alignment, ignore it. If the size is greater than or equal to
  3449. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3450. unsigned StackAlign =
  3451. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3452. if (Align <= StackAlign)
  3453. Align = 0;
  3454. // Round the size of the allocation up to the stack alignment size
  3455. // by add SA-1 to the size. This doesn't overflow because we're computing
  3456. // an address inside an alloca.
  3457. SDNodeFlags Flags;
  3458. Flags.setNoUnsignedWrap(true);
  3459. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3460. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3461. // Mask out the low bits for alignment purposes.
  3462. AllocSize =
  3463. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3464. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3465. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3466. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3467. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3468. setValue(&I, DSA);
  3469. DAG.setRoot(DSA.getValue(1));
  3470. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3471. }
  3472. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3473. if (I.isAtomic())
  3474. return visitAtomicLoad(I);
  3475. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3476. const Value *SV = I.getOperand(0);
  3477. if (TLI.supportSwiftError()) {
  3478. // Swifterror values can come from either a function parameter with
  3479. // swifterror attribute or an alloca with swifterror attribute.
  3480. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3481. if (Arg->hasSwiftErrorAttr())
  3482. return visitLoadFromSwiftError(I);
  3483. }
  3484. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3485. if (Alloca->isSwiftError())
  3486. return visitLoadFromSwiftError(I);
  3487. }
  3488. }
  3489. SDValue Ptr = getValue(SV);
  3490. Type *Ty = I.getType();
  3491. bool isVolatile = I.isVolatile();
  3492. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3493. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3494. bool isDereferenceable =
  3495. isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
  3496. unsigned Alignment = I.getAlignment();
  3497. AAMDNodes AAInfo;
  3498. I.getAAMetadata(AAInfo);
  3499. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3500. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3501. SmallVector<uint64_t, 4> Offsets;
  3502. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3503. unsigned NumValues = ValueVTs.size();
  3504. if (NumValues == 0)
  3505. return;
  3506. SDValue Root;
  3507. bool ConstantMemory = false;
  3508. if (isVolatile || NumValues > MaxParallelChains)
  3509. // Serialize volatile loads with other side effects.
  3510. Root = getRoot();
  3511. else if (AA &&
  3512. AA->pointsToConstantMemory(MemoryLocation(
  3513. SV,
  3514. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3515. AAInfo))) {
  3516. // Do not serialize (non-volatile) loads of constant memory with anything.
  3517. Root = DAG.getEntryNode();
  3518. ConstantMemory = true;
  3519. } else {
  3520. // Do not serialize non-volatile loads against each other.
  3521. Root = DAG.getRoot();
  3522. }
  3523. SDLoc dl = getCurSDLoc();
  3524. if (isVolatile)
  3525. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3526. // An aggregate load cannot wrap around the address space, so offsets to its
  3527. // parts don't wrap either.
  3528. SDNodeFlags Flags;
  3529. Flags.setNoUnsignedWrap(true);
  3530. SmallVector<SDValue, 4> Values(NumValues);
  3531. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3532. EVT PtrVT = Ptr.getValueType();
  3533. unsigned ChainI = 0;
  3534. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3535. // Serializing loads here may result in excessive register pressure, and
  3536. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3537. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3538. // they are side-effect free or do not alias. The optimizer should really
  3539. // avoid this case by converting large object/array copies to llvm.memcpy
  3540. // (MaxParallelChains should always remain as failsafe).
  3541. if (ChainI == MaxParallelChains) {
  3542. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3543. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3544. makeArrayRef(Chains.data(), ChainI));
  3545. Root = Chain;
  3546. ChainI = 0;
  3547. }
  3548. SDValue A = DAG.getNode(ISD::ADD, dl,
  3549. PtrVT, Ptr,
  3550. DAG.getConstant(Offsets[i], dl, PtrVT),
  3551. Flags);
  3552. auto MMOFlags = MachineMemOperand::MONone;
  3553. if (isVolatile)
  3554. MMOFlags |= MachineMemOperand::MOVolatile;
  3555. if (isNonTemporal)
  3556. MMOFlags |= MachineMemOperand::MONonTemporal;
  3557. if (isInvariant)
  3558. MMOFlags |= MachineMemOperand::MOInvariant;
  3559. if (isDereferenceable)
  3560. MMOFlags |= MachineMemOperand::MODereferenceable;
  3561. MMOFlags |= TLI.getMMOFlags(I);
  3562. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3563. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3564. MMOFlags, AAInfo, Ranges);
  3565. Chains[ChainI] = L.getValue(1);
  3566. if (MemVTs[i] != ValueVTs[i])
  3567. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3568. Values[i] = L;
  3569. }
  3570. if (!ConstantMemory) {
  3571. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3572. makeArrayRef(Chains.data(), ChainI));
  3573. if (isVolatile)
  3574. DAG.setRoot(Chain);
  3575. else
  3576. PendingLoads.push_back(Chain);
  3577. }
  3578. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3579. DAG.getVTList(ValueVTs), Values));
  3580. }
  3581. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3582. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3583. "call visitStoreToSwiftError when backend supports swifterror");
  3584. SmallVector<EVT, 4> ValueVTs;
  3585. SmallVector<uint64_t, 4> Offsets;
  3586. const Value *SrcV = I.getOperand(0);
  3587. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3588. SrcV->getType(), ValueVTs, &Offsets);
  3589. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3590. "expect a single EVT for swifterror");
  3591. SDValue Src = getValue(SrcV);
  3592. // Create a virtual register, then update the virtual register.
  3593. Register VReg =
  3594. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3595. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3596. // Chain can be getRoot or getControlRoot.
  3597. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3598. SDValue(Src.getNode(), Src.getResNo()));
  3599. DAG.setRoot(CopyNode);
  3600. }
  3601. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3602. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3603. "call visitLoadFromSwiftError when backend supports swifterror");
  3604. assert(!I.isVolatile() &&
  3605. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3606. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3607. "Support volatile, non temporal, invariant for load_from_swift_error");
  3608. const Value *SV = I.getOperand(0);
  3609. Type *Ty = I.getType();
  3610. AAMDNodes AAInfo;
  3611. I.getAAMetadata(AAInfo);
  3612. assert(
  3613. (!AA ||
  3614. !AA->pointsToConstantMemory(MemoryLocation(
  3615. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3616. AAInfo))) &&
  3617. "load_from_swift_error should not be constant memory");
  3618. SmallVector<EVT, 4> ValueVTs;
  3619. SmallVector<uint64_t, 4> Offsets;
  3620. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3621. ValueVTs, &Offsets);
  3622. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3623. "expect a single EVT for swifterror");
  3624. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3625. SDValue L = DAG.getCopyFromReg(
  3626. getRoot(), getCurSDLoc(),
  3627. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3628. setValue(&I, L);
  3629. }
  3630. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3631. if (I.isAtomic())
  3632. return visitAtomicStore(I);
  3633. const Value *SrcV = I.getOperand(0);
  3634. const Value *PtrV = I.getOperand(1);
  3635. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3636. if (TLI.supportSwiftError()) {
  3637. // Swifterror values can come from either a function parameter with
  3638. // swifterror attribute or an alloca with swifterror attribute.
  3639. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3640. if (Arg->hasSwiftErrorAttr())
  3641. return visitStoreToSwiftError(I);
  3642. }
  3643. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3644. if (Alloca->isSwiftError())
  3645. return visitStoreToSwiftError(I);
  3646. }
  3647. }
  3648. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3649. SmallVector<uint64_t, 4> Offsets;
  3650. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3651. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3652. unsigned NumValues = ValueVTs.size();
  3653. if (NumValues == 0)
  3654. return;
  3655. // Get the lowered operands. Note that we do this after
  3656. // checking if NumResults is zero, because with zero results
  3657. // the operands won't have values in the map.
  3658. SDValue Src = getValue(SrcV);
  3659. SDValue Ptr = getValue(PtrV);
  3660. SDValue Root = getRoot();
  3661. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3662. SDLoc dl = getCurSDLoc();
  3663. EVT PtrVT = Ptr.getValueType();
  3664. unsigned Alignment = I.getAlignment();
  3665. AAMDNodes AAInfo;
  3666. I.getAAMetadata(AAInfo);
  3667. auto MMOFlags = MachineMemOperand::MONone;
  3668. if (I.isVolatile())
  3669. MMOFlags |= MachineMemOperand::MOVolatile;
  3670. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3671. MMOFlags |= MachineMemOperand::MONonTemporal;
  3672. MMOFlags |= TLI.getMMOFlags(I);
  3673. // An aggregate load cannot wrap around the address space, so offsets to its
  3674. // parts don't wrap either.
  3675. SDNodeFlags Flags;
  3676. Flags.setNoUnsignedWrap(true);
  3677. unsigned ChainI = 0;
  3678. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3679. // See visitLoad comments.
  3680. if (ChainI == MaxParallelChains) {
  3681. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3682. makeArrayRef(Chains.data(), ChainI));
  3683. Root = Chain;
  3684. ChainI = 0;
  3685. }
  3686. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3687. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3688. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3689. if (MemVTs[i] != ValueVTs[i])
  3690. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3691. SDValue St =
  3692. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3693. Alignment, MMOFlags, AAInfo);
  3694. Chains[ChainI] = St;
  3695. }
  3696. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3697. makeArrayRef(Chains.data(), ChainI));
  3698. DAG.setRoot(StoreNode);
  3699. }
  3700. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3701. bool IsCompressing) {
  3702. SDLoc sdl = getCurSDLoc();
  3703. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3704. unsigned& Alignment) {
  3705. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3706. Src0 = I.getArgOperand(0);
  3707. Ptr = I.getArgOperand(1);
  3708. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3709. Mask = I.getArgOperand(3);
  3710. };
  3711. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3712. unsigned& Alignment) {
  3713. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3714. Src0 = I.getArgOperand(0);
  3715. Ptr = I.getArgOperand(1);
  3716. Mask = I.getArgOperand(2);
  3717. Alignment = 0;
  3718. };
  3719. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3720. unsigned Alignment;
  3721. if (IsCompressing)
  3722. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3723. else
  3724. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3725. SDValue Ptr = getValue(PtrOperand);
  3726. SDValue Src0 = getValue(Src0Operand);
  3727. SDValue Mask = getValue(MaskOperand);
  3728. EVT VT = Src0.getValueType();
  3729. if (!Alignment)
  3730. Alignment = DAG.getEVTAlignment(VT);
  3731. AAMDNodes AAInfo;
  3732. I.getAAMetadata(AAInfo);
  3733. MachineMemOperand *MMO =
  3734. DAG.getMachineFunction().
  3735. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3736. MachineMemOperand::MOStore, VT.getStoreSize(),
  3737. Alignment, AAInfo);
  3738. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3739. MMO, false /* Truncating */,
  3740. IsCompressing);
  3741. DAG.setRoot(StoreNode);
  3742. setValue(&I, StoreNode);
  3743. }
  3744. // Get a uniform base for the Gather/Scatter intrinsic.
  3745. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3746. // We try to represent it as a base pointer + vector of indices.
  3747. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3748. // The first operand of the GEP may be a single pointer or a vector of pointers
  3749. // Example:
  3750. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3751. // or
  3752. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3753. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3754. //
  3755. // When the first GEP operand is a single pointer - it is the uniform base we
  3756. // are looking for. If first operand of the GEP is a splat vector - we
  3757. // extract the splat value and use it as a uniform base.
  3758. // In all other cases the function returns 'false'.
  3759. static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
  3760. ISD::MemIndexType &IndexType, SDValue &Scale,
  3761. SelectionDAGBuilder *SDB) {
  3762. SelectionDAG& DAG = SDB->DAG;
  3763. LLVMContext &Context = *DAG.getContext();
  3764. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3765. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3766. if (!GEP)
  3767. return false;
  3768. const Value *GEPPtr = GEP->getPointerOperand();
  3769. if (!GEPPtr->getType()->isVectorTy())
  3770. Ptr = GEPPtr;
  3771. else if (!(Ptr = getSplatValue(GEPPtr)))
  3772. return false;
  3773. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3774. Value *IndexVal = GEP->getOperand(FinalIndex);
  3775. // Ensure all the other indices are 0.
  3776. for (unsigned i = 1; i < FinalIndex; ++i) {
  3777. auto *C = dyn_cast<Constant>(GEP->getOperand(i));
  3778. if (!C)
  3779. return false;
  3780. if (isa<VectorType>(C->getType()))
  3781. C = C->getSplatValue();
  3782. auto *CI = dyn_cast_or_null<ConstantInt>(C);
  3783. if (!CI || !CI->isZero())
  3784. return false;
  3785. }
  3786. // The operands of the GEP may be defined in another basic block.
  3787. // In this case we'll not find nodes for the operands.
  3788. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3789. return false;
  3790. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3791. const DataLayout &DL = DAG.getDataLayout();
  3792. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3793. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3794. Base = SDB->getValue(Ptr);
  3795. Index = SDB->getValue(IndexVal);
  3796. IndexType = ISD::SIGNED_SCALED;
  3797. if (!Index.getValueType().isVector()) {
  3798. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3799. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3800. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3801. }
  3802. return true;
  3803. }
  3804. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3805. SDLoc sdl = getCurSDLoc();
  3806. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3807. const Value *Ptr = I.getArgOperand(1);
  3808. SDValue Src0 = getValue(I.getArgOperand(0));
  3809. SDValue Mask = getValue(I.getArgOperand(3));
  3810. EVT VT = Src0.getValueType();
  3811. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3812. if (!Alignment)
  3813. Alignment = DAG.getEVTAlignment(VT);
  3814. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3815. AAMDNodes AAInfo;
  3816. I.getAAMetadata(AAInfo);
  3817. SDValue Base;
  3818. SDValue Index;
  3819. ISD::MemIndexType IndexType;
  3820. SDValue Scale;
  3821. const Value *BasePtr = Ptr;
  3822. bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
  3823. this);
  3824. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3825. MachineMemOperand *MMO = DAG.getMachineFunction().
  3826. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3827. MachineMemOperand::MOStore, VT.getStoreSize(),
  3828. Alignment, AAInfo);
  3829. if (!UniformBase) {
  3830. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3831. Index = getValue(Ptr);
  3832. IndexType = ISD::SIGNED_SCALED;
  3833. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3834. }
  3835. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3836. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3837. Ops, MMO, IndexType);
  3838. DAG.setRoot(Scatter);
  3839. setValue(&I, Scatter);
  3840. }
  3841. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3842. SDLoc sdl = getCurSDLoc();
  3843. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3844. unsigned& Alignment) {
  3845. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3846. Ptr = I.getArgOperand(0);
  3847. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3848. Mask = I.getArgOperand(2);
  3849. Src0 = I.getArgOperand(3);
  3850. };
  3851. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3852. unsigned& Alignment) {
  3853. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3854. Ptr = I.getArgOperand(0);
  3855. Alignment = 0;
  3856. Mask = I.getArgOperand(1);
  3857. Src0 = I.getArgOperand(2);
  3858. };
  3859. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3860. unsigned Alignment;
  3861. if (IsExpanding)
  3862. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3863. else
  3864. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3865. SDValue Ptr = getValue(PtrOperand);
  3866. SDValue Src0 = getValue(Src0Operand);
  3867. SDValue Mask = getValue(MaskOperand);
  3868. EVT VT = Src0.getValueType();
  3869. if (!Alignment)
  3870. Alignment = DAG.getEVTAlignment(VT);
  3871. AAMDNodes AAInfo;
  3872. I.getAAMetadata(AAInfo);
  3873. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3874. // Do not serialize masked loads of constant memory with anything.
  3875. bool AddToChain =
  3876. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3877. PtrOperand,
  3878. LocationSize::precise(
  3879. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3880. AAInfo));
  3881. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3882. MachineMemOperand *MMO =
  3883. DAG.getMachineFunction().
  3884. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3885. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3886. Alignment, AAInfo, Ranges);
  3887. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3888. ISD::NON_EXTLOAD, IsExpanding);
  3889. if (AddToChain)
  3890. PendingLoads.push_back(Load.getValue(1));
  3891. setValue(&I, Load);
  3892. }
  3893. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3894. SDLoc sdl = getCurSDLoc();
  3895. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3896. const Value *Ptr = I.getArgOperand(0);
  3897. SDValue Src0 = getValue(I.getArgOperand(3));
  3898. SDValue Mask = getValue(I.getArgOperand(2));
  3899. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3900. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3901. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3902. if (!Alignment)
  3903. Alignment = DAG.getEVTAlignment(VT);
  3904. AAMDNodes AAInfo;
  3905. I.getAAMetadata(AAInfo);
  3906. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3907. SDValue Root = DAG.getRoot();
  3908. SDValue Base;
  3909. SDValue Index;
  3910. ISD::MemIndexType IndexType;
  3911. SDValue Scale;
  3912. const Value *BasePtr = Ptr;
  3913. bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
  3914. this);
  3915. bool ConstantMemory = false;
  3916. if (UniformBase && AA &&
  3917. AA->pointsToConstantMemory(
  3918. MemoryLocation(BasePtr,
  3919. LocationSize::precise(
  3920. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3921. AAInfo))) {
  3922. // Do not serialize (non-volatile) loads of constant memory with anything.
  3923. Root = DAG.getEntryNode();
  3924. ConstantMemory = true;
  3925. }
  3926. MachineMemOperand *MMO =
  3927. DAG.getMachineFunction().
  3928. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3929. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3930. Alignment, AAInfo, Ranges);
  3931. if (!UniformBase) {
  3932. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3933. Index = getValue(Ptr);
  3934. IndexType = ISD::SIGNED_SCALED;
  3935. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3936. }
  3937. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3938. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3939. Ops, MMO, IndexType);
  3940. SDValue OutChain = Gather.getValue(1);
  3941. if (!ConstantMemory)
  3942. PendingLoads.push_back(OutChain);
  3943. setValue(&I, Gather);
  3944. }
  3945. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3946. SDLoc dl = getCurSDLoc();
  3947. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3948. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3949. SyncScope::ID SSID = I.getSyncScopeID();
  3950. SDValue InChain = getRoot();
  3951. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3952. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3953. auto Alignment = DAG.getEVTAlignment(MemVT);
  3954. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3955. if (I.isVolatile())
  3956. Flags |= MachineMemOperand::MOVolatile;
  3957. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3958. MachineFunction &MF = DAG.getMachineFunction();
  3959. MachineMemOperand *MMO =
  3960. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3961. Flags, MemVT.getStoreSize(), Alignment,
  3962. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3963. FailureOrdering);
  3964. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3965. dl, MemVT, VTs, InChain,
  3966. getValue(I.getPointerOperand()),
  3967. getValue(I.getCompareOperand()),
  3968. getValue(I.getNewValOperand()), MMO);
  3969. SDValue OutChain = L.getValue(2);
  3970. setValue(&I, L);
  3971. DAG.setRoot(OutChain);
  3972. }
  3973. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3974. SDLoc dl = getCurSDLoc();
  3975. ISD::NodeType NT;
  3976. switch (I.getOperation()) {
  3977. default: llvm_unreachable("Unknown atomicrmw operation");
  3978. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3979. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3980. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3981. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3982. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3983. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3984. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3985. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3986. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3987. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3988. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3989. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3990. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3991. }
  3992. AtomicOrdering Ordering = I.getOrdering();
  3993. SyncScope::ID SSID = I.getSyncScopeID();
  3994. SDValue InChain = getRoot();
  3995. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3996. auto Alignment = DAG.getEVTAlignment(MemVT);
  3997. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3998. if (I.isVolatile())
  3999. Flags |= MachineMemOperand::MOVolatile;
  4000. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  4001. MachineFunction &MF = DAG.getMachineFunction();
  4002. MachineMemOperand *MMO =
  4003. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4004. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  4005. nullptr, SSID, Ordering);
  4006. SDValue L =
  4007. DAG.getAtomic(NT, dl, MemVT, InChain,
  4008. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  4009. MMO);
  4010. SDValue OutChain = L.getValue(1);
  4011. setValue(&I, L);
  4012. DAG.setRoot(OutChain);
  4013. }
  4014. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4015. SDLoc dl = getCurSDLoc();
  4016. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4017. SDValue Ops[3];
  4018. Ops[0] = getRoot();
  4019. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  4020. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4021. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  4022. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4023. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  4024. }
  4025. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4026. SDLoc dl = getCurSDLoc();
  4027. AtomicOrdering Order = I.getOrdering();
  4028. SyncScope::ID SSID = I.getSyncScopeID();
  4029. SDValue InChain = getRoot();
  4030. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4031. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4032. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4033. if (!TLI.supportsUnalignedAtomics() &&
  4034. I.getAlignment() < MemVT.getSizeInBits() / 8)
  4035. report_fatal_error("Cannot generate unaligned atomic load");
  4036. auto Flags = MachineMemOperand::MOLoad;
  4037. if (I.isVolatile())
  4038. Flags |= MachineMemOperand::MOVolatile;
  4039. if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
  4040. Flags |= MachineMemOperand::MOInvariant;
  4041. if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
  4042. DAG.getDataLayout()))
  4043. Flags |= MachineMemOperand::MODereferenceable;
  4044. Flags |= TLI.getMMOFlags(I);
  4045. MachineMemOperand *MMO =
  4046. DAG.getMachineFunction().
  4047. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  4048. Flags, MemVT.getStoreSize(),
  4049. I.getAlignment() ? I.getAlignment() :
  4050. DAG.getEVTAlignment(MemVT),
  4051. AAMDNodes(), nullptr, SSID, Order);
  4052. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4053. SDValue L =
  4054. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4055. getValue(I.getPointerOperand()), MMO);
  4056. SDValue OutChain = L.getValue(1);
  4057. if (MemVT != VT)
  4058. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4059. setValue(&I, L);
  4060. DAG.setRoot(OutChain);
  4061. }
  4062. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4063. SDLoc dl = getCurSDLoc();
  4064. AtomicOrdering Ordering = I.getOrdering();
  4065. SyncScope::ID SSID = I.getSyncScopeID();
  4066. SDValue InChain = getRoot();
  4067. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4068. EVT MemVT =
  4069. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4070. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4071. report_fatal_error("Cannot generate unaligned atomic store");
  4072. auto Flags = MachineMemOperand::MOStore;
  4073. if (I.isVolatile())
  4074. Flags |= MachineMemOperand::MOVolatile;
  4075. Flags |= TLI.getMMOFlags(I);
  4076. MachineFunction &MF = DAG.getMachineFunction();
  4077. MachineMemOperand *MMO =
  4078. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4079. MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4080. nullptr, SSID, Ordering);
  4081. SDValue Val = getValue(I.getValueOperand());
  4082. if (Val.getValueType() != MemVT)
  4083. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4084. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4085. getValue(I.getPointerOperand()), Val, MMO);
  4086. DAG.setRoot(OutChain);
  4087. }
  4088. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4089. /// node.
  4090. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4091. unsigned Intrinsic) {
  4092. // Ignore the callsite's attributes. A specific call site may be marked with
  4093. // readnone, but the lowering code will expect the chain based on the
  4094. // definition.
  4095. const Function *F = I.getCalledFunction();
  4096. bool HasChain = !F->doesNotAccessMemory();
  4097. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4098. // Build the operand list.
  4099. SmallVector<SDValue, 8> Ops;
  4100. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4101. if (OnlyLoad) {
  4102. // We don't need to serialize loads against other loads.
  4103. Ops.push_back(DAG.getRoot());
  4104. } else {
  4105. Ops.push_back(getRoot());
  4106. }
  4107. }
  4108. // Info is set by getTgtMemInstrinsic
  4109. TargetLowering::IntrinsicInfo Info;
  4110. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4111. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4112. DAG.getMachineFunction(),
  4113. Intrinsic);
  4114. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4115. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4116. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4117. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4118. TLI.getPointerTy(DAG.getDataLayout())));
  4119. // Add all operands of the call to the operand list.
  4120. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4121. SDValue Op = getValue(I.getArgOperand(i));
  4122. Ops.push_back(Op);
  4123. }
  4124. SmallVector<EVT, 4> ValueVTs;
  4125. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4126. if (HasChain)
  4127. ValueVTs.push_back(MVT::Other);
  4128. SDVTList VTs = DAG.getVTList(ValueVTs);
  4129. // Create the node.
  4130. SDValue Result;
  4131. if (IsTgtIntrinsic) {
  4132. // This is target intrinsic that touches memory
  4133. AAMDNodes AAInfo;
  4134. I.getAAMetadata(AAInfo);
  4135. Result = DAG.getMemIntrinsicNode(
  4136. Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
  4137. MachinePointerInfo(Info.ptrVal, Info.offset),
  4138. Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
  4139. } else if (!HasChain) {
  4140. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4141. } else if (!I.getType()->isVoidTy()) {
  4142. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4143. } else {
  4144. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4145. }
  4146. if (HasChain) {
  4147. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4148. if (OnlyLoad)
  4149. PendingLoads.push_back(Chain);
  4150. else
  4151. DAG.setRoot(Chain);
  4152. }
  4153. if (!I.getType()->isVoidTy()) {
  4154. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4155. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4156. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4157. } else
  4158. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4159. setValue(&I, Result);
  4160. }
  4161. }
  4162. /// GetSignificand - Get the significand and build it into a floating-point
  4163. /// number with exponent of 1:
  4164. ///
  4165. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4166. ///
  4167. /// where Op is the hexadecimal representation of floating point value.
  4168. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4169. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4170. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4171. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4172. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4173. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4174. }
  4175. /// GetExponent - Get the exponent:
  4176. ///
  4177. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4178. ///
  4179. /// where Op is the hexadecimal representation of floating point value.
  4180. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4181. const TargetLowering &TLI, const SDLoc &dl) {
  4182. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4183. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4184. SDValue t1 = DAG.getNode(
  4185. ISD::SRL, dl, MVT::i32, t0,
  4186. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4187. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4188. DAG.getConstant(127, dl, MVT::i32));
  4189. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4190. }
  4191. /// getF32Constant - Get 32-bit floating point constant.
  4192. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4193. const SDLoc &dl) {
  4194. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4195. MVT::f32);
  4196. }
  4197. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4198. SelectionDAG &DAG) {
  4199. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4200. // IntegerPartOfX = ((int32_t)(t0);
  4201. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4202. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4203. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4204. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4205. // IntegerPartOfX <<= 23;
  4206. IntegerPartOfX = DAG.getNode(
  4207. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4208. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4209. DAG.getDataLayout())));
  4210. SDValue TwoToFractionalPartOfX;
  4211. if (LimitFloatPrecision <= 6) {
  4212. // For floating-point precision of 6:
  4213. //
  4214. // TwoToFractionalPartOfX =
  4215. // 0.997535578f +
  4216. // (0.735607626f + 0.252464424f * x) * x;
  4217. //
  4218. // error 0.0144103317, which is 6 bits
  4219. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4220. getF32Constant(DAG, 0x3e814304, dl));
  4221. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4222. getF32Constant(DAG, 0x3f3c50c8, dl));
  4223. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4224. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4225. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4226. } else if (LimitFloatPrecision <= 12) {
  4227. // For floating-point precision of 12:
  4228. //
  4229. // TwoToFractionalPartOfX =
  4230. // 0.999892986f +
  4231. // (0.696457318f +
  4232. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4233. //
  4234. // error 0.000107046256, which is 13 to 14 bits
  4235. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4236. getF32Constant(DAG, 0x3da235e3, dl));
  4237. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4238. getF32Constant(DAG, 0x3e65b8f3, dl));
  4239. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4240. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4241. getF32Constant(DAG, 0x3f324b07, dl));
  4242. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4243. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4244. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4245. } else { // LimitFloatPrecision <= 18
  4246. // For floating-point precision of 18:
  4247. //
  4248. // TwoToFractionalPartOfX =
  4249. // 0.999999982f +
  4250. // (0.693148872f +
  4251. // (0.240227044f +
  4252. // (0.554906021e-1f +
  4253. // (0.961591928e-2f +
  4254. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4255. // error 2.47208000*10^(-7), which is better than 18 bits
  4256. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4257. getF32Constant(DAG, 0x3924b03e, dl));
  4258. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4259. getF32Constant(DAG, 0x3ab24b87, dl));
  4260. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4261. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4262. getF32Constant(DAG, 0x3c1d8c17, dl));
  4263. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4264. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4265. getF32Constant(DAG, 0x3d634a1d, dl));
  4266. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4267. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4268. getF32Constant(DAG, 0x3e75fe14, dl));
  4269. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4270. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4271. getF32Constant(DAG, 0x3f317234, dl));
  4272. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4273. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4274. getF32Constant(DAG, 0x3f800000, dl));
  4275. }
  4276. // Add the exponent into the result in integer domain.
  4277. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4278. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4279. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4280. }
  4281. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4282. /// limited-precision mode.
  4283. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4284. const TargetLowering &TLI) {
  4285. if (Op.getValueType() == MVT::f32 &&
  4286. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4287. // Put the exponent in the right bit position for later addition to the
  4288. // final result:
  4289. //
  4290. // #define LOG2OFe 1.4426950f
  4291. // t0 = Op * LOG2OFe
  4292. // TODO: What fast-math-flags should be set here?
  4293. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4294. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4295. return getLimitedPrecisionExp2(t0, dl, DAG);
  4296. }
  4297. // No special expansion.
  4298. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4299. }
  4300. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4301. /// limited-precision mode.
  4302. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4303. const TargetLowering &TLI) {
  4304. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4305. if (Op.getValueType() == MVT::f32 &&
  4306. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4307. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4308. // Scale the exponent by log(2) [0.69314718f].
  4309. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4310. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4311. getF32Constant(DAG, 0x3f317218, dl));
  4312. // Get the significand and build it into a floating-point number with
  4313. // exponent of 1.
  4314. SDValue X = GetSignificand(DAG, Op1, dl);
  4315. SDValue LogOfMantissa;
  4316. if (LimitFloatPrecision <= 6) {
  4317. // For floating-point precision of 6:
  4318. //
  4319. // LogofMantissa =
  4320. // -1.1609546f +
  4321. // (1.4034025f - 0.23903021f * x) * x;
  4322. //
  4323. // error 0.0034276066, which is better than 8 bits
  4324. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4325. getF32Constant(DAG, 0xbe74c456, dl));
  4326. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4327. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4328. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4329. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4330. getF32Constant(DAG, 0x3f949a29, dl));
  4331. } else if (LimitFloatPrecision <= 12) {
  4332. // For floating-point precision of 12:
  4333. //
  4334. // LogOfMantissa =
  4335. // -1.7417939f +
  4336. // (2.8212026f +
  4337. // (-1.4699568f +
  4338. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4339. //
  4340. // error 0.000061011436, which is 14 bits
  4341. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4342. getF32Constant(DAG, 0xbd67b6d6, dl));
  4343. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4344. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4345. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4346. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4347. getF32Constant(DAG, 0x3fbc278b, dl));
  4348. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4349. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4350. getF32Constant(DAG, 0x40348e95, dl));
  4351. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4352. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4353. getF32Constant(DAG, 0x3fdef31a, dl));
  4354. } else { // LimitFloatPrecision <= 18
  4355. // For floating-point precision of 18:
  4356. //
  4357. // LogOfMantissa =
  4358. // -2.1072184f +
  4359. // (4.2372794f +
  4360. // (-3.7029485f +
  4361. // (2.2781945f +
  4362. // (-0.87823314f +
  4363. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4364. //
  4365. // error 0.0000023660568, which is better than 18 bits
  4366. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4367. getF32Constant(DAG, 0xbc91e5ac, dl));
  4368. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4369. getF32Constant(DAG, 0x3e4350aa, dl));
  4370. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4371. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4372. getF32Constant(DAG, 0x3f60d3e3, dl));
  4373. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4374. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4375. getF32Constant(DAG, 0x4011cdf0, dl));
  4376. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4377. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4378. getF32Constant(DAG, 0x406cfd1c, dl));
  4379. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4380. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4381. getF32Constant(DAG, 0x408797cb, dl));
  4382. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4383. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4384. getF32Constant(DAG, 0x4006dcab, dl));
  4385. }
  4386. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4387. }
  4388. // No special expansion.
  4389. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4390. }
  4391. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4392. /// limited-precision mode.
  4393. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4394. const TargetLowering &TLI) {
  4395. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4396. if (Op.getValueType() == MVT::f32 &&
  4397. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4398. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4399. // Get the exponent.
  4400. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4401. // Get the significand and build it into a floating-point number with
  4402. // exponent of 1.
  4403. SDValue X = GetSignificand(DAG, Op1, dl);
  4404. // Different possible minimax approximations of significand in
  4405. // floating-point for various degrees of accuracy over [1,2].
  4406. SDValue Log2ofMantissa;
  4407. if (LimitFloatPrecision <= 6) {
  4408. // For floating-point precision of 6:
  4409. //
  4410. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4411. //
  4412. // error 0.0049451742, which is more than 7 bits
  4413. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4414. getF32Constant(DAG, 0xbeb08fe0, dl));
  4415. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4416. getF32Constant(DAG, 0x40019463, dl));
  4417. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4418. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4419. getF32Constant(DAG, 0x3fd6633d, dl));
  4420. } else if (LimitFloatPrecision <= 12) {
  4421. // For floating-point precision of 12:
  4422. //
  4423. // Log2ofMantissa =
  4424. // -2.51285454f +
  4425. // (4.07009056f +
  4426. // (-2.12067489f +
  4427. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4428. //
  4429. // error 0.0000876136000, which is better than 13 bits
  4430. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4431. getF32Constant(DAG, 0xbda7262e, dl));
  4432. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4433. getF32Constant(DAG, 0x3f25280b, dl));
  4434. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4435. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4436. getF32Constant(DAG, 0x4007b923, dl));
  4437. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4438. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4439. getF32Constant(DAG, 0x40823e2f, dl));
  4440. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4441. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4442. getF32Constant(DAG, 0x4020d29c, dl));
  4443. } else { // LimitFloatPrecision <= 18
  4444. // For floating-point precision of 18:
  4445. //
  4446. // Log2ofMantissa =
  4447. // -3.0400495f +
  4448. // (6.1129976f +
  4449. // (-5.3420409f +
  4450. // (3.2865683f +
  4451. // (-1.2669343f +
  4452. // (0.27515199f -
  4453. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4454. //
  4455. // error 0.0000018516, which is better than 18 bits
  4456. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4457. getF32Constant(DAG, 0xbcd2769e, dl));
  4458. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4459. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4460. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4461. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4462. getF32Constant(DAG, 0x3fa22ae7, dl));
  4463. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4464. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4465. getF32Constant(DAG, 0x40525723, dl));
  4466. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4467. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4468. getF32Constant(DAG, 0x40aaf200, dl));
  4469. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4470. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4471. getF32Constant(DAG, 0x40c39dad, dl));
  4472. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4473. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4474. getF32Constant(DAG, 0x4042902c, dl));
  4475. }
  4476. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4477. }
  4478. // No special expansion.
  4479. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4480. }
  4481. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4482. /// limited-precision mode.
  4483. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4484. const TargetLowering &TLI) {
  4485. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4486. if (Op.getValueType() == MVT::f32 &&
  4487. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4488. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4489. // Scale the exponent by log10(2) [0.30102999f].
  4490. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4491. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4492. getF32Constant(DAG, 0x3e9a209a, dl));
  4493. // Get the significand and build it into a floating-point number with
  4494. // exponent of 1.
  4495. SDValue X = GetSignificand(DAG, Op1, dl);
  4496. SDValue Log10ofMantissa;
  4497. if (LimitFloatPrecision <= 6) {
  4498. // For floating-point precision of 6:
  4499. //
  4500. // Log10ofMantissa =
  4501. // -0.50419619f +
  4502. // (0.60948995f - 0.10380950f * x) * x;
  4503. //
  4504. // error 0.0014886165, which is 6 bits
  4505. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4506. getF32Constant(DAG, 0xbdd49a13, dl));
  4507. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4508. getF32Constant(DAG, 0x3f1c0789, dl));
  4509. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4510. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4511. getF32Constant(DAG, 0x3f011300, dl));
  4512. } else if (LimitFloatPrecision <= 12) {
  4513. // For floating-point precision of 12:
  4514. //
  4515. // Log10ofMantissa =
  4516. // -0.64831180f +
  4517. // (0.91751397f +
  4518. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4519. //
  4520. // error 0.00019228036, which is better than 12 bits
  4521. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4522. getF32Constant(DAG, 0x3d431f31, dl));
  4523. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4524. getF32Constant(DAG, 0x3ea21fb2, dl));
  4525. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4526. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4527. getF32Constant(DAG, 0x3f6ae232, dl));
  4528. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4529. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4530. getF32Constant(DAG, 0x3f25f7c3, dl));
  4531. } else { // LimitFloatPrecision <= 18
  4532. // For floating-point precision of 18:
  4533. //
  4534. // Log10ofMantissa =
  4535. // -0.84299375f +
  4536. // (1.5327582f +
  4537. // (-1.0688956f +
  4538. // (0.49102474f +
  4539. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4540. //
  4541. // error 0.0000037995730, which is better than 18 bits
  4542. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4543. getF32Constant(DAG, 0x3c5d51ce, dl));
  4544. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4545. getF32Constant(DAG, 0x3e00685a, dl));
  4546. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4547. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4548. getF32Constant(DAG, 0x3efb6798, dl));
  4549. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4550. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4551. getF32Constant(DAG, 0x3f88d192, dl));
  4552. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4553. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4554. getF32Constant(DAG, 0x3fc4316c, dl));
  4555. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4556. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4557. getF32Constant(DAG, 0x3f57ce70, dl));
  4558. }
  4559. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4560. }
  4561. // No special expansion.
  4562. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4563. }
  4564. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4565. /// limited-precision mode.
  4566. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4567. const TargetLowering &TLI) {
  4568. if (Op.getValueType() == MVT::f32 &&
  4569. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4570. return getLimitedPrecisionExp2(Op, dl, DAG);
  4571. // No special expansion.
  4572. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4573. }
  4574. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4575. /// limited-precision mode with x == 10.0f.
  4576. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4577. SelectionDAG &DAG, const TargetLowering &TLI) {
  4578. bool IsExp10 = false;
  4579. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4580. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4581. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4582. APFloat Ten(10.0f);
  4583. IsExp10 = LHSC->isExactlyValue(Ten);
  4584. }
  4585. }
  4586. // TODO: What fast-math-flags should be set on the FMUL node?
  4587. if (IsExp10) {
  4588. // Put the exponent in the right bit position for later addition to the
  4589. // final result:
  4590. //
  4591. // #define LOG2OF10 3.3219281f
  4592. // t0 = Op * LOG2OF10;
  4593. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4594. getF32Constant(DAG, 0x40549a78, dl));
  4595. return getLimitedPrecisionExp2(t0, dl, DAG);
  4596. }
  4597. // No special expansion.
  4598. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4599. }
  4600. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4601. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4602. SelectionDAG &DAG) {
  4603. // If RHS is a constant, we can expand this out to a multiplication tree,
  4604. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4605. // optimizing for size, we only want to do this if the expansion would produce
  4606. // a small number of multiplies, otherwise we do the full expansion.
  4607. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4608. // Get the exponent as a positive value.
  4609. unsigned Val = RHSC->getSExtValue();
  4610. if ((int)Val < 0) Val = -Val;
  4611. // powi(x, 0) -> 1.0
  4612. if (Val == 0)
  4613. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4614. const Function &F = DAG.getMachineFunction().getFunction();
  4615. if (!F.hasOptSize() ||
  4616. // If optimizing for size, don't insert too many multiplies.
  4617. // This inserts up to 5 multiplies.
  4618. countPopulation(Val) + Log2_32(Val) < 7) {
  4619. // We use the simple binary decomposition method to generate the multiply
  4620. // sequence. There are more optimal ways to do this (for example,
  4621. // powi(x,15) generates one more multiply than it should), but this has
  4622. // the benefit of being both really simple and much better than a libcall.
  4623. SDValue Res; // Logically starts equal to 1.0
  4624. SDValue CurSquare = LHS;
  4625. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4626. // nodes.
  4627. while (Val) {
  4628. if (Val & 1) {
  4629. if (Res.getNode())
  4630. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4631. else
  4632. Res = CurSquare; // 1.0*CurSquare.
  4633. }
  4634. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4635. CurSquare, CurSquare);
  4636. Val >>= 1;
  4637. }
  4638. // If the original was negative, invert the result, producing 1/(x*x*x).
  4639. if (RHSC->getSExtValue() < 0)
  4640. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4641. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4642. return Res;
  4643. }
  4644. }
  4645. // Otherwise, expand to a libcall.
  4646. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4647. }
  4648. // getUnderlyingArgRegs - Find underlying registers used for a truncated,
  4649. // bitcasted, or split argument. Returns a list of <Register, size in bits>
  4650. static void
  4651. getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
  4652. const SDValue &N) {
  4653. switch (N.getOpcode()) {
  4654. case ISD::CopyFromReg: {
  4655. SDValue Op = N.getOperand(1);
  4656. Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
  4657. Op.getValueType().getSizeInBits());
  4658. return;
  4659. }
  4660. case ISD::BITCAST:
  4661. case ISD::AssertZext:
  4662. case ISD::AssertSext:
  4663. case ISD::TRUNCATE:
  4664. getUnderlyingArgRegs(Regs, N.getOperand(0));
  4665. return;
  4666. case ISD::BUILD_PAIR:
  4667. case ISD::BUILD_VECTOR:
  4668. case ISD::CONCAT_VECTORS:
  4669. for (SDValue Op : N->op_values())
  4670. getUnderlyingArgRegs(Regs, Op);
  4671. return;
  4672. default:
  4673. return;
  4674. }
  4675. }
  4676. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4677. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4678. /// instruction selection, they will be inserted to the entry BB.
  4679. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4680. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4681. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4682. const Argument *Arg = dyn_cast<Argument>(V);
  4683. if (!Arg)
  4684. return false;
  4685. if (!IsDbgDeclare) {
  4686. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4687. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4688. // the entry block.
  4689. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4690. if (!IsInEntryBlock)
  4691. return false;
  4692. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4693. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4694. // variable that also is a param.
  4695. //
  4696. // Although, if we are at the top of the entry block already, we can still
  4697. // emit using ArgDbgValue. This might catch some situations when the
  4698. // dbg.value refers to an argument that isn't used in the entry block, so
  4699. // any CopyToReg node would be optimized out and the only way to express
  4700. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4701. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4702. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4703. // current function, and the dbg.value intrinsic is found in the entry
  4704. // block.
  4705. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4706. !DL->getInlinedAt();
  4707. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4708. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4709. return false;
  4710. // Here we assume that a function argument on IR level only can be used to
  4711. // describe one input parameter on source level. If we for example have
  4712. // source code like this
  4713. //
  4714. // struct A { long x, y; };
  4715. // void foo(struct A a, long b) {
  4716. // ...
  4717. // b = a.x;
  4718. // ...
  4719. // }
  4720. //
  4721. // and IR like this
  4722. //
  4723. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4724. // entry:
  4725. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4726. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4727. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4728. // ...
  4729. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4730. // ...
  4731. //
  4732. // then the last dbg.value is describing a parameter "b" using a value that
  4733. // is an argument. But since we already has used %a1 to describe a parameter
  4734. // we should not handle that last dbg.value here (that would result in an
  4735. // incorrect hoisting of the DBG_VALUE to the function entry).
  4736. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4737. // for the situation with fragments above.
  4738. if (VariableIsFunctionInputArg) {
  4739. unsigned ArgNo = Arg->getArgNo();
  4740. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4741. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4742. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4743. return false;
  4744. FuncInfo.DescribedArgs.set(ArgNo);
  4745. }
  4746. }
  4747. MachineFunction &MF = DAG.getMachineFunction();
  4748. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4749. bool IsIndirect = false;
  4750. Optional<MachineOperand> Op;
  4751. // Some arguments' frame index is recorded during argument lowering.
  4752. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4753. if (FI != std::numeric_limits<int>::max())
  4754. Op = MachineOperand::CreateFI(FI);
  4755. SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
  4756. if (!Op && N.getNode()) {
  4757. getUnderlyingArgRegs(ArgRegsAndSizes, N);
  4758. Register Reg;
  4759. if (ArgRegsAndSizes.size() == 1)
  4760. Reg = ArgRegsAndSizes.front().first;
  4761. if (Reg && Reg.isVirtual()) {
  4762. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4763. Register PR = RegInfo.getLiveInPhysReg(Reg);
  4764. if (PR)
  4765. Reg = PR;
  4766. }
  4767. if (Reg) {
  4768. Op = MachineOperand::CreateReg(Reg, false);
  4769. IsIndirect = IsDbgDeclare;
  4770. }
  4771. }
  4772. if (!Op && N.getNode()) {
  4773. // Check if frame index is available.
  4774. SDValue LCandidate = peekThroughBitcasts(N);
  4775. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4776. if (FrameIndexSDNode *FINode =
  4777. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4778. Op = MachineOperand::CreateFI(FINode->getIndex());
  4779. }
  4780. if (!Op) {
  4781. // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
  4782. auto splitMultiRegDbgValue
  4783. = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
  4784. unsigned Offset = 0;
  4785. for (auto RegAndSize : SplitRegs) {
  4786. auto FragmentExpr = DIExpression::createFragmentExpression(
  4787. Expr, Offset, RegAndSize.second);
  4788. if (!FragmentExpr)
  4789. continue;
  4790. FuncInfo.ArgDbgValues.push_back(
  4791. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4792. RegAndSize.first, Variable, *FragmentExpr));
  4793. Offset += RegAndSize.second;
  4794. }
  4795. };
  4796. // Check if ValueMap has reg number.
  4797. DenseMap<const Value *, unsigned>::const_iterator
  4798. VMI = FuncInfo.ValueMap.find(V);
  4799. if (VMI != FuncInfo.ValueMap.end()) {
  4800. const auto &TLI = DAG.getTargetLoweringInfo();
  4801. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4802. V->getType(), getABIRegCopyCC(V));
  4803. if (RFV.occupiesMultipleRegs()) {
  4804. splitMultiRegDbgValue(RFV.getRegsAndSizes());
  4805. return true;
  4806. }
  4807. Op = MachineOperand::CreateReg(VMI->second, false);
  4808. IsIndirect = IsDbgDeclare;
  4809. } else if (ArgRegsAndSizes.size() > 1) {
  4810. // This was split due to the calling convention, and no virtual register
  4811. // mapping exists for the value.
  4812. splitMultiRegDbgValue(ArgRegsAndSizes);
  4813. return true;
  4814. }
  4815. }
  4816. if (!Op)
  4817. return false;
  4818. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4819. "Expected inlined-at fields to agree");
  4820. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4821. FuncInfo.ArgDbgValues.push_back(
  4822. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4823. *Op, Variable, Expr));
  4824. return true;
  4825. }
  4826. /// Return the appropriate SDDbgValue based on N.
  4827. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4828. DILocalVariable *Variable,
  4829. DIExpression *Expr,
  4830. const DebugLoc &dl,
  4831. unsigned DbgSDNodeOrder) {
  4832. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4833. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4834. // stack slot locations.
  4835. //
  4836. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4837. // debug values here after optimization:
  4838. //
  4839. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4840. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4841. //
  4842. // Both describe the direct values of their associated variables.
  4843. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4844. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4845. }
  4846. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4847. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4848. }
  4849. // VisualStudio defines setjmp as _setjmp
  4850. #if defined(_MSC_VER) && defined(setjmp) && \
  4851. !defined(setjmp_undefined_for_msvc)
  4852. # pragma push_macro("setjmp")
  4853. # undef setjmp
  4854. # define setjmp_undefined_for_msvc
  4855. #endif
  4856. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4857. switch (Intrinsic) {
  4858. case Intrinsic::smul_fix:
  4859. return ISD::SMULFIX;
  4860. case Intrinsic::umul_fix:
  4861. return ISD::UMULFIX;
  4862. default:
  4863. llvm_unreachable("Unhandled fixed point intrinsic");
  4864. }
  4865. }
  4866. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  4867. const char *FunctionName) {
  4868. assert(FunctionName && "FunctionName must not be nullptr");
  4869. SDValue Callee = DAG.getExternalSymbol(
  4870. FunctionName,
  4871. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  4872. LowerCallTo(&I, Callee, I.isTailCall());
  4873. }
  4874. /// Lower the call to the specified intrinsic function.
  4875. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  4876. unsigned Intrinsic) {
  4877. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4878. SDLoc sdl = getCurSDLoc();
  4879. DebugLoc dl = getCurDebugLoc();
  4880. SDValue Res;
  4881. switch (Intrinsic) {
  4882. default:
  4883. // By default, turn this into a target intrinsic node.
  4884. visitTargetIntrinsic(I, Intrinsic);
  4885. return;
  4886. case Intrinsic::vastart: visitVAStart(I); return;
  4887. case Intrinsic::vaend: visitVAEnd(I); return;
  4888. case Intrinsic::vacopy: visitVACopy(I); return;
  4889. case Intrinsic::returnaddress:
  4890. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4891. TLI.getPointerTy(DAG.getDataLayout()),
  4892. getValue(I.getArgOperand(0))));
  4893. return;
  4894. case Intrinsic::addressofreturnaddress:
  4895. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4896. TLI.getPointerTy(DAG.getDataLayout())));
  4897. return;
  4898. case Intrinsic::sponentry:
  4899. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4900. TLI.getFrameIndexTy(DAG.getDataLayout())));
  4901. return;
  4902. case Intrinsic::frameaddress:
  4903. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4904. TLI.getFrameIndexTy(DAG.getDataLayout()),
  4905. getValue(I.getArgOperand(0))));
  4906. return;
  4907. case Intrinsic::read_register: {
  4908. Value *Reg = I.getArgOperand(0);
  4909. SDValue Chain = getRoot();
  4910. SDValue RegName =
  4911. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4912. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4913. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4914. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4915. setValue(&I, Res);
  4916. DAG.setRoot(Res.getValue(1));
  4917. return;
  4918. }
  4919. case Intrinsic::write_register: {
  4920. Value *Reg = I.getArgOperand(0);
  4921. Value *RegValue = I.getArgOperand(1);
  4922. SDValue Chain = getRoot();
  4923. SDValue RegName =
  4924. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4925. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4926. RegName, getValue(RegValue)));
  4927. return;
  4928. }
  4929. case Intrinsic::setjmp:
  4930. lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
  4931. return;
  4932. case Intrinsic::longjmp:
  4933. lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
  4934. return;
  4935. case Intrinsic::memcpy: {
  4936. const auto &MCI = cast<MemCpyInst>(I);
  4937. SDValue Op1 = getValue(I.getArgOperand(0));
  4938. SDValue Op2 = getValue(I.getArgOperand(1));
  4939. SDValue Op3 = getValue(I.getArgOperand(2));
  4940. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4941. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4942. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4943. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4944. bool isVol = MCI.isVolatile();
  4945. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4946. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4947. // node.
  4948. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4949. false, isTC,
  4950. MachinePointerInfo(I.getArgOperand(0)),
  4951. MachinePointerInfo(I.getArgOperand(1)));
  4952. updateDAGForMaybeTailCall(MC);
  4953. return;
  4954. }
  4955. case Intrinsic::memset: {
  4956. const auto &MSI = cast<MemSetInst>(I);
  4957. SDValue Op1 = getValue(I.getArgOperand(0));
  4958. SDValue Op2 = getValue(I.getArgOperand(1));
  4959. SDValue Op3 = getValue(I.getArgOperand(2));
  4960. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4961. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4962. bool isVol = MSI.isVolatile();
  4963. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4964. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4965. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4966. updateDAGForMaybeTailCall(MS);
  4967. return;
  4968. }
  4969. case Intrinsic::memmove: {
  4970. const auto &MMI = cast<MemMoveInst>(I);
  4971. SDValue Op1 = getValue(I.getArgOperand(0));
  4972. SDValue Op2 = getValue(I.getArgOperand(1));
  4973. SDValue Op3 = getValue(I.getArgOperand(2));
  4974. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4975. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4976. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4977. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4978. bool isVol = MMI.isVolatile();
  4979. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4980. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4981. // node.
  4982. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4983. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4984. MachinePointerInfo(I.getArgOperand(1)));
  4985. updateDAGForMaybeTailCall(MM);
  4986. return;
  4987. }
  4988. case Intrinsic::memcpy_element_unordered_atomic: {
  4989. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4990. SDValue Dst = getValue(MI.getRawDest());
  4991. SDValue Src = getValue(MI.getRawSource());
  4992. SDValue Length = getValue(MI.getLength());
  4993. unsigned DstAlign = MI.getDestAlignment();
  4994. unsigned SrcAlign = MI.getSourceAlignment();
  4995. Type *LengthTy = MI.getLength()->getType();
  4996. unsigned ElemSz = MI.getElementSizeInBytes();
  4997. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4998. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4999. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5000. MachinePointerInfo(MI.getRawDest()),
  5001. MachinePointerInfo(MI.getRawSource()));
  5002. updateDAGForMaybeTailCall(MC);
  5003. return;
  5004. }
  5005. case Intrinsic::memmove_element_unordered_atomic: {
  5006. auto &MI = cast<AtomicMemMoveInst>(I);
  5007. SDValue Dst = getValue(MI.getRawDest());
  5008. SDValue Src = getValue(MI.getRawSource());
  5009. SDValue Length = getValue(MI.getLength());
  5010. unsigned DstAlign = MI.getDestAlignment();
  5011. unsigned SrcAlign = MI.getSourceAlignment();
  5012. Type *LengthTy = MI.getLength()->getType();
  5013. unsigned ElemSz = MI.getElementSizeInBytes();
  5014. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5015. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  5016. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5017. MachinePointerInfo(MI.getRawDest()),
  5018. MachinePointerInfo(MI.getRawSource()));
  5019. updateDAGForMaybeTailCall(MC);
  5020. return;
  5021. }
  5022. case Intrinsic::memset_element_unordered_atomic: {
  5023. auto &MI = cast<AtomicMemSetInst>(I);
  5024. SDValue Dst = getValue(MI.getRawDest());
  5025. SDValue Val = getValue(MI.getValue());
  5026. SDValue Length = getValue(MI.getLength());
  5027. unsigned DstAlign = MI.getDestAlignment();
  5028. Type *LengthTy = MI.getLength()->getType();
  5029. unsigned ElemSz = MI.getElementSizeInBytes();
  5030. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5031. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  5032. LengthTy, ElemSz, isTC,
  5033. MachinePointerInfo(MI.getRawDest()));
  5034. updateDAGForMaybeTailCall(MC);
  5035. return;
  5036. }
  5037. case Intrinsic::dbg_addr:
  5038. case Intrinsic::dbg_declare: {
  5039. const auto &DI = cast<DbgVariableIntrinsic>(I);
  5040. DILocalVariable *Variable = DI.getVariable();
  5041. DIExpression *Expression = DI.getExpression();
  5042. dropDanglingDebugInfo(Variable, Expression);
  5043. assert(Variable && "Missing variable");
  5044. // Check if address has undef value.
  5045. const Value *Address = DI.getVariableLocation();
  5046. if (!Address || isa<UndefValue>(Address) ||
  5047. (Address->use_empty() && !isa<Argument>(Address))) {
  5048. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5049. return;
  5050. }
  5051. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5052. // Check if this variable can be described by a frame index, typically
  5053. // either as a static alloca or a byval parameter.
  5054. int FI = std::numeric_limits<int>::max();
  5055. if (const auto *AI =
  5056. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5057. if (AI->isStaticAlloca()) {
  5058. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5059. if (I != FuncInfo.StaticAllocaMap.end())
  5060. FI = I->second;
  5061. }
  5062. } else if (const auto *Arg = dyn_cast<Argument>(
  5063. Address->stripInBoundsConstantOffsets())) {
  5064. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5065. }
  5066. // llvm.dbg.addr is control dependent and always generates indirect
  5067. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5068. // the MachineFunction variable table.
  5069. if (FI != std::numeric_limits<int>::max()) {
  5070. if (Intrinsic == Intrinsic::dbg_addr) {
  5071. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5072. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  5073. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  5074. }
  5075. return;
  5076. }
  5077. SDValue &N = NodeMap[Address];
  5078. if (!N.getNode() && isa<Argument>(Address))
  5079. // Check unused arguments map.
  5080. N = UnusedArgNodeMap[Address];
  5081. SDDbgValue *SDV;
  5082. if (N.getNode()) {
  5083. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5084. Address = BCI->getOperand(0);
  5085. // Parameters are handled specially.
  5086. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5087. if (isParameter && FINode) {
  5088. // Byval parameter. We have a frame index at this point.
  5089. SDV =
  5090. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5091. /*IsIndirect*/ true, dl, SDNodeOrder);
  5092. } else if (isa<Argument>(Address)) {
  5093. // Address is an argument, so try to emit its dbg value using
  5094. // virtual register info from the FuncInfo.ValueMap.
  5095. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5096. return;
  5097. } else {
  5098. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5099. true, dl, SDNodeOrder);
  5100. }
  5101. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5102. } else {
  5103. // If Address is an argument then try to emit its dbg value using
  5104. // virtual register info from the FuncInfo.ValueMap.
  5105. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5106. N)) {
  5107. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5108. }
  5109. }
  5110. return;
  5111. }
  5112. case Intrinsic::dbg_label: {
  5113. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5114. DILabel *Label = DI.getLabel();
  5115. assert(Label && "Missing label");
  5116. SDDbgLabel *SDV;
  5117. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5118. DAG.AddDbgLabel(SDV);
  5119. return;
  5120. }
  5121. case Intrinsic::dbg_value: {
  5122. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5123. assert(DI.getVariable() && "Missing variable");
  5124. DILocalVariable *Variable = DI.getVariable();
  5125. DIExpression *Expression = DI.getExpression();
  5126. dropDanglingDebugInfo(Variable, Expression);
  5127. const Value *V = DI.getValue();
  5128. if (!V)
  5129. return;
  5130. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5131. SDNodeOrder))
  5132. return;
  5133. // TODO: Dangling debug info will eventually either be resolved or produce
  5134. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5135. // between the original dbg.value location and its resolved DBG_VALUE, which
  5136. // we should ideally fill with an extra Undef DBG_VALUE.
  5137. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5138. return;
  5139. }
  5140. case Intrinsic::eh_typeid_for: {
  5141. // Find the type id for the given typeinfo.
  5142. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5143. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5144. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5145. setValue(&I, Res);
  5146. return;
  5147. }
  5148. case Intrinsic::eh_return_i32:
  5149. case Intrinsic::eh_return_i64:
  5150. DAG.getMachineFunction().setCallsEHReturn(true);
  5151. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5152. MVT::Other,
  5153. getControlRoot(),
  5154. getValue(I.getArgOperand(0)),
  5155. getValue(I.getArgOperand(1))));
  5156. return;
  5157. case Intrinsic::eh_unwind_init:
  5158. DAG.getMachineFunction().setCallsUnwindInit(true);
  5159. return;
  5160. case Intrinsic::eh_dwarf_cfa:
  5161. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5162. TLI.getPointerTy(DAG.getDataLayout()),
  5163. getValue(I.getArgOperand(0))));
  5164. return;
  5165. case Intrinsic::eh_sjlj_callsite: {
  5166. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5167. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5168. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5169. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5170. MMI.setCurrentCallSite(CI->getZExtValue());
  5171. return;
  5172. }
  5173. case Intrinsic::eh_sjlj_functioncontext: {
  5174. // Get and store the index of the function context.
  5175. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5176. AllocaInst *FnCtx =
  5177. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5178. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5179. MFI.setFunctionContextIndex(FI);
  5180. return;
  5181. }
  5182. case Intrinsic::eh_sjlj_setjmp: {
  5183. SDValue Ops[2];
  5184. Ops[0] = getRoot();
  5185. Ops[1] = getValue(I.getArgOperand(0));
  5186. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5187. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5188. setValue(&I, Op.getValue(0));
  5189. DAG.setRoot(Op.getValue(1));
  5190. return;
  5191. }
  5192. case Intrinsic::eh_sjlj_longjmp:
  5193. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5194. getRoot(), getValue(I.getArgOperand(0))));
  5195. return;
  5196. case Intrinsic::eh_sjlj_setup_dispatch:
  5197. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5198. getRoot()));
  5199. return;
  5200. case Intrinsic::masked_gather:
  5201. visitMaskedGather(I);
  5202. return;
  5203. case Intrinsic::masked_load:
  5204. visitMaskedLoad(I);
  5205. return;
  5206. case Intrinsic::masked_scatter:
  5207. visitMaskedScatter(I);
  5208. return;
  5209. case Intrinsic::masked_store:
  5210. visitMaskedStore(I);
  5211. return;
  5212. case Intrinsic::masked_expandload:
  5213. visitMaskedLoad(I, true /* IsExpanding */);
  5214. return;
  5215. case Intrinsic::masked_compressstore:
  5216. visitMaskedStore(I, true /* IsCompressing */);
  5217. return;
  5218. case Intrinsic::x86_mmx_pslli_w:
  5219. case Intrinsic::x86_mmx_pslli_d:
  5220. case Intrinsic::x86_mmx_pslli_q:
  5221. case Intrinsic::x86_mmx_psrli_w:
  5222. case Intrinsic::x86_mmx_psrli_d:
  5223. case Intrinsic::x86_mmx_psrli_q:
  5224. case Intrinsic::x86_mmx_psrai_w:
  5225. case Intrinsic::x86_mmx_psrai_d: {
  5226. SDValue ShAmt = getValue(I.getArgOperand(1));
  5227. if (isa<ConstantSDNode>(ShAmt)) {
  5228. visitTargetIntrinsic(I, Intrinsic);
  5229. return;
  5230. }
  5231. unsigned NewIntrinsic = 0;
  5232. EVT ShAmtVT = MVT::v2i32;
  5233. switch (Intrinsic) {
  5234. case Intrinsic::x86_mmx_pslli_w:
  5235. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  5236. break;
  5237. case Intrinsic::x86_mmx_pslli_d:
  5238. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  5239. break;
  5240. case Intrinsic::x86_mmx_pslli_q:
  5241. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  5242. break;
  5243. case Intrinsic::x86_mmx_psrli_w:
  5244. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  5245. break;
  5246. case Intrinsic::x86_mmx_psrli_d:
  5247. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  5248. break;
  5249. case Intrinsic::x86_mmx_psrli_q:
  5250. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  5251. break;
  5252. case Intrinsic::x86_mmx_psrai_w:
  5253. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  5254. break;
  5255. case Intrinsic::x86_mmx_psrai_d:
  5256. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  5257. break;
  5258. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5259. }
  5260. // The vector shift intrinsics with scalars uses 32b shift amounts but
  5261. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  5262. // to be zero.
  5263. // We must do this early because v2i32 is not a legal type.
  5264. SDValue ShOps[2];
  5265. ShOps[0] = ShAmt;
  5266. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  5267. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  5268. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5269. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  5270. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  5271. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  5272. getValue(I.getArgOperand(0)), ShAmt);
  5273. setValue(&I, Res);
  5274. return;
  5275. }
  5276. case Intrinsic::powi:
  5277. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5278. getValue(I.getArgOperand(1)), DAG));
  5279. return;
  5280. case Intrinsic::log:
  5281. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5282. return;
  5283. case Intrinsic::log2:
  5284. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5285. return;
  5286. case Intrinsic::log10:
  5287. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5288. return;
  5289. case Intrinsic::exp:
  5290. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5291. return;
  5292. case Intrinsic::exp2:
  5293. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5294. return;
  5295. case Intrinsic::pow:
  5296. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5297. getValue(I.getArgOperand(1)), DAG, TLI));
  5298. return;
  5299. case Intrinsic::sqrt:
  5300. case Intrinsic::fabs:
  5301. case Intrinsic::sin:
  5302. case Intrinsic::cos:
  5303. case Intrinsic::floor:
  5304. case Intrinsic::ceil:
  5305. case Intrinsic::trunc:
  5306. case Intrinsic::rint:
  5307. case Intrinsic::nearbyint:
  5308. case Intrinsic::round:
  5309. case Intrinsic::canonicalize: {
  5310. unsigned Opcode;
  5311. switch (Intrinsic) {
  5312. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5313. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5314. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5315. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5316. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5317. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5318. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5319. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5320. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5321. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5322. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5323. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5324. }
  5325. setValue(&I, DAG.getNode(Opcode, sdl,
  5326. getValue(I.getArgOperand(0)).getValueType(),
  5327. getValue(I.getArgOperand(0))));
  5328. return;
  5329. }
  5330. case Intrinsic::lround:
  5331. case Intrinsic::llround:
  5332. case Intrinsic::lrint:
  5333. case Intrinsic::llrint: {
  5334. unsigned Opcode;
  5335. switch (Intrinsic) {
  5336. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5337. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5338. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5339. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5340. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5341. }
  5342. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5343. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5344. getValue(I.getArgOperand(0))));
  5345. return;
  5346. }
  5347. case Intrinsic::minnum:
  5348. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  5349. getValue(I.getArgOperand(0)).getValueType(),
  5350. getValue(I.getArgOperand(0)),
  5351. getValue(I.getArgOperand(1))));
  5352. return;
  5353. case Intrinsic::maxnum:
  5354. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  5355. getValue(I.getArgOperand(0)).getValueType(),
  5356. getValue(I.getArgOperand(0)),
  5357. getValue(I.getArgOperand(1))));
  5358. return;
  5359. case Intrinsic::minimum:
  5360. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5361. getValue(I.getArgOperand(0)).getValueType(),
  5362. getValue(I.getArgOperand(0)),
  5363. getValue(I.getArgOperand(1))));
  5364. return;
  5365. case Intrinsic::maximum:
  5366. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5367. getValue(I.getArgOperand(0)).getValueType(),
  5368. getValue(I.getArgOperand(0)),
  5369. getValue(I.getArgOperand(1))));
  5370. return;
  5371. case Intrinsic::copysign:
  5372. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5373. getValue(I.getArgOperand(0)).getValueType(),
  5374. getValue(I.getArgOperand(0)),
  5375. getValue(I.getArgOperand(1))));
  5376. return;
  5377. case Intrinsic::fma:
  5378. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5379. getValue(I.getArgOperand(0)).getValueType(),
  5380. getValue(I.getArgOperand(0)),
  5381. getValue(I.getArgOperand(1)),
  5382. getValue(I.getArgOperand(2))));
  5383. return;
  5384. case Intrinsic::experimental_constrained_fadd:
  5385. case Intrinsic::experimental_constrained_fsub:
  5386. case Intrinsic::experimental_constrained_fmul:
  5387. case Intrinsic::experimental_constrained_fdiv:
  5388. case Intrinsic::experimental_constrained_frem:
  5389. case Intrinsic::experimental_constrained_fma:
  5390. case Intrinsic::experimental_constrained_fptosi:
  5391. case Intrinsic::experimental_constrained_fptoui:
  5392. case Intrinsic::experimental_constrained_fptrunc:
  5393. case Intrinsic::experimental_constrained_fpext:
  5394. case Intrinsic::experimental_constrained_sqrt:
  5395. case Intrinsic::experimental_constrained_pow:
  5396. case Intrinsic::experimental_constrained_powi:
  5397. case Intrinsic::experimental_constrained_sin:
  5398. case Intrinsic::experimental_constrained_cos:
  5399. case Intrinsic::experimental_constrained_exp:
  5400. case Intrinsic::experimental_constrained_exp2:
  5401. case Intrinsic::experimental_constrained_log:
  5402. case Intrinsic::experimental_constrained_log10:
  5403. case Intrinsic::experimental_constrained_log2:
  5404. case Intrinsic::experimental_constrained_rint:
  5405. case Intrinsic::experimental_constrained_nearbyint:
  5406. case Intrinsic::experimental_constrained_maxnum:
  5407. case Intrinsic::experimental_constrained_minnum:
  5408. case Intrinsic::experimental_constrained_ceil:
  5409. case Intrinsic::experimental_constrained_floor:
  5410. case Intrinsic::experimental_constrained_round:
  5411. case Intrinsic::experimental_constrained_trunc:
  5412. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5413. return;
  5414. case Intrinsic::fmuladd: {
  5415. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5416. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5417. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5418. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5419. getValue(I.getArgOperand(0)).getValueType(),
  5420. getValue(I.getArgOperand(0)),
  5421. getValue(I.getArgOperand(1)),
  5422. getValue(I.getArgOperand(2))));
  5423. } else {
  5424. // TODO: Intrinsic calls should have fast-math-flags.
  5425. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5426. getValue(I.getArgOperand(0)).getValueType(),
  5427. getValue(I.getArgOperand(0)),
  5428. getValue(I.getArgOperand(1)));
  5429. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5430. getValue(I.getArgOperand(0)).getValueType(),
  5431. Mul,
  5432. getValue(I.getArgOperand(2)));
  5433. setValue(&I, Add);
  5434. }
  5435. return;
  5436. }
  5437. case Intrinsic::convert_to_fp16:
  5438. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5439. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5440. getValue(I.getArgOperand(0)),
  5441. DAG.getTargetConstant(0, sdl,
  5442. MVT::i32))));
  5443. return;
  5444. case Intrinsic::convert_from_fp16:
  5445. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5446. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5447. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5448. getValue(I.getArgOperand(0)))));
  5449. return;
  5450. case Intrinsic::pcmarker: {
  5451. SDValue Tmp = getValue(I.getArgOperand(0));
  5452. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5453. return;
  5454. }
  5455. case Intrinsic::readcyclecounter: {
  5456. SDValue Op = getRoot();
  5457. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5458. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5459. setValue(&I, Res);
  5460. DAG.setRoot(Res.getValue(1));
  5461. return;
  5462. }
  5463. case Intrinsic::bitreverse:
  5464. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5465. getValue(I.getArgOperand(0)).getValueType(),
  5466. getValue(I.getArgOperand(0))));
  5467. return;
  5468. case Intrinsic::bswap:
  5469. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5470. getValue(I.getArgOperand(0)).getValueType(),
  5471. getValue(I.getArgOperand(0))));
  5472. return;
  5473. case Intrinsic::cttz: {
  5474. SDValue Arg = getValue(I.getArgOperand(0));
  5475. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5476. EVT Ty = Arg.getValueType();
  5477. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5478. sdl, Ty, Arg));
  5479. return;
  5480. }
  5481. case Intrinsic::ctlz: {
  5482. SDValue Arg = getValue(I.getArgOperand(0));
  5483. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5484. EVT Ty = Arg.getValueType();
  5485. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5486. sdl, Ty, Arg));
  5487. return;
  5488. }
  5489. case Intrinsic::ctpop: {
  5490. SDValue Arg = getValue(I.getArgOperand(0));
  5491. EVT Ty = Arg.getValueType();
  5492. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5493. return;
  5494. }
  5495. case Intrinsic::fshl:
  5496. case Intrinsic::fshr: {
  5497. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5498. SDValue X = getValue(I.getArgOperand(0));
  5499. SDValue Y = getValue(I.getArgOperand(1));
  5500. SDValue Z = getValue(I.getArgOperand(2));
  5501. EVT VT = X.getValueType();
  5502. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5503. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5504. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5505. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5506. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5507. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5508. return;
  5509. }
  5510. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5511. // avoid the select that is necessary in the general case to filter out
  5512. // the 0-shift possibility that leads to UB.
  5513. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5514. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5515. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5516. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5517. return;
  5518. }
  5519. // Some targets only rotate one way. Try the opposite direction.
  5520. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5521. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5522. // Negate the shift amount because it is safe to ignore the high bits.
  5523. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5524. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5525. return;
  5526. }
  5527. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5528. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5529. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5530. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5531. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5532. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5533. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5534. return;
  5535. }
  5536. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5537. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5538. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5539. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5540. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5541. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5542. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5543. // and that is undefined. We must compare and select to avoid UB.
  5544. EVT CCVT = MVT::i1;
  5545. if (VT.isVector())
  5546. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5547. // For fshl, 0-shift returns the 1st arg (X).
  5548. // For fshr, 0-shift returns the 2nd arg (Y).
  5549. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5550. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5551. return;
  5552. }
  5553. case Intrinsic::sadd_sat: {
  5554. SDValue Op1 = getValue(I.getArgOperand(0));
  5555. SDValue Op2 = getValue(I.getArgOperand(1));
  5556. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5557. return;
  5558. }
  5559. case Intrinsic::uadd_sat: {
  5560. SDValue Op1 = getValue(I.getArgOperand(0));
  5561. SDValue Op2 = getValue(I.getArgOperand(1));
  5562. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5563. return;
  5564. }
  5565. case Intrinsic::ssub_sat: {
  5566. SDValue Op1 = getValue(I.getArgOperand(0));
  5567. SDValue Op2 = getValue(I.getArgOperand(1));
  5568. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5569. return;
  5570. }
  5571. case Intrinsic::usub_sat: {
  5572. SDValue Op1 = getValue(I.getArgOperand(0));
  5573. SDValue Op2 = getValue(I.getArgOperand(1));
  5574. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5575. return;
  5576. }
  5577. case Intrinsic::smul_fix:
  5578. case Intrinsic::umul_fix: {
  5579. SDValue Op1 = getValue(I.getArgOperand(0));
  5580. SDValue Op2 = getValue(I.getArgOperand(1));
  5581. SDValue Op3 = getValue(I.getArgOperand(2));
  5582. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5583. Op1.getValueType(), Op1, Op2, Op3));
  5584. return;
  5585. }
  5586. case Intrinsic::smul_fix_sat: {
  5587. SDValue Op1 = getValue(I.getArgOperand(0));
  5588. SDValue Op2 = getValue(I.getArgOperand(1));
  5589. SDValue Op3 = getValue(I.getArgOperand(2));
  5590. setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5591. Op3));
  5592. return;
  5593. }
  5594. case Intrinsic::stacksave: {
  5595. SDValue Op = getRoot();
  5596. Res = DAG.getNode(
  5597. ISD::STACKSAVE, sdl,
  5598. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5599. setValue(&I, Res);
  5600. DAG.setRoot(Res.getValue(1));
  5601. return;
  5602. }
  5603. case Intrinsic::stackrestore:
  5604. Res = getValue(I.getArgOperand(0));
  5605. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5606. return;
  5607. case Intrinsic::get_dynamic_area_offset: {
  5608. SDValue Op = getRoot();
  5609. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5610. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5611. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5612. // target.
  5613. if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
  5614. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5615. " intrinsic!");
  5616. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5617. Op);
  5618. DAG.setRoot(Op);
  5619. setValue(&I, Res);
  5620. return;
  5621. }
  5622. case Intrinsic::stackguard: {
  5623. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5624. MachineFunction &MF = DAG.getMachineFunction();
  5625. const Module &M = *MF.getFunction().getParent();
  5626. SDValue Chain = getRoot();
  5627. if (TLI.useLoadStackGuardNode()) {
  5628. Res = getLoadStackGuard(DAG, sdl, Chain);
  5629. } else {
  5630. const Value *Global = TLI.getSDagStackGuard(M);
  5631. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5632. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5633. MachinePointerInfo(Global, 0), Align,
  5634. MachineMemOperand::MOVolatile);
  5635. }
  5636. if (TLI.useStackGuardXorFP())
  5637. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5638. DAG.setRoot(Chain);
  5639. setValue(&I, Res);
  5640. return;
  5641. }
  5642. case Intrinsic::stackprotector: {
  5643. // Emit code into the DAG to store the stack guard onto the stack.
  5644. MachineFunction &MF = DAG.getMachineFunction();
  5645. MachineFrameInfo &MFI = MF.getFrameInfo();
  5646. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5647. SDValue Src, Chain = getRoot();
  5648. if (TLI.useLoadStackGuardNode())
  5649. Src = getLoadStackGuard(DAG, sdl, Chain);
  5650. else
  5651. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5652. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5653. int FI = FuncInfo.StaticAllocaMap[Slot];
  5654. MFI.setStackProtectorIndex(FI);
  5655. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5656. // Store the stack protector onto the stack.
  5657. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5658. DAG.getMachineFunction(), FI),
  5659. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5660. setValue(&I, Res);
  5661. DAG.setRoot(Res);
  5662. return;
  5663. }
  5664. case Intrinsic::objectsize: {
  5665. // If we don't know by now, we're never going to know.
  5666. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5667. assert(CI && "Non-constant type in __builtin_object_size?");
  5668. SDValue Arg = getValue(I.getCalledValue());
  5669. EVT Ty = Arg.getValueType();
  5670. if (CI->isZero())
  5671. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5672. else
  5673. Res = DAG.getConstant(0, sdl, Ty);
  5674. setValue(&I, Res);
  5675. return;
  5676. }
  5677. case Intrinsic::is_constant:
  5678. // If this wasn't constant-folded away by now, then it's not a
  5679. // constant.
  5680. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5681. return;
  5682. case Intrinsic::annotation:
  5683. case Intrinsic::ptr_annotation:
  5684. case Intrinsic::launder_invariant_group:
  5685. case Intrinsic::strip_invariant_group:
  5686. // Drop the intrinsic, but forward the value
  5687. setValue(&I, getValue(I.getOperand(0)));
  5688. return;
  5689. case Intrinsic::assume:
  5690. case Intrinsic::var_annotation:
  5691. case Intrinsic::sideeffect:
  5692. // Discard annotate attributes, assumptions, and artificial side-effects.
  5693. return;
  5694. case Intrinsic::codeview_annotation: {
  5695. // Emit a label associated with this metadata.
  5696. MachineFunction &MF = DAG.getMachineFunction();
  5697. MCSymbol *Label =
  5698. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5699. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5700. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5701. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5702. DAG.setRoot(Res);
  5703. return;
  5704. }
  5705. case Intrinsic::init_trampoline: {
  5706. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5707. SDValue Ops[6];
  5708. Ops[0] = getRoot();
  5709. Ops[1] = getValue(I.getArgOperand(0));
  5710. Ops[2] = getValue(I.getArgOperand(1));
  5711. Ops[3] = getValue(I.getArgOperand(2));
  5712. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5713. Ops[5] = DAG.getSrcValue(F);
  5714. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5715. DAG.setRoot(Res);
  5716. return;
  5717. }
  5718. case Intrinsic::adjust_trampoline:
  5719. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5720. TLI.getPointerTy(DAG.getDataLayout()),
  5721. getValue(I.getArgOperand(0))));
  5722. return;
  5723. case Intrinsic::gcroot: {
  5724. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5725. "only valid in functions with gc specified, enforced by Verifier");
  5726. assert(GFI && "implied by previous");
  5727. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5728. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5729. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5730. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5731. return;
  5732. }
  5733. case Intrinsic::gcread:
  5734. case Intrinsic::gcwrite:
  5735. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5736. case Intrinsic::flt_rounds:
  5737. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5738. return;
  5739. case Intrinsic::expect:
  5740. // Just replace __builtin_expect(exp, c) with EXP.
  5741. setValue(&I, getValue(I.getArgOperand(0)));
  5742. return;
  5743. case Intrinsic::debugtrap:
  5744. case Intrinsic::trap: {
  5745. StringRef TrapFuncName =
  5746. I.getAttributes()
  5747. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5748. .getValueAsString();
  5749. if (TrapFuncName.empty()) {
  5750. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5751. ISD::TRAP : ISD::DEBUGTRAP;
  5752. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5753. return;
  5754. }
  5755. TargetLowering::ArgListTy Args;
  5756. TargetLowering::CallLoweringInfo CLI(DAG);
  5757. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5758. CallingConv::C, I.getType(),
  5759. DAG.getExternalSymbol(TrapFuncName.data(),
  5760. TLI.getPointerTy(DAG.getDataLayout())),
  5761. std::move(Args));
  5762. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5763. DAG.setRoot(Result.second);
  5764. return;
  5765. }
  5766. case Intrinsic::uadd_with_overflow:
  5767. case Intrinsic::sadd_with_overflow:
  5768. case Intrinsic::usub_with_overflow:
  5769. case Intrinsic::ssub_with_overflow:
  5770. case Intrinsic::umul_with_overflow:
  5771. case Intrinsic::smul_with_overflow: {
  5772. ISD::NodeType Op;
  5773. switch (Intrinsic) {
  5774. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5775. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5776. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5777. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5778. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5779. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5780. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5781. }
  5782. SDValue Op1 = getValue(I.getArgOperand(0));
  5783. SDValue Op2 = getValue(I.getArgOperand(1));
  5784. EVT ResultVT = Op1.getValueType();
  5785. EVT OverflowVT = MVT::i1;
  5786. if (ResultVT.isVector())
  5787. OverflowVT = EVT::getVectorVT(
  5788. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5789. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5790. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5791. return;
  5792. }
  5793. case Intrinsic::prefetch: {
  5794. SDValue Ops[5];
  5795. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5796. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5797. Ops[0] = DAG.getRoot();
  5798. Ops[1] = getValue(I.getArgOperand(0));
  5799. Ops[2] = getValue(I.getArgOperand(1));
  5800. Ops[3] = getValue(I.getArgOperand(2));
  5801. Ops[4] = getValue(I.getArgOperand(3));
  5802. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5803. DAG.getVTList(MVT::Other), Ops,
  5804. EVT::getIntegerVT(*Context, 8),
  5805. MachinePointerInfo(I.getArgOperand(0)),
  5806. 0, /* align */
  5807. Flags);
  5808. // Chain the prefetch in parallell with any pending loads, to stay out of
  5809. // the way of later optimizations.
  5810. PendingLoads.push_back(Result);
  5811. Result = getRoot();
  5812. DAG.setRoot(Result);
  5813. return;
  5814. }
  5815. case Intrinsic::lifetime_start:
  5816. case Intrinsic::lifetime_end: {
  5817. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5818. // Stack coloring is not enabled in O0, discard region information.
  5819. if (TM.getOptLevel() == CodeGenOpt::None)
  5820. return;
  5821. const int64_t ObjectSize =
  5822. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5823. Value *const ObjectPtr = I.getArgOperand(1);
  5824. SmallVector<const Value *, 4> Allocas;
  5825. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5826. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5827. E = Allocas.end(); Object != E; ++Object) {
  5828. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5829. // Could not find an Alloca.
  5830. if (!LifetimeObject)
  5831. continue;
  5832. // First check that the Alloca is static, otherwise it won't have a
  5833. // valid frame index.
  5834. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5835. if (SI == FuncInfo.StaticAllocaMap.end())
  5836. return;
  5837. const int FrameIndex = SI->second;
  5838. int64_t Offset;
  5839. if (GetPointerBaseWithConstantOffset(
  5840. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5841. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5842. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5843. Offset);
  5844. DAG.setRoot(Res);
  5845. }
  5846. return;
  5847. }
  5848. case Intrinsic::invariant_start:
  5849. // Discard region information.
  5850. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5851. return;
  5852. case Intrinsic::invariant_end:
  5853. // Discard region information.
  5854. return;
  5855. case Intrinsic::clear_cache:
  5856. /// FunctionName may be null.
  5857. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  5858. lowerCallToExternalSymbol(I, FunctionName);
  5859. return;
  5860. case Intrinsic::donothing:
  5861. // ignore
  5862. return;
  5863. case Intrinsic::experimental_stackmap:
  5864. visitStackmap(I);
  5865. return;
  5866. case Intrinsic::experimental_patchpoint_void:
  5867. case Intrinsic::experimental_patchpoint_i64:
  5868. visitPatchpoint(&I);
  5869. return;
  5870. case Intrinsic::experimental_gc_statepoint:
  5871. LowerStatepoint(ImmutableStatepoint(&I));
  5872. return;
  5873. case Intrinsic::experimental_gc_result:
  5874. visitGCResult(cast<GCResultInst>(I));
  5875. return;
  5876. case Intrinsic::experimental_gc_relocate:
  5877. visitGCRelocate(cast<GCRelocateInst>(I));
  5878. return;
  5879. case Intrinsic::instrprof_increment:
  5880. llvm_unreachable("instrprof failed to lower an increment");
  5881. case Intrinsic::instrprof_value_profile:
  5882. llvm_unreachable("instrprof failed to lower a value profiling call");
  5883. case Intrinsic::localescape: {
  5884. MachineFunction &MF = DAG.getMachineFunction();
  5885. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5886. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5887. // is the same on all targets.
  5888. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5889. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5890. if (isa<ConstantPointerNull>(Arg))
  5891. continue; // Skip null pointers. They represent a hole in index space.
  5892. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5893. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5894. "can only escape static allocas");
  5895. int FI = FuncInfo.StaticAllocaMap[Slot];
  5896. MCSymbol *FrameAllocSym =
  5897. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5898. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5899. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5900. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5901. .addSym(FrameAllocSym)
  5902. .addFrameIndex(FI);
  5903. }
  5904. return;
  5905. }
  5906. case Intrinsic::localrecover: {
  5907. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5908. MachineFunction &MF = DAG.getMachineFunction();
  5909. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5910. // Get the symbol that defines the frame offset.
  5911. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5912. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5913. unsigned IdxVal =
  5914. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5915. MCSymbol *FrameAllocSym =
  5916. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5917. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5918. // Create a MCSymbol for the label to avoid any target lowering
  5919. // that would make this PC relative.
  5920. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5921. SDValue OffsetVal =
  5922. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5923. // Add the offset to the FP.
  5924. Value *FP = I.getArgOperand(1);
  5925. SDValue FPVal = getValue(FP);
  5926. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5927. setValue(&I, Add);
  5928. return;
  5929. }
  5930. case Intrinsic::eh_exceptionpointer:
  5931. case Intrinsic::eh_exceptioncode: {
  5932. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5933. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5934. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5935. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5936. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5937. SDValue N =
  5938. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5939. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5940. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5941. setValue(&I, N);
  5942. return;
  5943. }
  5944. case Intrinsic::xray_customevent: {
  5945. // Here we want to make sure that the intrinsic behaves as if it has a
  5946. // specific calling convention, and only for x86_64.
  5947. // FIXME: Support other platforms later.
  5948. const auto &Triple = DAG.getTarget().getTargetTriple();
  5949. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5950. return;
  5951. SDLoc DL = getCurSDLoc();
  5952. SmallVector<SDValue, 8> Ops;
  5953. // We want to say that we always want the arguments in registers.
  5954. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5955. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5956. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5957. SDValue Chain = getRoot();
  5958. Ops.push_back(LogEntryVal);
  5959. Ops.push_back(StrSizeVal);
  5960. Ops.push_back(Chain);
  5961. // We need to enforce the calling convention for the callsite, so that
  5962. // argument ordering is enforced correctly, and that register allocation can
  5963. // see that some registers may be assumed clobbered and have to preserve
  5964. // them across calls to the intrinsic.
  5965. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5966. DL, NodeTys, Ops);
  5967. SDValue patchableNode = SDValue(MN, 0);
  5968. DAG.setRoot(patchableNode);
  5969. setValue(&I, patchableNode);
  5970. return;
  5971. }
  5972. case Intrinsic::xray_typedevent: {
  5973. // Here we want to make sure that the intrinsic behaves as if it has a
  5974. // specific calling convention, and only for x86_64.
  5975. // FIXME: Support other platforms later.
  5976. const auto &Triple = DAG.getTarget().getTargetTriple();
  5977. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5978. return;
  5979. SDLoc DL = getCurSDLoc();
  5980. SmallVector<SDValue, 8> Ops;
  5981. // We want to say that we always want the arguments in registers.
  5982. // It's unclear to me how manipulating the selection DAG here forces callers
  5983. // to provide arguments in registers instead of on the stack.
  5984. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5985. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5986. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5987. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5988. SDValue Chain = getRoot();
  5989. Ops.push_back(LogTypeId);
  5990. Ops.push_back(LogEntryVal);
  5991. Ops.push_back(StrSizeVal);
  5992. Ops.push_back(Chain);
  5993. // We need to enforce the calling convention for the callsite, so that
  5994. // argument ordering is enforced correctly, and that register allocation can
  5995. // see that some registers may be assumed clobbered and have to preserve
  5996. // them across calls to the intrinsic.
  5997. MachineSDNode *MN = DAG.getMachineNode(
  5998. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5999. SDValue patchableNode = SDValue(MN, 0);
  6000. DAG.setRoot(patchableNode);
  6001. setValue(&I, patchableNode);
  6002. return;
  6003. }
  6004. case Intrinsic::experimental_deoptimize:
  6005. LowerDeoptimizeCall(&I);
  6006. return;
  6007. case Intrinsic::experimental_vector_reduce_v2_fadd:
  6008. case Intrinsic::experimental_vector_reduce_v2_fmul:
  6009. case Intrinsic::experimental_vector_reduce_add:
  6010. case Intrinsic::experimental_vector_reduce_mul:
  6011. case Intrinsic::experimental_vector_reduce_and:
  6012. case Intrinsic::experimental_vector_reduce_or:
  6013. case Intrinsic::experimental_vector_reduce_xor:
  6014. case Intrinsic::experimental_vector_reduce_smax:
  6015. case Intrinsic::experimental_vector_reduce_smin:
  6016. case Intrinsic::experimental_vector_reduce_umax:
  6017. case Intrinsic::experimental_vector_reduce_umin:
  6018. case Intrinsic::experimental_vector_reduce_fmax:
  6019. case Intrinsic::experimental_vector_reduce_fmin:
  6020. visitVectorReduce(I, Intrinsic);
  6021. return;
  6022. case Intrinsic::icall_branch_funnel: {
  6023. SmallVector<SDValue, 16> Ops;
  6024. Ops.push_back(getValue(I.getArgOperand(0)));
  6025. int64_t Offset;
  6026. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6027. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  6028. if (!Base)
  6029. report_fatal_error(
  6030. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6031. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  6032. struct BranchFunnelTarget {
  6033. int64_t Offset;
  6034. SDValue Target;
  6035. };
  6036. SmallVector<BranchFunnelTarget, 8> Targets;
  6037. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  6038. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6039. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6040. if (ElemBase != Base)
  6041. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6042. "to the same GlobalValue");
  6043. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6044. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6045. if (!GA)
  6046. report_fatal_error(
  6047. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6048. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6049. GA->getGlobal(), getCurSDLoc(),
  6050. Val.getValueType(), GA->getOffset())});
  6051. }
  6052. llvm::sort(Targets,
  6053. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6054. return T1.Offset < T2.Offset;
  6055. });
  6056. for (auto &T : Targets) {
  6057. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  6058. Ops.push_back(T.Target);
  6059. }
  6060. Ops.push_back(DAG.getRoot()); // Chain
  6061. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  6062. getCurSDLoc(), MVT::Other, Ops),
  6063. 0);
  6064. DAG.setRoot(N);
  6065. setValue(&I, N);
  6066. HasTailCall = true;
  6067. return;
  6068. }
  6069. case Intrinsic::wasm_landingpad_index:
  6070. // Information this intrinsic contained has been transferred to
  6071. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6072. // delete it now.
  6073. return;
  6074. case Intrinsic::aarch64_settag:
  6075. case Intrinsic::aarch64_settag_zero: {
  6076. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6077. bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
  6078. SDValue Val = TSI.EmitTargetCodeForSetTag(
  6079. DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
  6080. getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
  6081. ZeroMemory);
  6082. DAG.setRoot(Val);
  6083. setValue(&I, Val);
  6084. return;
  6085. }
  6086. case Intrinsic::ptrmask: {
  6087. SDValue Ptr = getValue(I.getOperand(0));
  6088. SDValue Const = getValue(I.getOperand(1));
  6089. EVT DestVT =
  6090. EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6091. setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
  6092. DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
  6093. return;
  6094. }
  6095. }
  6096. }
  6097. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6098. const ConstrainedFPIntrinsic &FPI) {
  6099. SDLoc sdl = getCurSDLoc();
  6100. unsigned Opcode;
  6101. switch (FPI.getIntrinsicID()) {
  6102. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6103. case Intrinsic::experimental_constrained_fadd:
  6104. Opcode = ISD::STRICT_FADD;
  6105. break;
  6106. case Intrinsic::experimental_constrained_fsub:
  6107. Opcode = ISD::STRICT_FSUB;
  6108. break;
  6109. case Intrinsic::experimental_constrained_fmul:
  6110. Opcode = ISD::STRICT_FMUL;
  6111. break;
  6112. case Intrinsic::experimental_constrained_fdiv:
  6113. Opcode = ISD::STRICT_FDIV;
  6114. break;
  6115. case Intrinsic::experimental_constrained_frem:
  6116. Opcode = ISD::STRICT_FREM;
  6117. break;
  6118. case Intrinsic::experimental_constrained_fma:
  6119. Opcode = ISD::STRICT_FMA;
  6120. break;
  6121. case Intrinsic::experimental_constrained_fptosi:
  6122. Opcode = ISD::STRICT_FP_TO_SINT;
  6123. break;
  6124. case Intrinsic::experimental_constrained_fptoui:
  6125. Opcode = ISD::STRICT_FP_TO_UINT;
  6126. break;
  6127. case Intrinsic::experimental_constrained_fptrunc:
  6128. Opcode = ISD::STRICT_FP_ROUND;
  6129. break;
  6130. case Intrinsic::experimental_constrained_fpext:
  6131. Opcode = ISD::STRICT_FP_EXTEND;
  6132. break;
  6133. case Intrinsic::experimental_constrained_sqrt:
  6134. Opcode = ISD::STRICT_FSQRT;
  6135. break;
  6136. case Intrinsic::experimental_constrained_pow:
  6137. Opcode = ISD::STRICT_FPOW;
  6138. break;
  6139. case Intrinsic::experimental_constrained_powi:
  6140. Opcode = ISD::STRICT_FPOWI;
  6141. break;
  6142. case Intrinsic::experimental_constrained_sin:
  6143. Opcode = ISD::STRICT_FSIN;
  6144. break;
  6145. case Intrinsic::experimental_constrained_cos:
  6146. Opcode = ISD::STRICT_FCOS;
  6147. break;
  6148. case Intrinsic::experimental_constrained_exp:
  6149. Opcode = ISD::STRICT_FEXP;
  6150. break;
  6151. case Intrinsic::experimental_constrained_exp2:
  6152. Opcode = ISD::STRICT_FEXP2;
  6153. break;
  6154. case Intrinsic::experimental_constrained_log:
  6155. Opcode = ISD::STRICT_FLOG;
  6156. break;
  6157. case Intrinsic::experimental_constrained_log10:
  6158. Opcode = ISD::STRICT_FLOG10;
  6159. break;
  6160. case Intrinsic::experimental_constrained_log2:
  6161. Opcode = ISD::STRICT_FLOG2;
  6162. break;
  6163. case Intrinsic::experimental_constrained_rint:
  6164. Opcode = ISD::STRICT_FRINT;
  6165. break;
  6166. case Intrinsic::experimental_constrained_nearbyint:
  6167. Opcode = ISD::STRICT_FNEARBYINT;
  6168. break;
  6169. case Intrinsic::experimental_constrained_maxnum:
  6170. Opcode = ISD::STRICT_FMAXNUM;
  6171. break;
  6172. case Intrinsic::experimental_constrained_minnum:
  6173. Opcode = ISD::STRICT_FMINNUM;
  6174. break;
  6175. case Intrinsic::experimental_constrained_ceil:
  6176. Opcode = ISD::STRICT_FCEIL;
  6177. break;
  6178. case Intrinsic::experimental_constrained_floor:
  6179. Opcode = ISD::STRICT_FFLOOR;
  6180. break;
  6181. case Intrinsic::experimental_constrained_round:
  6182. Opcode = ISD::STRICT_FROUND;
  6183. break;
  6184. case Intrinsic::experimental_constrained_trunc:
  6185. Opcode = ISD::STRICT_FTRUNC;
  6186. break;
  6187. }
  6188. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6189. SDValue Chain = getRoot();
  6190. SmallVector<EVT, 4> ValueVTs;
  6191. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6192. ValueVTs.push_back(MVT::Other); // Out chain
  6193. SDVTList VTs = DAG.getVTList(ValueVTs);
  6194. SDValue Result;
  6195. if (Opcode == ISD::STRICT_FP_ROUND)
  6196. Result = DAG.getNode(Opcode, sdl, VTs,
  6197. { Chain, getValue(FPI.getArgOperand(0)),
  6198. DAG.getTargetConstant(0, sdl,
  6199. TLI.getPointerTy(DAG.getDataLayout())) });
  6200. else if (FPI.isUnaryOp())
  6201. Result = DAG.getNode(Opcode, sdl, VTs,
  6202. { Chain, getValue(FPI.getArgOperand(0)) });
  6203. else if (FPI.isTernaryOp())
  6204. Result = DAG.getNode(Opcode, sdl, VTs,
  6205. { Chain, getValue(FPI.getArgOperand(0)),
  6206. getValue(FPI.getArgOperand(1)),
  6207. getValue(FPI.getArgOperand(2)) });
  6208. else
  6209. Result = DAG.getNode(Opcode, sdl, VTs,
  6210. { Chain, getValue(FPI.getArgOperand(0)),
  6211. getValue(FPI.getArgOperand(1)) });
  6212. if (FPI.getExceptionBehavior() !=
  6213. ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
  6214. SDNodeFlags Flags;
  6215. Flags.setFPExcept(true);
  6216. Result->setFlags(Flags);
  6217. }
  6218. assert(Result.getNode()->getNumValues() == 2);
  6219. SDValue OutChain = Result.getValue(1);
  6220. DAG.setRoot(OutChain);
  6221. SDValue FPResult = Result.getValue(0);
  6222. setValue(&FPI, FPResult);
  6223. }
  6224. std::pair<SDValue, SDValue>
  6225. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6226. const BasicBlock *EHPadBB) {
  6227. MachineFunction &MF = DAG.getMachineFunction();
  6228. MachineModuleInfo &MMI = MF.getMMI();
  6229. MCSymbol *BeginLabel = nullptr;
  6230. if (EHPadBB) {
  6231. // Insert a label before the invoke call to mark the try range. This can be
  6232. // used to detect deletion of the invoke via the MachineModuleInfo.
  6233. BeginLabel = MMI.getContext().createTempSymbol();
  6234. // For SjLj, keep track of which landing pads go with which invokes
  6235. // so as to maintain the ordering of pads in the LSDA.
  6236. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6237. if (CallSiteIndex) {
  6238. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6239. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6240. // Now that the call site is handled, stop tracking it.
  6241. MMI.setCurrentCallSite(0);
  6242. }
  6243. // Both PendingLoads and PendingExports must be flushed here;
  6244. // this call might not return.
  6245. (void)getRoot();
  6246. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6247. CLI.setChain(getRoot());
  6248. }
  6249. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6250. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6251. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6252. "Non-null chain expected with non-tail call!");
  6253. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6254. "Null value expected with tail call!");
  6255. if (!Result.second.getNode()) {
  6256. // As a special case, a null chain means that a tail call has been emitted
  6257. // and the DAG root is already updated.
  6258. HasTailCall = true;
  6259. // Since there's no actual continuation from this block, nothing can be
  6260. // relying on us setting vregs for them.
  6261. PendingExports.clear();
  6262. } else {
  6263. DAG.setRoot(Result.second);
  6264. }
  6265. if (EHPadBB) {
  6266. // Insert a label at the end of the invoke call to mark the try range. This
  6267. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6268. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6269. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6270. // Inform MachineModuleInfo of range.
  6271. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6272. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6273. // actually use outlined funclets and their LSDA info style.
  6274. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6275. assert(CLI.CS);
  6276. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6277. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6278. BeginLabel, EndLabel);
  6279. } else if (!isScopedEHPersonality(Pers)) {
  6280. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6281. }
  6282. }
  6283. return Result;
  6284. }
  6285. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6286. bool isTailCall,
  6287. const BasicBlock *EHPadBB) {
  6288. auto &DL = DAG.getDataLayout();
  6289. FunctionType *FTy = CS.getFunctionType();
  6290. Type *RetTy = CS.getType();
  6291. TargetLowering::ArgListTy Args;
  6292. Args.reserve(CS.arg_size());
  6293. const Value *SwiftErrorVal = nullptr;
  6294. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6295. // We can't tail call inside a function with a swifterror argument. Lowering
  6296. // does not support this yet. It would have to move into the swifterror
  6297. // register before the call.
  6298. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6299. if (TLI.supportSwiftError() &&
  6300. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6301. isTailCall = false;
  6302. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6303. i != e; ++i) {
  6304. TargetLowering::ArgListEntry Entry;
  6305. const Value *V = *i;
  6306. // Skip empty types
  6307. if (V->getType()->isEmptyTy())
  6308. continue;
  6309. SDValue ArgNode = getValue(V);
  6310. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6311. Entry.setAttributes(&CS, i - CS.arg_begin());
  6312. // Use swifterror virtual register as input to the call.
  6313. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6314. SwiftErrorVal = V;
  6315. // We find the virtual register for the actual swifterror argument.
  6316. // Instead of using the Value, we use the virtual register instead.
  6317. Entry.Node = DAG.getRegister(
  6318. SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
  6319. EVT(TLI.getPointerTy(DL)));
  6320. }
  6321. Args.push_back(Entry);
  6322. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6323. // might point to function-local memory), we can't meaningfully tail-call.
  6324. if (Entry.IsSRet && isa<Instruction>(V))
  6325. isTailCall = false;
  6326. }
  6327. // Check if target-independent constraints permit a tail call here.
  6328. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6329. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6330. isTailCall = false;
  6331. // Disable tail calls if there is an swifterror argument. Targets have not
  6332. // been updated to support tail calls.
  6333. if (TLI.supportSwiftError() && SwiftErrorVal)
  6334. isTailCall = false;
  6335. TargetLowering::CallLoweringInfo CLI(DAG);
  6336. CLI.setDebugLoc(getCurSDLoc())
  6337. .setChain(getRoot())
  6338. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6339. .setTailCall(isTailCall)
  6340. .setConvergent(CS.isConvergent());
  6341. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6342. if (Result.first.getNode()) {
  6343. const Instruction *Inst = CS.getInstruction();
  6344. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6345. setValue(Inst, Result.first);
  6346. }
  6347. // The last element of CLI.InVals has the SDValue for swifterror return.
  6348. // Here we copy it to a virtual register and update SwiftErrorMap for
  6349. // book-keeping.
  6350. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6351. // Get the last element of InVals.
  6352. SDValue Src = CLI.InVals.back();
  6353. Register VReg = SwiftError.getOrCreateVRegDefAt(
  6354. CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
  6355. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6356. DAG.setRoot(CopyNode);
  6357. }
  6358. }
  6359. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6360. SelectionDAGBuilder &Builder) {
  6361. // Check to see if this load can be trivially constant folded, e.g. if the
  6362. // input is from a string literal.
  6363. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6364. // Cast pointer to the type we really want to load.
  6365. Type *LoadTy =
  6366. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6367. if (LoadVT.isVector())
  6368. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6369. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6370. PointerType::getUnqual(LoadTy));
  6371. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6372. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6373. return Builder.getValue(LoadCst);
  6374. }
  6375. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6376. // still constant memory, the input chain can be the entry node.
  6377. SDValue Root;
  6378. bool ConstantMemory = false;
  6379. // Do not serialize (non-volatile) loads of constant memory with anything.
  6380. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6381. Root = Builder.DAG.getEntryNode();
  6382. ConstantMemory = true;
  6383. } else {
  6384. // Do not serialize non-volatile loads against each other.
  6385. Root = Builder.DAG.getRoot();
  6386. }
  6387. SDValue Ptr = Builder.getValue(PtrVal);
  6388. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6389. Ptr, MachinePointerInfo(PtrVal),
  6390. /* Alignment = */ 1);
  6391. if (!ConstantMemory)
  6392. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6393. return LoadVal;
  6394. }
  6395. /// Record the value for an instruction that produces an integer result,
  6396. /// converting the type where necessary.
  6397. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6398. SDValue Value,
  6399. bool IsSigned) {
  6400. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6401. I.getType(), true);
  6402. if (IsSigned)
  6403. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6404. else
  6405. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6406. setValue(&I, Value);
  6407. }
  6408. /// See if we can lower a memcmp call into an optimized form. If so, return
  6409. /// true and lower it. Otherwise return false, and it will be lowered like a
  6410. /// normal call.
  6411. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6412. /// correct prototype.
  6413. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6414. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6415. const Value *Size = I.getArgOperand(2);
  6416. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6417. if (CSize && CSize->getZExtValue() == 0) {
  6418. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6419. I.getType(), true);
  6420. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6421. return true;
  6422. }
  6423. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6424. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6425. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6426. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6427. if (Res.first.getNode()) {
  6428. processIntegerCallValue(I, Res.first, true);
  6429. PendingLoads.push_back(Res.second);
  6430. return true;
  6431. }
  6432. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6433. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6434. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6435. return false;
  6436. // If the target has a fast compare for the given size, it will return a
  6437. // preferred load type for that size. Require that the load VT is legal and
  6438. // that the target supports unaligned loads of that type. Otherwise, return
  6439. // INVALID.
  6440. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6441. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6442. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6443. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6444. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6445. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6446. // TODO: Check alignment of src and dest ptrs.
  6447. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6448. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6449. if (!TLI.isTypeLegal(LVT) ||
  6450. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6451. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6452. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6453. }
  6454. return LVT;
  6455. };
  6456. // This turns into unaligned loads. We only do this if the target natively
  6457. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6458. // we'll only produce a small number of byte loads.
  6459. MVT LoadVT;
  6460. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6461. switch (NumBitsToCompare) {
  6462. default:
  6463. return false;
  6464. case 16:
  6465. LoadVT = MVT::i16;
  6466. break;
  6467. case 32:
  6468. LoadVT = MVT::i32;
  6469. break;
  6470. case 64:
  6471. case 128:
  6472. case 256:
  6473. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6474. break;
  6475. }
  6476. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6477. return false;
  6478. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6479. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6480. // Bitcast to a wide integer type if the loads are vectors.
  6481. if (LoadVT.isVector()) {
  6482. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6483. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6484. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6485. }
  6486. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6487. processIntegerCallValue(I, Cmp, false);
  6488. return true;
  6489. }
  6490. /// See if we can lower a memchr call into an optimized form. If so, return
  6491. /// true and lower it. Otherwise return false, and it will be lowered like a
  6492. /// normal call.
  6493. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6494. /// correct prototype.
  6495. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6496. const Value *Src = I.getArgOperand(0);
  6497. const Value *Char = I.getArgOperand(1);
  6498. const Value *Length = I.getArgOperand(2);
  6499. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6500. std::pair<SDValue, SDValue> Res =
  6501. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6502. getValue(Src), getValue(Char), getValue(Length),
  6503. MachinePointerInfo(Src));
  6504. if (Res.first.getNode()) {
  6505. setValue(&I, Res.first);
  6506. PendingLoads.push_back(Res.second);
  6507. return true;
  6508. }
  6509. return false;
  6510. }
  6511. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6512. /// true and lower it. Otherwise return false, and it will be lowered like a
  6513. /// normal call.
  6514. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6515. /// correct prototype.
  6516. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6517. SDValue Dst = getValue(I.getArgOperand(0));
  6518. SDValue Src = getValue(I.getArgOperand(1));
  6519. SDValue Size = getValue(I.getArgOperand(2));
  6520. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6521. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6522. unsigned Align = std::min(DstAlign, SrcAlign);
  6523. if (Align == 0) // Alignment of one or both could not be inferred.
  6524. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6525. bool isVol = false;
  6526. SDLoc sdl = getCurSDLoc();
  6527. // In the mempcpy context we need to pass in a false value for isTailCall
  6528. // because the return pointer needs to be adjusted by the size of
  6529. // the copied memory.
  6530. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6531. false, /*isTailCall=*/false,
  6532. MachinePointerInfo(I.getArgOperand(0)),
  6533. MachinePointerInfo(I.getArgOperand(1)));
  6534. assert(MC.getNode() != nullptr &&
  6535. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6536. DAG.setRoot(MC);
  6537. // Check if Size needs to be truncated or extended.
  6538. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6539. // Adjust return pointer to point just past the last dst byte.
  6540. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6541. Dst, Size);
  6542. setValue(&I, DstPlusSize);
  6543. return true;
  6544. }
  6545. /// See if we can lower a strcpy call into an optimized form. If so, return
  6546. /// true and lower it, otherwise return false and it will be lowered like a
  6547. /// normal call.
  6548. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6549. /// correct prototype.
  6550. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6551. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6552. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6553. std::pair<SDValue, SDValue> Res =
  6554. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6555. getValue(Arg0), getValue(Arg1),
  6556. MachinePointerInfo(Arg0),
  6557. MachinePointerInfo(Arg1), isStpcpy);
  6558. if (Res.first.getNode()) {
  6559. setValue(&I, Res.first);
  6560. DAG.setRoot(Res.second);
  6561. return true;
  6562. }
  6563. return false;
  6564. }
  6565. /// See if we can lower a strcmp call into an optimized form. If so, return
  6566. /// true and lower it, otherwise return false and it will be lowered like a
  6567. /// normal call.
  6568. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6569. /// correct prototype.
  6570. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6571. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6572. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6573. std::pair<SDValue, SDValue> Res =
  6574. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6575. getValue(Arg0), getValue(Arg1),
  6576. MachinePointerInfo(Arg0),
  6577. MachinePointerInfo(Arg1));
  6578. if (Res.first.getNode()) {
  6579. processIntegerCallValue(I, Res.first, true);
  6580. PendingLoads.push_back(Res.second);
  6581. return true;
  6582. }
  6583. return false;
  6584. }
  6585. /// See if we can lower a strlen call into an optimized form. If so, return
  6586. /// true and lower it, otherwise return false and it will be lowered like a
  6587. /// normal call.
  6588. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6589. /// correct prototype.
  6590. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6591. const Value *Arg0 = I.getArgOperand(0);
  6592. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6593. std::pair<SDValue, SDValue> Res =
  6594. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6595. getValue(Arg0), MachinePointerInfo(Arg0));
  6596. if (Res.first.getNode()) {
  6597. processIntegerCallValue(I, Res.first, false);
  6598. PendingLoads.push_back(Res.second);
  6599. return true;
  6600. }
  6601. return false;
  6602. }
  6603. /// See if we can lower a strnlen call into an optimized form. If so, return
  6604. /// true and lower it, otherwise return false and it will be lowered like a
  6605. /// normal call.
  6606. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6607. /// correct prototype.
  6608. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6609. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6610. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6611. std::pair<SDValue, SDValue> Res =
  6612. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6613. getValue(Arg0), getValue(Arg1),
  6614. MachinePointerInfo(Arg0));
  6615. if (Res.first.getNode()) {
  6616. processIntegerCallValue(I, Res.first, false);
  6617. PendingLoads.push_back(Res.second);
  6618. return true;
  6619. }
  6620. return false;
  6621. }
  6622. /// See if we can lower a unary 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::visitUnaryFloatCall(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 Tmp = getValue(I.getArgOperand(0));
  6633. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6634. return true;
  6635. }
  6636. /// See if we can lower a binary floating-point operation into an SDNode with
  6637. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6638. /// false, and it will be lowered like a normal call.
  6639. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6640. /// correct prototype.
  6641. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6642. unsigned Opcode) {
  6643. // We already checked this call's prototype; verify it doesn't modify errno.
  6644. if (!I.onlyReadsMemory())
  6645. return false;
  6646. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6647. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6648. EVT VT = Tmp0.getValueType();
  6649. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6650. return true;
  6651. }
  6652. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6653. // Handle inline assembly differently.
  6654. if (isa<InlineAsm>(I.getCalledValue())) {
  6655. visitInlineAsm(&I);
  6656. return;
  6657. }
  6658. if (Function *F = I.getCalledFunction()) {
  6659. if (F->isDeclaration()) {
  6660. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6661. unsigned IID = F->getIntrinsicID();
  6662. if (!IID)
  6663. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6664. IID = II->getIntrinsicID(F);
  6665. if (IID) {
  6666. visitIntrinsicCall(I, IID);
  6667. return;
  6668. }
  6669. }
  6670. // Check for well-known libc/libm calls. If the function is internal, it
  6671. // can't be a library call. Don't do the check if marked as nobuiltin for
  6672. // some reason or the call site requires strict floating point semantics.
  6673. LibFunc Func;
  6674. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6675. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6676. LibInfo->hasOptimizedCodeGen(Func)) {
  6677. switch (Func) {
  6678. default: break;
  6679. case LibFunc_copysign:
  6680. case LibFunc_copysignf:
  6681. case LibFunc_copysignl:
  6682. // We already checked this call's prototype; verify it doesn't modify
  6683. // errno.
  6684. if (I.onlyReadsMemory()) {
  6685. SDValue LHS = getValue(I.getArgOperand(0));
  6686. SDValue RHS = getValue(I.getArgOperand(1));
  6687. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6688. LHS.getValueType(), LHS, RHS));
  6689. return;
  6690. }
  6691. break;
  6692. case LibFunc_fabs:
  6693. case LibFunc_fabsf:
  6694. case LibFunc_fabsl:
  6695. if (visitUnaryFloatCall(I, ISD::FABS))
  6696. return;
  6697. break;
  6698. case LibFunc_fmin:
  6699. case LibFunc_fminf:
  6700. case LibFunc_fminl:
  6701. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6702. return;
  6703. break;
  6704. case LibFunc_fmax:
  6705. case LibFunc_fmaxf:
  6706. case LibFunc_fmaxl:
  6707. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6708. return;
  6709. break;
  6710. case LibFunc_sin:
  6711. case LibFunc_sinf:
  6712. case LibFunc_sinl:
  6713. if (visitUnaryFloatCall(I, ISD::FSIN))
  6714. return;
  6715. break;
  6716. case LibFunc_cos:
  6717. case LibFunc_cosf:
  6718. case LibFunc_cosl:
  6719. if (visitUnaryFloatCall(I, ISD::FCOS))
  6720. return;
  6721. break;
  6722. case LibFunc_sqrt:
  6723. case LibFunc_sqrtf:
  6724. case LibFunc_sqrtl:
  6725. case LibFunc_sqrt_finite:
  6726. case LibFunc_sqrtf_finite:
  6727. case LibFunc_sqrtl_finite:
  6728. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6729. return;
  6730. break;
  6731. case LibFunc_floor:
  6732. case LibFunc_floorf:
  6733. case LibFunc_floorl:
  6734. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6735. return;
  6736. break;
  6737. case LibFunc_nearbyint:
  6738. case LibFunc_nearbyintf:
  6739. case LibFunc_nearbyintl:
  6740. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6741. return;
  6742. break;
  6743. case LibFunc_ceil:
  6744. case LibFunc_ceilf:
  6745. case LibFunc_ceill:
  6746. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6747. return;
  6748. break;
  6749. case LibFunc_rint:
  6750. case LibFunc_rintf:
  6751. case LibFunc_rintl:
  6752. if (visitUnaryFloatCall(I, ISD::FRINT))
  6753. return;
  6754. break;
  6755. case LibFunc_round:
  6756. case LibFunc_roundf:
  6757. case LibFunc_roundl:
  6758. if (visitUnaryFloatCall(I, ISD::FROUND))
  6759. return;
  6760. break;
  6761. case LibFunc_trunc:
  6762. case LibFunc_truncf:
  6763. case LibFunc_truncl:
  6764. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6765. return;
  6766. break;
  6767. case LibFunc_log2:
  6768. case LibFunc_log2f:
  6769. case LibFunc_log2l:
  6770. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6771. return;
  6772. break;
  6773. case LibFunc_exp2:
  6774. case LibFunc_exp2f:
  6775. case LibFunc_exp2l:
  6776. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6777. return;
  6778. break;
  6779. case LibFunc_memcmp:
  6780. if (visitMemCmpCall(I))
  6781. return;
  6782. break;
  6783. case LibFunc_mempcpy:
  6784. if (visitMemPCpyCall(I))
  6785. return;
  6786. break;
  6787. case LibFunc_memchr:
  6788. if (visitMemChrCall(I))
  6789. return;
  6790. break;
  6791. case LibFunc_strcpy:
  6792. if (visitStrCpyCall(I, false))
  6793. return;
  6794. break;
  6795. case LibFunc_stpcpy:
  6796. if (visitStrCpyCall(I, true))
  6797. return;
  6798. break;
  6799. case LibFunc_strcmp:
  6800. if (visitStrCmpCall(I))
  6801. return;
  6802. break;
  6803. case LibFunc_strlen:
  6804. if (visitStrLenCall(I))
  6805. return;
  6806. break;
  6807. case LibFunc_strnlen:
  6808. if (visitStrNLenCall(I))
  6809. return;
  6810. break;
  6811. }
  6812. }
  6813. }
  6814. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6815. // have to do anything here to lower funclet bundles.
  6816. assert(!I.hasOperandBundlesOtherThan(
  6817. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6818. "Cannot lower calls with arbitrary operand bundles!");
  6819. SDValue Callee = getValue(I.getCalledValue());
  6820. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6821. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6822. else
  6823. // Check if we can potentially perform a tail call. More detailed checking
  6824. // is be done within LowerCallTo, after more information about the call is
  6825. // known.
  6826. LowerCallTo(&I, Callee, I.isTailCall());
  6827. }
  6828. namespace {
  6829. /// AsmOperandInfo - This contains information for each constraint that we are
  6830. /// lowering.
  6831. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6832. public:
  6833. /// CallOperand - If this is the result output operand or a clobber
  6834. /// this is null, otherwise it is the incoming operand to the CallInst.
  6835. /// This gets modified as the asm is processed.
  6836. SDValue CallOperand;
  6837. /// AssignedRegs - If this is a register or register class operand, this
  6838. /// contains the set of register corresponding to the operand.
  6839. RegsForValue AssignedRegs;
  6840. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6841. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6842. }
  6843. /// Whether or not this operand accesses memory
  6844. bool hasMemory(const TargetLowering &TLI) const {
  6845. // Indirect operand accesses access memory.
  6846. if (isIndirect)
  6847. return true;
  6848. for (const auto &Code : Codes)
  6849. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6850. return true;
  6851. return false;
  6852. }
  6853. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6854. /// corresponds to. If there is no Value* for this operand, it returns
  6855. /// MVT::Other.
  6856. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6857. const DataLayout &DL) const {
  6858. if (!CallOperandVal) return MVT::Other;
  6859. if (isa<BasicBlock>(CallOperandVal))
  6860. return TLI.getPointerTy(DL);
  6861. llvm::Type *OpTy = CallOperandVal->getType();
  6862. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6863. // If this is an indirect operand, the operand is a pointer to the
  6864. // accessed type.
  6865. if (isIndirect) {
  6866. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6867. if (!PtrTy)
  6868. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6869. OpTy = PtrTy->getElementType();
  6870. }
  6871. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6872. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6873. if (STy->getNumElements() == 1)
  6874. OpTy = STy->getElementType(0);
  6875. // If OpTy is not a single value, it may be a struct/union that we
  6876. // can tile with integers.
  6877. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6878. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6879. switch (BitSize) {
  6880. default: break;
  6881. case 1:
  6882. case 8:
  6883. case 16:
  6884. case 32:
  6885. case 64:
  6886. case 128:
  6887. OpTy = IntegerType::get(Context, BitSize);
  6888. break;
  6889. }
  6890. }
  6891. return TLI.getValueType(DL, OpTy, true);
  6892. }
  6893. };
  6894. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6895. } // end anonymous namespace
  6896. /// Make sure that the output operand \p OpInfo and its corresponding input
  6897. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6898. /// out).
  6899. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6900. SDISelAsmOperandInfo &MatchingOpInfo,
  6901. SelectionDAG &DAG) {
  6902. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6903. return;
  6904. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6905. const auto &TLI = DAG.getTargetLoweringInfo();
  6906. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6907. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6908. OpInfo.ConstraintVT);
  6909. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6910. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6911. MatchingOpInfo.ConstraintVT);
  6912. if ((OpInfo.ConstraintVT.isInteger() !=
  6913. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6914. (MatchRC.second != InputRC.second)) {
  6915. // FIXME: error out in a more elegant fashion
  6916. report_fatal_error("Unsupported asm: input constraint"
  6917. " with a matching output constraint of"
  6918. " incompatible type!");
  6919. }
  6920. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6921. }
  6922. /// Get a direct memory input to behave well as an indirect operand.
  6923. /// This may introduce stores, hence the need for a \p Chain.
  6924. /// \return The (possibly updated) chain.
  6925. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6926. SDISelAsmOperandInfo &OpInfo,
  6927. SelectionDAG &DAG) {
  6928. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6929. // If we don't have an indirect input, put it in the constpool if we can,
  6930. // otherwise spill it to a stack slot.
  6931. // TODO: This isn't quite right. We need to handle these according to
  6932. // the addressing mode that the constraint wants. Also, this may take
  6933. // an additional register for the computation and we don't want that
  6934. // either.
  6935. // If the operand is a float, integer, or vector constant, spill to a
  6936. // constant pool entry to get its address.
  6937. const Value *OpVal = OpInfo.CallOperandVal;
  6938. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6939. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6940. OpInfo.CallOperand = DAG.getConstantPool(
  6941. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6942. return Chain;
  6943. }
  6944. // Otherwise, create a stack slot and emit a store to it before the asm.
  6945. Type *Ty = OpVal->getType();
  6946. auto &DL = DAG.getDataLayout();
  6947. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6948. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6949. MachineFunction &MF = DAG.getMachineFunction();
  6950. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6951. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6952. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6953. MachinePointerInfo::getFixedStack(MF, SSFI),
  6954. TLI.getMemValueType(DL, Ty));
  6955. OpInfo.CallOperand = StackSlot;
  6956. return Chain;
  6957. }
  6958. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6959. /// specified operand. We prefer to assign virtual registers, to allow the
  6960. /// register allocator to handle the assignment process. However, if the asm
  6961. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6962. /// allocation. This produces generally horrible, but correct, code.
  6963. ///
  6964. /// OpInfo describes the operand
  6965. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6966. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6967. SDISelAsmOperandInfo &OpInfo,
  6968. SDISelAsmOperandInfo &RefOpInfo) {
  6969. LLVMContext &Context = *DAG.getContext();
  6970. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6971. MachineFunction &MF = DAG.getMachineFunction();
  6972. SmallVector<unsigned, 4> Regs;
  6973. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6974. // No work to do for memory operations.
  6975. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6976. return;
  6977. // If this is a constraint for a single physreg, or a constraint for a
  6978. // register class, find it.
  6979. unsigned AssignedReg;
  6980. const TargetRegisterClass *RC;
  6981. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6982. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6983. // RC is unset only on failure. Return immediately.
  6984. if (!RC)
  6985. return;
  6986. // Get the actual register value type. This is important, because the user
  6987. // may have asked for (e.g.) the AX register in i32 type. We need to
  6988. // remember that AX is actually i16 to get the right extension.
  6989. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6990. if (OpInfo.ConstraintVT != MVT::Other) {
  6991. // If this is an FP operand in an integer register (or visa versa), or more
  6992. // generally if the operand value disagrees with the register class we plan
  6993. // to stick it in, fix the operand type.
  6994. //
  6995. // If this is an input value, the bitcast to the new type is done now.
  6996. // Bitcast for output value is done at the end of visitInlineAsm().
  6997. if ((OpInfo.Type == InlineAsm::isOutput ||
  6998. OpInfo.Type == InlineAsm::isInput) &&
  6999. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  7000. // Try to convert to the first EVT that the reg class contains. If the
  7001. // types are identical size, use a bitcast to convert (e.g. two differing
  7002. // vector types). Note: output bitcast is done at the end of
  7003. // visitInlineAsm().
  7004. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  7005. // Exclude indirect inputs while they are unsupported because the code
  7006. // to perform the load is missing and thus OpInfo.CallOperand still
  7007. // refers to the input address rather than the pointed-to value.
  7008. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  7009. OpInfo.CallOperand =
  7010. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  7011. OpInfo.ConstraintVT = RegVT;
  7012. // If the operand is an FP value and we want it in integer registers,
  7013. // use the corresponding integer type. This turns an f64 value into
  7014. // i64, which can be passed with two i32 values on a 32-bit machine.
  7015. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  7016. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  7017. if (OpInfo.Type == InlineAsm::isInput)
  7018. OpInfo.CallOperand =
  7019. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  7020. OpInfo.ConstraintVT = VT;
  7021. }
  7022. }
  7023. }
  7024. // No need to allocate a matching input constraint since the constraint it's
  7025. // matching to has already been allocated.
  7026. if (OpInfo.isMatchingInputConstraint())
  7027. return;
  7028. EVT ValueVT = OpInfo.ConstraintVT;
  7029. if (OpInfo.ConstraintVT == MVT::Other)
  7030. ValueVT = RegVT;
  7031. // Initialize NumRegs.
  7032. unsigned NumRegs = 1;
  7033. if (OpInfo.ConstraintVT != MVT::Other)
  7034. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  7035. // If this is a constraint for a specific physical register, like {r17},
  7036. // assign it now.
  7037. // If this associated to a specific register, initialize iterator to correct
  7038. // place. If virtual, make sure we have enough registers
  7039. // Initialize iterator if necessary
  7040. TargetRegisterClass::iterator I = RC->begin();
  7041. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  7042. // Do not check for single registers.
  7043. if (AssignedReg) {
  7044. for (; *I != AssignedReg; ++I)
  7045. assert(I != RC->end() && "AssignedReg should be member of RC");
  7046. }
  7047. for (; NumRegs; --NumRegs, ++I) {
  7048. assert(I != RC->end() && "Ran out of registers to allocate!");
  7049. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  7050. Regs.push_back(R);
  7051. }
  7052. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  7053. }
  7054. static unsigned
  7055. findMatchingInlineAsmOperand(unsigned OperandNo,
  7056. const std::vector<SDValue> &AsmNodeOperands) {
  7057. // Scan until we find the definition we already emitted of this operand.
  7058. unsigned CurOp = InlineAsm::Op_FirstOperand;
  7059. for (; OperandNo; --OperandNo) {
  7060. // Advance to the next operand.
  7061. unsigned OpFlag =
  7062. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7063. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7064. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7065. InlineAsm::isMemKind(OpFlag)) &&
  7066. "Skipped past definitions?");
  7067. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7068. }
  7069. return CurOp;
  7070. }
  7071. namespace {
  7072. class ExtraFlags {
  7073. unsigned Flags = 0;
  7074. public:
  7075. explicit ExtraFlags(ImmutableCallSite CS) {
  7076. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7077. if (IA->hasSideEffects())
  7078. Flags |= InlineAsm::Extra_HasSideEffects;
  7079. if (IA->isAlignStack())
  7080. Flags |= InlineAsm::Extra_IsAlignStack;
  7081. if (CS.isConvergent())
  7082. Flags |= InlineAsm::Extra_IsConvergent;
  7083. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7084. }
  7085. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7086. // Ideally, we would only check against memory constraints. However, the
  7087. // meaning of an Other constraint can be target-specific and we can't easily
  7088. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7089. // for Other constraints as well.
  7090. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7091. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7092. if (OpInfo.Type == InlineAsm::isInput)
  7093. Flags |= InlineAsm::Extra_MayLoad;
  7094. else if (OpInfo.Type == InlineAsm::isOutput)
  7095. Flags |= InlineAsm::Extra_MayStore;
  7096. else if (OpInfo.Type == InlineAsm::isClobber)
  7097. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7098. }
  7099. }
  7100. unsigned get() const { return Flags; }
  7101. };
  7102. } // end anonymous namespace
  7103. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7104. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  7105. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7106. /// ConstraintOperands - Information about all of the constraints.
  7107. SDISelAsmOperandInfoVector ConstraintOperands;
  7108. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7109. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7110. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  7111. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7112. // AsmDialect, MayLoad, MayStore).
  7113. bool HasSideEffect = IA->hasSideEffects();
  7114. ExtraFlags ExtraInfo(CS);
  7115. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7116. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7117. for (auto &T : TargetConstraints) {
  7118. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7119. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7120. // Compute the value type for each operand.
  7121. if (OpInfo.Type == InlineAsm::isInput ||
  7122. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  7123. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  7124. // Process the call argument. BasicBlocks are labels, currently appearing
  7125. // only in asm's.
  7126. const Instruction *I = CS.getInstruction();
  7127. if (isa<CallBrInst>(I) &&
  7128. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  7129. cast<CallBrInst>(I)->getNumIndirectDests())) {
  7130. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  7131. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7132. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7133. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7134. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7135. } else {
  7136. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7137. }
  7138. OpInfo.ConstraintVT =
  7139. OpInfo
  7140. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  7141. .getSimpleVT();
  7142. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7143. // The return value of the call is this value. As such, there is no
  7144. // corresponding argument.
  7145. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7146. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7147. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7148. DAG.getDataLayout(), STy->getElementType(ResNo));
  7149. } else {
  7150. assert(ResNo == 0 && "Asm only has one result!");
  7151. OpInfo.ConstraintVT =
  7152. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7153. }
  7154. ++ResNo;
  7155. } else {
  7156. OpInfo.ConstraintVT = MVT::Other;
  7157. }
  7158. if (!HasSideEffect)
  7159. HasSideEffect = OpInfo.hasMemory(TLI);
  7160. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7161. // FIXME: Could we compute this on OpInfo rather than T?
  7162. // Compute the constraint code and ConstraintType to use.
  7163. TLI.ComputeConstraintToUse(T, SDValue());
  7164. if (T.ConstraintType == TargetLowering::C_Immediate &&
  7165. OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
  7166. // We've delayed emitting a diagnostic like the "n" constraint because
  7167. // inlining could cause an integer showing up.
  7168. return emitInlineAsmError(
  7169. CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
  7170. "integer constant expression");
  7171. ExtraInfo.update(T);
  7172. }
  7173. // We won't need to flush pending loads if this asm doesn't touch
  7174. // memory and is nonvolatile.
  7175. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7176. bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
  7177. if (IsCallBr) {
  7178. // If this is a callbr we need to flush pending exports since inlineasm_br
  7179. // is a terminator. We need to do this before nodes are glued to
  7180. // the inlineasm_br node.
  7181. Chain = getControlRoot();
  7182. }
  7183. // Second pass over the constraints: compute which constraint option to use.
  7184. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7185. // If this is an output operand with a matching input operand, look up the
  7186. // matching input. If their types mismatch, e.g. one is an integer, the
  7187. // other is floating point, or their sizes are different, flag it as an
  7188. // error.
  7189. if (OpInfo.hasMatchingInput()) {
  7190. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7191. patchMatchingInput(OpInfo, Input, DAG);
  7192. }
  7193. // Compute the constraint code and ConstraintType to use.
  7194. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7195. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7196. OpInfo.Type == InlineAsm::isClobber)
  7197. continue;
  7198. // If this is a memory input, and if the operand is not indirect, do what we
  7199. // need to provide an address for the memory input.
  7200. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7201. !OpInfo.isIndirect) {
  7202. assert((OpInfo.isMultipleAlternative ||
  7203. (OpInfo.Type == InlineAsm::isInput)) &&
  7204. "Can only indirectify direct input operands!");
  7205. // Memory operands really want the address of the value.
  7206. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7207. // There is no longer a Value* corresponding to this operand.
  7208. OpInfo.CallOperandVal = nullptr;
  7209. // It is now an indirect operand.
  7210. OpInfo.isIndirect = true;
  7211. }
  7212. }
  7213. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7214. std::vector<SDValue> AsmNodeOperands;
  7215. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7216. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7217. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7218. // If we have a !srcloc metadata node associated with it, we want to attach
  7219. // this to the ultimately generated inline asm machineinstr. To do this, we
  7220. // pass in the third operand as this (potentially null) inline asm MDNode.
  7221. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7222. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7223. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7224. // bits as operand 3.
  7225. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7226. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7227. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7228. // this, assign virtual and physical registers for inputs and otput.
  7229. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7230. // Assign Registers.
  7231. SDISelAsmOperandInfo &RefOpInfo =
  7232. OpInfo.isMatchingInputConstraint()
  7233. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7234. : OpInfo;
  7235. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7236. switch (OpInfo.Type) {
  7237. case InlineAsm::isOutput:
  7238. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7239. ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7240. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7241. OpInfo.isIndirect)) {
  7242. unsigned ConstraintID =
  7243. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7244. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7245. "Failed to convert memory constraint code to constraint id.");
  7246. // Add information to the INLINEASM node to know about this output.
  7247. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7248. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7249. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7250. MVT::i32));
  7251. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7252. break;
  7253. } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7254. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7255. !OpInfo.isIndirect) ||
  7256. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7257. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7258. // Otherwise, this outputs to a register (directly for C_Register /
  7259. // C_RegisterClass, and a target-defined fashion for
  7260. // C_Immediate/C_Other). Find a register that we can use.
  7261. if (OpInfo.AssignedRegs.Regs.empty()) {
  7262. emitInlineAsmError(
  7263. CS, "couldn't allocate output register for constraint '" +
  7264. Twine(OpInfo.ConstraintCode) + "'");
  7265. return;
  7266. }
  7267. // Add information to the INLINEASM node to know that this register is
  7268. // set.
  7269. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7270. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7271. : InlineAsm::Kind_RegDef,
  7272. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7273. }
  7274. break;
  7275. case InlineAsm::isInput: {
  7276. SDValue InOperandVal = OpInfo.CallOperand;
  7277. if (OpInfo.isMatchingInputConstraint()) {
  7278. // If this is required to match an output register we have already set,
  7279. // just use its register.
  7280. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7281. AsmNodeOperands);
  7282. unsigned OpFlag =
  7283. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7284. if (InlineAsm::isRegDefKind(OpFlag) ||
  7285. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7286. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7287. if (OpInfo.isIndirect) {
  7288. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7289. emitInlineAsmError(CS, "inline asm not supported yet:"
  7290. " don't know how to handle tied "
  7291. "indirect register inputs");
  7292. return;
  7293. }
  7294. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7295. SmallVector<unsigned, 4> Regs;
  7296. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7297. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7298. MachineRegisterInfo &RegInfo =
  7299. DAG.getMachineFunction().getRegInfo();
  7300. for (unsigned i = 0; i != NumRegs; ++i)
  7301. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7302. } else {
  7303. emitInlineAsmError(CS, "inline asm error: This value type register "
  7304. "class is not natively supported!");
  7305. return;
  7306. }
  7307. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7308. SDLoc dl = getCurSDLoc();
  7309. // Use the produced MatchedRegs object to
  7310. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7311. CS.getInstruction());
  7312. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7313. true, OpInfo.getMatchedOperand(), dl,
  7314. DAG, AsmNodeOperands);
  7315. break;
  7316. }
  7317. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7318. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7319. "Unexpected number of operands");
  7320. // Add information to the INLINEASM node to know about this input.
  7321. // See InlineAsm.h isUseOperandTiedToDef.
  7322. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7323. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7324. OpInfo.getMatchedOperand());
  7325. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7326. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7327. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7328. break;
  7329. }
  7330. // Treat indirect 'X' constraint as memory.
  7331. if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7332. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7333. OpInfo.isIndirect)
  7334. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7335. if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7336. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7337. std::vector<SDValue> Ops;
  7338. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7339. Ops, DAG);
  7340. if (Ops.empty()) {
  7341. if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
  7342. if (isa<ConstantSDNode>(InOperandVal)) {
  7343. emitInlineAsmError(CS, "value out of range for constraint '" +
  7344. Twine(OpInfo.ConstraintCode) + "'");
  7345. return;
  7346. }
  7347. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7348. Twine(OpInfo.ConstraintCode) + "'");
  7349. return;
  7350. }
  7351. // Add information to the INLINEASM node to know about this input.
  7352. unsigned ResOpType =
  7353. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7354. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7355. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7356. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7357. break;
  7358. }
  7359. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7360. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7361. assert(InOperandVal.getValueType() ==
  7362. TLI.getPointerTy(DAG.getDataLayout()) &&
  7363. "Memory operands expect pointer values");
  7364. unsigned ConstraintID =
  7365. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7366. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7367. "Failed to convert memory constraint code to constraint id.");
  7368. // Add information to the INLINEASM node to know about this input.
  7369. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7370. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7371. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7372. getCurSDLoc(),
  7373. MVT::i32));
  7374. AsmNodeOperands.push_back(InOperandVal);
  7375. break;
  7376. }
  7377. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7378. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7379. OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
  7380. "Unknown constraint type!");
  7381. // TODO: Support this.
  7382. if (OpInfo.isIndirect) {
  7383. emitInlineAsmError(
  7384. CS, "Don't know how to handle indirect register inputs yet "
  7385. "for constraint '" +
  7386. Twine(OpInfo.ConstraintCode) + "'");
  7387. return;
  7388. }
  7389. // Copy the input into the appropriate registers.
  7390. if (OpInfo.AssignedRegs.Regs.empty()) {
  7391. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7392. Twine(OpInfo.ConstraintCode) + "'");
  7393. return;
  7394. }
  7395. SDLoc dl = getCurSDLoc();
  7396. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7397. Chain, &Flag, CS.getInstruction());
  7398. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7399. dl, DAG, AsmNodeOperands);
  7400. break;
  7401. }
  7402. case InlineAsm::isClobber:
  7403. // Add the clobbered value to the operand list, so that the register
  7404. // allocator is aware that the physreg got clobbered.
  7405. if (!OpInfo.AssignedRegs.Regs.empty())
  7406. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7407. false, 0, getCurSDLoc(), DAG,
  7408. AsmNodeOperands);
  7409. break;
  7410. }
  7411. }
  7412. // Finish up input operands. Set the input chain and add the flag last.
  7413. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7414. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7415. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7416. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7417. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7418. Flag = Chain.getValue(1);
  7419. // Do additional work to generate outputs.
  7420. SmallVector<EVT, 1> ResultVTs;
  7421. SmallVector<SDValue, 1> ResultValues;
  7422. SmallVector<SDValue, 8> OutChains;
  7423. llvm::Type *CSResultType = CS.getType();
  7424. ArrayRef<Type *> ResultTypes;
  7425. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7426. ResultTypes = StructResult->elements();
  7427. else if (!CSResultType->isVoidTy())
  7428. ResultTypes = makeArrayRef(CSResultType);
  7429. auto CurResultType = ResultTypes.begin();
  7430. auto handleRegAssign = [&](SDValue V) {
  7431. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7432. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7433. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7434. ++CurResultType;
  7435. // If the type of the inline asm call site return value is different but has
  7436. // same size as the type of the asm output bitcast it. One example of this
  7437. // is for vectors with different width / number of elements. This can
  7438. // happen for register classes that can contain multiple different value
  7439. // types. The preg or vreg allocated may not have the same VT as was
  7440. // expected.
  7441. //
  7442. // This can also happen for a return value that disagrees with the register
  7443. // class it is put in, eg. a double in a general-purpose register on a
  7444. // 32-bit machine.
  7445. if (ResultVT != V.getValueType() &&
  7446. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7447. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7448. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7449. V.getValueType().isInteger()) {
  7450. // If a result value was tied to an input value, the computed result
  7451. // may have a wider width than the expected result. Extract the
  7452. // relevant portion.
  7453. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7454. }
  7455. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7456. ResultVTs.push_back(ResultVT);
  7457. ResultValues.push_back(V);
  7458. };
  7459. // Deal with output operands.
  7460. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7461. if (OpInfo.Type == InlineAsm::isOutput) {
  7462. SDValue Val;
  7463. // Skip trivial output operands.
  7464. if (OpInfo.AssignedRegs.Regs.empty())
  7465. continue;
  7466. switch (OpInfo.ConstraintType) {
  7467. case TargetLowering::C_Register:
  7468. case TargetLowering::C_RegisterClass:
  7469. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7470. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7471. break;
  7472. case TargetLowering::C_Immediate:
  7473. case TargetLowering::C_Other:
  7474. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7475. OpInfo, DAG);
  7476. break;
  7477. case TargetLowering::C_Memory:
  7478. break; // Already handled.
  7479. case TargetLowering::C_Unknown:
  7480. assert(false && "Unexpected unknown constraint");
  7481. }
  7482. // Indirect output manifest as stores. Record output chains.
  7483. if (OpInfo.isIndirect) {
  7484. const Value *Ptr = OpInfo.CallOperandVal;
  7485. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7486. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7487. MachinePointerInfo(Ptr));
  7488. OutChains.push_back(Store);
  7489. } else {
  7490. // generate CopyFromRegs to associated registers.
  7491. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7492. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7493. for (const SDValue &V : Val->op_values())
  7494. handleRegAssign(V);
  7495. } else
  7496. handleRegAssign(Val);
  7497. }
  7498. }
  7499. }
  7500. // Set results.
  7501. if (!ResultValues.empty()) {
  7502. assert(CurResultType == ResultTypes.end() &&
  7503. "Mismatch in number of ResultTypes");
  7504. assert(ResultValues.size() == ResultTypes.size() &&
  7505. "Mismatch in number of output operands in asm result");
  7506. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7507. DAG.getVTList(ResultVTs), ResultValues);
  7508. setValue(CS.getInstruction(), V);
  7509. }
  7510. // Collect store chains.
  7511. if (!OutChains.empty())
  7512. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7513. // Only Update Root if inline assembly has a memory effect.
  7514. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
  7515. DAG.setRoot(Chain);
  7516. }
  7517. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7518. const Twine &Message) {
  7519. LLVMContext &Ctx = *DAG.getContext();
  7520. Ctx.emitError(CS.getInstruction(), Message);
  7521. // Make sure we leave the DAG in a valid state
  7522. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7523. SmallVector<EVT, 1> ValueVTs;
  7524. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7525. if (ValueVTs.empty())
  7526. return;
  7527. SmallVector<SDValue, 1> Ops;
  7528. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7529. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7530. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7531. }
  7532. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7533. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7534. MVT::Other, getRoot(),
  7535. getValue(I.getArgOperand(0)),
  7536. DAG.getSrcValue(I.getArgOperand(0))));
  7537. }
  7538. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7539. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7540. const DataLayout &DL = DAG.getDataLayout();
  7541. SDValue V = DAG.getVAArg(
  7542. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  7543. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  7544. DL.getABITypeAlignment(I.getType()));
  7545. DAG.setRoot(V.getValue(1));
  7546. if (I.getType()->isPointerTy())
  7547. V = DAG.getPtrExtOrTrunc(
  7548. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  7549. setValue(&I, V);
  7550. }
  7551. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7552. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7553. MVT::Other, getRoot(),
  7554. getValue(I.getArgOperand(0)),
  7555. DAG.getSrcValue(I.getArgOperand(0))));
  7556. }
  7557. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7558. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7559. MVT::Other, getRoot(),
  7560. getValue(I.getArgOperand(0)),
  7561. getValue(I.getArgOperand(1)),
  7562. DAG.getSrcValue(I.getArgOperand(0)),
  7563. DAG.getSrcValue(I.getArgOperand(1))));
  7564. }
  7565. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7566. const Instruction &I,
  7567. SDValue Op) {
  7568. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7569. if (!Range)
  7570. return Op;
  7571. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7572. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7573. return Op;
  7574. APInt Lo = CR.getUnsignedMin();
  7575. if (!Lo.isMinValue())
  7576. return Op;
  7577. APInt Hi = CR.getUnsignedMax();
  7578. unsigned Bits = std::max(Hi.getActiveBits(),
  7579. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7580. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7581. SDLoc SL = getCurSDLoc();
  7582. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7583. DAG.getValueType(SmallVT));
  7584. unsigned NumVals = Op.getNode()->getNumValues();
  7585. if (NumVals == 1)
  7586. return ZExt;
  7587. SmallVector<SDValue, 4> Ops;
  7588. Ops.push_back(ZExt);
  7589. for (unsigned I = 1; I != NumVals; ++I)
  7590. Ops.push_back(Op.getValue(I));
  7591. return DAG.getMergeValues(Ops, SL);
  7592. }
  7593. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7594. /// the call being lowered.
  7595. ///
  7596. /// This is a helper for lowering intrinsics that follow a target calling
  7597. /// convention or require stack pointer adjustment. Only a subset of the
  7598. /// intrinsic's operands need to participate in the calling convention.
  7599. void SelectionDAGBuilder::populateCallLoweringInfo(
  7600. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7601. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7602. bool IsPatchPoint) {
  7603. TargetLowering::ArgListTy Args;
  7604. Args.reserve(NumArgs);
  7605. // Populate the argument list.
  7606. // Attributes for args start at offset 1, after the return attribute.
  7607. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7608. ArgI != ArgE; ++ArgI) {
  7609. const Value *V = Call->getOperand(ArgI);
  7610. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7611. TargetLowering::ArgListEntry Entry;
  7612. Entry.Node = getValue(V);
  7613. Entry.Ty = V->getType();
  7614. Entry.setAttributes(Call, ArgI);
  7615. Args.push_back(Entry);
  7616. }
  7617. CLI.setDebugLoc(getCurSDLoc())
  7618. .setChain(getRoot())
  7619. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7620. .setDiscardResult(Call->use_empty())
  7621. .setIsPatchPoint(IsPatchPoint);
  7622. }
  7623. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7624. /// or patchpoint target node's operand list.
  7625. ///
  7626. /// Constants are converted to TargetConstants purely as an optimization to
  7627. /// avoid constant materialization and register allocation.
  7628. ///
  7629. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7630. /// generate addess computation nodes, and so FinalizeISel can convert the
  7631. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7632. /// address materialization and register allocation, but may also be required
  7633. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7634. /// alloca in the entry block, then the runtime may assume that the alloca's
  7635. /// StackMap location can be read immediately after compilation and that the
  7636. /// location is valid at any point during execution (this is similar to the
  7637. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7638. /// only available in a register, then the runtime would need to trap when
  7639. /// execution reaches the StackMap in order to read the alloca's location.
  7640. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7641. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7642. SelectionDAGBuilder &Builder) {
  7643. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7644. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7645. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7646. Ops.push_back(
  7647. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7648. Ops.push_back(
  7649. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7650. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7651. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7652. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7653. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7654. } else
  7655. Ops.push_back(OpVal);
  7656. }
  7657. }
  7658. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7659. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7660. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7661. // [live variables...])
  7662. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7663. SDValue Chain, InFlag, Callee, NullPtr;
  7664. SmallVector<SDValue, 32> Ops;
  7665. SDLoc DL = getCurSDLoc();
  7666. Callee = getValue(CI.getCalledValue());
  7667. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7668. // The stackmap intrinsic only records the live variables (the arguemnts
  7669. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7670. // intrinsic, this won't be lowered to a function call. This means we don't
  7671. // have to worry about calling conventions and target specific lowering code.
  7672. // Instead we perform the call lowering right here.
  7673. //
  7674. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7675. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7676. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7677. //
  7678. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7679. InFlag = Chain.getValue(1);
  7680. // Add the <id> and <numBytes> constants.
  7681. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7682. Ops.push_back(DAG.getTargetConstant(
  7683. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7684. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7685. Ops.push_back(DAG.getTargetConstant(
  7686. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7687. MVT::i32));
  7688. // Push live variables for the stack map.
  7689. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7690. // We are not pushing any register mask info here on the operands list,
  7691. // because the stackmap doesn't clobber anything.
  7692. // Push the chain and the glue flag.
  7693. Ops.push_back(Chain);
  7694. Ops.push_back(InFlag);
  7695. // Create the STACKMAP node.
  7696. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7697. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7698. Chain = SDValue(SM, 0);
  7699. InFlag = Chain.getValue(1);
  7700. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7701. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7702. // Set the root to the target-lowered call chain.
  7703. DAG.setRoot(Chain);
  7704. // Inform the Frame Information that we have a stackmap in this function.
  7705. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7706. }
  7707. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7708. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7709. const BasicBlock *EHPadBB) {
  7710. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7711. // i32 <numBytes>,
  7712. // i8* <target>,
  7713. // i32 <numArgs>,
  7714. // [Args...],
  7715. // [live variables...])
  7716. CallingConv::ID CC = CS.getCallingConv();
  7717. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7718. bool HasDef = !CS->getType()->isVoidTy();
  7719. SDLoc dl = getCurSDLoc();
  7720. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7721. // Handle immediate and symbolic callees.
  7722. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7723. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7724. /*isTarget=*/true);
  7725. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7726. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7727. SDLoc(SymbolicCallee),
  7728. SymbolicCallee->getValueType(0));
  7729. // Get the real number of arguments participating in the call <numArgs>
  7730. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7731. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7732. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7733. // Intrinsics include all meta-operands up to but not including CC.
  7734. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7735. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7736. "Not enough arguments provided to the patchpoint intrinsic");
  7737. // For AnyRegCC the arguments are lowered later on manually.
  7738. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7739. Type *ReturnTy =
  7740. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7741. TargetLowering::CallLoweringInfo CLI(DAG);
  7742. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7743. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7744. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7745. SDNode *CallEnd = Result.second.getNode();
  7746. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7747. CallEnd = CallEnd->getOperand(0).getNode();
  7748. /// Get a call instruction from the call sequence chain.
  7749. /// Tail calls are not allowed.
  7750. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7751. "Expected a callseq node.");
  7752. SDNode *Call = CallEnd->getOperand(0).getNode();
  7753. bool HasGlue = Call->getGluedNode();
  7754. // Replace the target specific call node with the patchable intrinsic.
  7755. SmallVector<SDValue, 8> Ops;
  7756. // Add the <id> and <numBytes> constants.
  7757. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7758. Ops.push_back(DAG.getTargetConstant(
  7759. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7760. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7761. Ops.push_back(DAG.getTargetConstant(
  7762. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7763. MVT::i32));
  7764. // Add the callee.
  7765. Ops.push_back(Callee);
  7766. // Adjust <numArgs> to account for any arguments that have been passed on the
  7767. // stack instead.
  7768. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7769. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7770. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7771. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7772. // Add the calling convention
  7773. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7774. // Add the arguments we omitted previously. The register allocator should
  7775. // place these in any free register.
  7776. if (IsAnyRegCC)
  7777. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7778. Ops.push_back(getValue(CS.getArgument(i)));
  7779. // Push the arguments from the call instruction up to the register mask.
  7780. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7781. Ops.append(Call->op_begin() + 2, e);
  7782. // Push live variables for the stack map.
  7783. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7784. // Push the register mask info.
  7785. if (HasGlue)
  7786. Ops.push_back(*(Call->op_end()-2));
  7787. else
  7788. Ops.push_back(*(Call->op_end()-1));
  7789. // Push the chain (this is originally the first operand of the call, but
  7790. // becomes now the last or second to last operand).
  7791. Ops.push_back(*(Call->op_begin()));
  7792. // Push the glue flag (last operand).
  7793. if (HasGlue)
  7794. Ops.push_back(*(Call->op_end()-1));
  7795. SDVTList NodeTys;
  7796. if (IsAnyRegCC && HasDef) {
  7797. // Create the return types based on the intrinsic definition
  7798. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7799. SmallVector<EVT, 3> ValueVTs;
  7800. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7801. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7802. // There is always a chain and a glue type at the end
  7803. ValueVTs.push_back(MVT::Other);
  7804. ValueVTs.push_back(MVT::Glue);
  7805. NodeTys = DAG.getVTList(ValueVTs);
  7806. } else
  7807. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7808. // Replace the target specific call node with a PATCHPOINT node.
  7809. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7810. dl, NodeTys, Ops);
  7811. // Update the NodeMap.
  7812. if (HasDef) {
  7813. if (IsAnyRegCC)
  7814. setValue(CS.getInstruction(), SDValue(MN, 0));
  7815. else
  7816. setValue(CS.getInstruction(), Result.first);
  7817. }
  7818. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7819. // call sequence. Furthermore the location of the chain and glue can change
  7820. // when the AnyReg calling convention is used and the intrinsic returns a
  7821. // value.
  7822. if (IsAnyRegCC && HasDef) {
  7823. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7824. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7825. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7826. } else
  7827. DAG.ReplaceAllUsesWith(Call, MN);
  7828. DAG.DeleteNode(Call);
  7829. // Inform the Frame Information that we have a patchpoint in this function.
  7830. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7831. }
  7832. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7833. unsigned Intrinsic) {
  7834. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7835. SDValue Op1 = getValue(I.getArgOperand(0));
  7836. SDValue Op2;
  7837. if (I.getNumArgOperands() > 1)
  7838. Op2 = getValue(I.getArgOperand(1));
  7839. SDLoc dl = getCurSDLoc();
  7840. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7841. SDValue Res;
  7842. FastMathFlags FMF;
  7843. if (isa<FPMathOperator>(I))
  7844. FMF = I.getFastMathFlags();
  7845. switch (Intrinsic) {
  7846. case Intrinsic::experimental_vector_reduce_v2_fadd:
  7847. if (FMF.allowReassoc())
  7848. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  7849. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
  7850. else
  7851. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7852. break;
  7853. case Intrinsic::experimental_vector_reduce_v2_fmul:
  7854. if (FMF.allowReassoc())
  7855. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  7856. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
  7857. else
  7858. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7859. break;
  7860. case Intrinsic::experimental_vector_reduce_add:
  7861. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7862. break;
  7863. case Intrinsic::experimental_vector_reduce_mul:
  7864. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7865. break;
  7866. case Intrinsic::experimental_vector_reduce_and:
  7867. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7868. break;
  7869. case Intrinsic::experimental_vector_reduce_or:
  7870. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7871. break;
  7872. case Intrinsic::experimental_vector_reduce_xor:
  7873. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7874. break;
  7875. case Intrinsic::experimental_vector_reduce_smax:
  7876. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7877. break;
  7878. case Intrinsic::experimental_vector_reduce_smin:
  7879. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7880. break;
  7881. case Intrinsic::experimental_vector_reduce_umax:
  7882. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7883. break;
  7884. case Intrinsic::experimental_vector_reduce_umin:
  7885. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7886. break;
  7887. case Intrinsic::experimental_vector_reduce_fmax:
  7888. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7889. break;
  7890. case Intrinsic::experimental_vector_reduce_fmin:
  7891. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7892. break;
  7893. default:
  7894. llvm_unreachable("Unhandled vector reduce intrinsic");
  7895. }
  7896. setValue(&I, Res);
  7897. }
  7898. /// Returns an AttributeList representing the attributes applied to the return
  7899. /// value of the given call.
  7900. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7901. SmallVector<Attribute::AttrKind, 2> Attrs;
  7902. if (CLI.RetSExt)
  7903. Attrs.push_back(Attribute::SExt);
  7904. if (CLI.RetZExt)
  7905. Attrs.push_back(Attribute::ZExt);
  7906. if (CLI.IsInReg)
  7907. Attrs.push_back(Attribute::InReg);
  7908. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7909. Attrs);
  7910. }
  7911. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7912. /// implementation, which just calls LowerCall.
  7913. /// FIXME: When all targets are
  7914. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7915. std::pair<SDValue, SDValue>
  7916. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7917. // Handle the incoming return values from the call.
  7918. CLI.Ins.clear();
  7919. Type *OrigRetTy = CLI.RetTy;
  7920. SmallVector<EVT, 4> RetTys;
  7921. SmallVector<uint64_t, 4> Offsets;
  7922. auto &DL = CLI.DAG.getDataLayout();
  7923. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7924. if (CLI.IsPostTypeLegalization) {
  7925. // If we are lowering a libcall after legalization, split the return type.
  7926. SmallVector<EVT, 4> OldRetTys;
  7927. SmallVector<uint64_t, 4> OldOffsets;
  7928. RetTys.swap(OldRetTys);
  7929. Offsets.swap(OldOffsets);
  7930. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7931. EVT RetVT = OldRetTys[i];
  7932. uint64_t Offset = OldOffsets[i];
  7933. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7934. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7935. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7936. RetTys.append(NumRegs, RegisterVT);
  7937. for (unsigned j = 0; j != NumRegs; ++j)
  7938. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7939. }
  7940. }
  7941. SmallVector<ISD::OutputArg, 4> Outs;
  7942. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7943. bool CanLowerReturn =
  7944. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7945. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7946. SDValue DemoteStackSlot;
  7947. int DemoteStackIdx = -100;
  7948. if (!CanLowerReturn) {
  7949. // FIXME: equivalent assert?
  7950. // assert(!CS.hasInAllocaArgument() &&
  7951. // "sret demotion is incompatible with inalloca");
  7952. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7953. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7954. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7955. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7956. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7957. DL.getAllocaAddrSpace());
  7958. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7959. ArgListEntry Entry;
  7960. Entry.Node = DemoteStackSlot;
  7961. Entry.Ty = StackSlotPtrType;
  7962. Entry.IsSExt = false;
  7963. Entry.IsZExt = false;
  7964. Entry.IsInReg = false;
  7965. Entry.IsSRet = true;
  7966. Entry.IsNest = false;
  7967. Entry.IsByVal = false;
  7968. Entry.IsReturned = false;
  7969. Entry.IsSwiftSelf = false;
  7970. Entry.IsSwiftError = false;
  7971. Entry.Alignment = Align;
  7972. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7973. CLI.NumFixedArgs += 1;
  7974. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7975. // sret demotion isn't compatible with tail-calls, since the sret argument
  7976. // points into the callers stack frame.
  7977. CLI.IsTailCall = false;
  7978. } else {
  7979. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7980. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  7981. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7982. ISD::ArgFlagsTy Flags;
  7983. if (NeedsRegBlock) {
  7984. Flags.setInConsecutiveRegs();
  7985. if (I == RetTys.size() - 1)
  7986. Flags.setInConsecutiveRegsLast();
  7987. }
  7988. EVT VT = RetTys[I];
  7989. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7990. CLI.CallConv, VT);
  7991. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7992. CLI.CallConv, VT);
  7993. for (unsigned i = 0; i != NumRegs; ++i) {
  7994. ISD::InputArg MyFlags;
  7995. MyFlags.Flags = Flags;
  7996. MyFlags.VT = RegisterVT;
  7997. MyFlags.ArgVT = VT;
  7998. MyFlags.Used = CLI.IsReturnValueUsed;
  7999. if (CLI.RetTy->isPointerTy()) {
  8000. MyFlags.Flags.setPointer();
  8001. MyFlags.Flags.setPointerAddrSpace(
  8002. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  8003. }
  8004. if (CLI.RetSExt)
  8005. MyFlags.Flags.setSExt();
  8006. if (CLI.RetZExt)
  8007. MyFlags.Flags.setZExt();
  8008. if (CLI.IsInReg)
  8009. MyFlags.Flags.setInReg();
  8010. CLI.Ins.push_back(MyFlags);
  8011. }
  8012. }
  8013. }
  8014. // We push in swifterror return as the last element of CLI.Ins.
  8015. ArgListTy &Args = CLI.getArgs();
  8016. if (supportSwiftError()) {
  8017. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8018. if (Args[i].IsSwiftError) {
  8019. ISD::InputArg MyFlags;
  8020. MyFlags.VT = getPointerTy(DL);
  8021. MyFlags.ArgVT = EVT(getPointerTy(DL));
  8022. MyFlags.Flags.setSwiftError();
  8023. CLI.Ins.push_back(MyFlags);
  8024. }
  8025. }
  8026. }
  8027. // Handle all of the outgoing arguments.
  8028. CLI.Outs.clear();
  8029. CLI.OutVals.clear();
  8030. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8031. SmallVector<EVT, 4> ValueVTs;
  8032. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  8033. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  8034. Type *FinalType = Args[i].Ty;
  8035. if (Args[i].IsByVal)
  8036. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  8037. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8038. FinalType, CLI.CallConv, CLI.IsVarArg);
  8039. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  8040. ++Value) {
  8041. EVT VT = ValueVTs[Value];
  8042. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  8043. SDValue Op = SDValue(Args[i].Node.getNode(),
  8044. Args[i].Node.getResNo() + Value);
  8045. ISD::ArgFlagsTy Flags;
  8046. // Certain targets (such as MIPS), may have a different ABI alignment
  8047. // for a type depending on the context. Give the target a chance to
  8048. // specify the alignment it wants.
  8049. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  8050. if (Args[i].Ty->isPointerTy()) {
  8051. Flags.setPointer();
  8052. Flags.setPointerAddrSpace(
  8053. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  8054. }
  8055. if (Args[i].IsZExt)
  8056. Flags.setZExt();
  8057. if (Args[i].IsSExt)
  8058. Flags.setSExt();
  8059. if (Args[i].IsInReg) {
  8060. // If we are using vectorcall calling convention, a structure that is
  8061. // passed InReg - is surely an HVA
  8062. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  8063. isa<StructType>(FinalType)) {
  8064. // The first value of a structure is marked
  8065. if (0 == Value)
  8066. Flags.setHvaStart();
  8067. Flags.setHva();
  8068. }
  8069. // Set InReg Flag
  8070. Flags.setInReg();
  8071. }
  8072. if (Args[i].IsSRet)
  8073. Flags.setSRet();
  8074. if (Args[i].IsSwiftSelf)
  8075. Flags.setSwiftSelf();
  8076. if (Args[i].IsSwiftError)
  8077. Flags.setSwiftError();
  8078. if (Args[i].IsByVal)
  8079. Flags.setByVal();
  8080. if (Args[i].IsInAlloca) {
  8081. Flags.setInAlloca();
  8082. // Set the byval flag for CCAssignFn callbacks that don't know about
  8083. // inalloca. This way we can know how many bytes we should've allocated
  8084. // and how many bytes a callee cleanup function will pop. If we port
  8085. // inalloca to more targets, we'll have to add custom inalloca handling
  8086. // in the various CC lowering callbacks.
  8087. Flags.setByVal();
  8088. }
  8089. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  8090. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  8091. Type *ElementTy = Ty->getElementType();
  8092. unsigned FrameSize = DL.getTypeAllocSize(
  8093. Args[i].ByValType ? Args[i].ByValType : ElementTy);
  8094. Flags.setByValSize(FrameSize);
  8095. // info is not there but there are cases it cannot get right.
  8096. unsigned FrameAlign;
  8097. if (Args[i].Alignment)
  8098. FrameAlign = Args[i].Alignment;
  8099. else
  8100. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  8101. Flags.setByValAlign(FrameAlign);
  8102. }
  8103. if (Args[i].IsNest)
  8104. Flags.setNest();
  8105. if (NeedsRegBlock)
  8106. Flags.setInConsecutiveRegs();
  8107. Flags.setOrigAlign(OriginalAlignment);
  8108. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8109. CLI.CallConv, VT);
  8110. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8111. CLI.CallConv, VT);
  8112. SmallVector<SDValue, 4> Parts(NumParts);
  8113. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8114. if (Args[i].IsSExt)
  8115. ExtendKind = ISD::SIGN_EXTEND;
  8116. else if (Args[i].IsZExt)
  8117. ExtendKind = ISD::ZERO_EXTEND;
  8118. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8119. // for now.
  8120. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8121. CanLowerReturn) {
  8122. assert((CLI.RetTy == Args[i].Ty ||
  8123. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8124. CLI.RetTy->getPointerAddressSpace() ==
  8125. Args[i].Ty->getPointerAddressSpace())) &&
  8126. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8127. // Before passing 'returned' to the target lowering code, ensure that
  8128. // either the register MVT and the actual EVT are the same size or that
  8129. // the return value and argument are extended in the same way; in these
  8130. // cases it's safe to pass the argument register value unchanged as the
  8131. // return register value (although it's at the target's option whether
  8132. // to do so)
  8133. // TODO: allow code generation to take advantage of partially preserved
  8134. // registers rather than clobbering the entire register when the
  8135. // parameter extension method is not compatible with the return
  8136. // extension method
  8137. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8138. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8139. CLI.RetZExt == Args[i].IsZExt))
  8140. Flags.setReturned();
  8141. }
  8142. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  8143. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  8144. for (unsigned j = 0; j != NumParts; ++j) {
  8145. // if it isn't first piece, alignment must be 1
  8146. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  8147. i < CLI.NumFixedArgs,
  8148. i, j*Parts[j].getValueType().getStoreSize());
  8149. if (NumParts > 1 && j == 0)
  8150. MyFlags.Flags.setSplit();
  8151. else if (j != 0) {
  8152. MyFlags.Flags.setOrigAlign(1);
  8153. if (j == NumParts - 1)
  8154. MyFlags.Flags.setSplitEnd();
  8155. }
  8156. CLI.Outs.push_back(MyFlags);
  8157. CLI.OutVals.push_back(Parts[j]);
  8158. }
  8159. if (NeedsRegBlock && Value == NumValues - 1)
  8160. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8161. }
  8162. }
  8163. SmallVector<SDValue, 4> InVals;
  8164. CLI.Chain = LowerCall(CLI, InVals);
  8165. // Update CLI.InVals to use outside of this function.
  8166. CLI.InVals = InVals;
  8167. // Verify that the target's LowerCall behaved as expected.
  8168. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8169. "LowerCall didn't return a valid chain!");
  8170. assert((!CLI.IsTailCall || InVals.empty()) &&
  8171. "LowerCall emitted a return value for a tail call!");
  8172. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8173. "LowerCall didn't emit the correct number of values!");
  8174. // For a tail call, the return value is merely live-out and there aren't
  8175. // any nodes in the DAG representing it. Return a special value to
  8176. // indicate that a tail call has been emitted and no more Instructions
  8177. // should be processed in the current block.
  8178. if (CLI.IsTailCall) {
  8179. CLI.DAG.setRoot(CLI.Chain);
  8180. return std::make_pair(SDValue(), SDValue());
  8181. }
  8182. #ifndef NDEBUG
  8183. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8184. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8185. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8186. "LowerCall emitted a value with the wrong type!");
  8187. }
  8188. #endif
  8189. SmallVector<SDValue, 4> ReturnValues;
  8190. if (!CanLowerReturn) {
  8191. // The instruction result is the result of loading from the
  8192. // hidden sret parameter.
  8193. SmallVector<EVT, 1> PVTs;
  8194. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8195. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8196. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8197. EVT PtrVT = PVTs[0];
  8198. unsigned NumValues = RetTys.size();
  8199. ReturnValues.resize(NumValues);
  8200. SmallVector<SDValue, 4> Chains(NumValues);
  8201. // An aggregate return value cannot wrap around the address space, so
  8202. // offsets to its parts don't wrap either.
  8203. SDNodeFlags Flags;
  8204. Flags.setNoUnsignedWrap(true);
  8205. for (unsigned i = 0; i < NumValues; ++i) {
  8206. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8207. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8208. PtrVT), Flags);
  8209. SDValue L = CLI.DAG.getLoad(
  8210. RetTys[i], CLI.DL, CLI.Chain, Add,
  8211. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8212. DemoteStackIdx, Offsets[i]),
  8213. /* Alignment = */ 1);
  8214. ReturnValues[i] = L;
  8215. Chains[i] = L.getValue(1);
  8216. }
  8217. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8218. } else {
  8219. // Collect the legal value parts into potentially illegal values
  8220. // that correspond to the original function's return values.
  8221. Optional<ISD::NodeType> AssertOp;
  8222. if (CLI.RetSExt)
  8223. AssertOp = ISD::AssertSext;
  8224. else if (CLI.RetZExt)
  8225. AssertOp = ISD::AssertZext;
  8226. unsigned CurReg = 0;
  8227. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8228. EVT VT = RetTys[I];
  8229. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8230. CLI.CallConv, VT);
  8231. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8232. CLI.CallConv, VT);
  8233. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8234. NumRegs, RegisterVT, VT, nullptr,
  8235. CLI.CallConv, AssertOp));
  8236. CurReg += NumRegs;
  8237. }
  8238. // For a function returning void, there is no return value. We can't create
  8239. // such a node, so we just return a null return value in that case. In
  8240. // that case, nothing will actually look at the value.
  8241. if (ReturnValues.empty())
  8242. return std::make_pair(SDValue(), CLI.Chain);
  8243. }
  8244. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8245. CLI.DAG.getVTList(RetTys), ReturnValues);
  8246. return std::make_pair(Res, CLI.Chain);
  8247. }
  8248. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8249. SmallVectorImpl<SDValue> &Results,
  8250. SelectionDAG &DAG) const {
  8251. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8252. Results.push_back(Res);
  8253. }
  8254. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8255. llvm_unreachable("LowerOperation not implemented for this target!");
  8256. }
  8257. void
  8258. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8259. SDValue Op = getNonRegisterValue(V);
  8260. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8261. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8262. "Copy from a reg to the same reg!");
  8263. assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
  8264. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8265. // If this is an InlineAsm we have to match the registers required, not the
  8266. // notional registers required by the type.
  8267. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8268. None); // This is not an ABI copy.
  8269. SDValue Chain = DAG.getEntryNode();
  8270. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8271. FuncInfo.PreferredExtendType.end())
  8272. ? ISD::ANY_EXTEND
  8273. : FuncInfo.PreferredExtendType[V];
  8274. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8275. PendingExports.push_back(Chain);
  8276. }
  8277. #include "llvm/CodeGen/SelectionDAGISel.h"
  8278. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8279. /// entry block, return true. This includes arguments used by switches, since
  8280. /// the switch may expand into multiple basic blocks.
  8281. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8282. // With FastISel active, we may be splitting blocks, so force creation
  8283. // of virtual registers for all non-dead arguments.
  8284. if (FastISel)
  8285. return A->use_empty();
  8286. const BasicBlock &Entry = A->getParent()->front();
  8287. for (const User *U : A->users())
  8288. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8289. return false; // Use not in entry block.
  8290. return true;
  8291. }
  8292. using ArgCopyElisionMapTy =
  8293. DenseMap<const Argument *,
  8294. std::pair<const AllocaInst *, const StoreInst *>>;
  8295. /// Scan the entry block of the function in FuncInfo for arguments that look
  8296. /// like copies into a local alloca. Record any copied arguments in
  8297. /// ArgCopyElisionCandidates.
  8298. static void
  8299. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8300. FunctionLoweringInfo *FuncInfo,
  8301. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8302. // Record the state of every static alloca used in the entry block. Argument
  8303. // allocas are all used in the entry block, so we need approximately as many
  8304. // entries as we have arguments.
  8305. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8306. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8307. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8308. StaticAllocas.reserve(NumArgs * 2);
  8309. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8310. if (!V)
  8311. return nullptr;
  8312. V = V->stripPointerCasts();
  8313. const auto *AI = dyn_cast<AllocaInst>(V);
  8314. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8315. return nullptr;
  8316. auto Iter = StaticAllocas.insert({AI, Unknown});
  8317. return &Iter.first->second;
  8318. };
  8319. // Look for stores of arguments to static allocas. Look through bitcasts and
  8320. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8321. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8322. // unanalyzed store might write it.
  8323. // FIXME: Handle structs initialized with multiple stores.
  8324. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8325. // Look for stores, and handle non-store uses conservatively.
  8326. const auto *SI = dyn_cast<StoreInst>(&I);
  8327. if (!SI) {
  8328. // We will look through cast uses, so ignore them completely.
  8329. if (I.isCast())
  8330. continue;
  8331. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8332. if (isa<DbgInfoIntrinsic>(I))
  8333. continue;
  8334. // This is an unknown instruction. Assume it escapes or writes to all
  8335. // static alloca operands.
  8336. for (const Use &U : I.operands()) {
  8337. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8338. *Info = StaticAllocaInfo::Clobbered;
  8339. }
  8340. continue;
  8341. }
  8342. // If the stored value is a static alloca, mark it as escaped.
  8343. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8344. *Info = StaticAllocaInfo::Clobbered;
  8345. // Check if the destination is a static alloca.
  8346. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8347. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8348. if (!Info)
  8349. continue;
  8350. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8351. // Skip allocas that have been initialized or clobbered.
  8352. if (*Info != StaticAllocaInfo::Unknown)
  8353. continue;
  8354. // Check if the stored value is an argument, and that this store fully
  8355. // initializes the alloca. Don't elide copies from the same argument twice.
  8356. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8357. const auto *Arg = dyn_cast<Argument>(Val);
  8358. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8359. Arg->getType()->isEmptyTy() ||
  8360. DL.getTypeStoreSize(Arg->getType()) !=
  8361. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8362. ArgCopyElisionCandidates.count(Arg)) {
  8363. *Info = StaticAllocaInfo::Clobbered;
  8364. continue;
  8365. }
  8366. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8367. << '\n');
  8368. // Mark this alloca and store for argument copy elision.
  8369. *Info = StaticAllocaInfo::Elidable;
  8370. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8371. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8372. // builds, which is useful, because -O0 builds have large entry blocks and
  8373. // many allocas.
  8374. if (ArgCopyElisionCandidates.size() == NumArgs)
  8375. break;
  8376. }
  8377. }
  8378. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8379. /// ArgVal is a load from a suitable fixed stack object.
  8380. static void tryToElideArgumentCopy(
  8381. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8382. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8383. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8384. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8385. SDValue ArgVal, bool &ArgHasUses) {
  8386. // Check if this is a load from a fixed stack object.
  8387. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8388. if (!LNode)
  8389. return;
  8390. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8391. if (!FINode)
  8392. return;
  8393. // Check that the fixed stack object is the right size and alignment.
  8394. // Look at the alignment that the user wrote on the alloca instead of looking
  8395. // at the stack object.
  8396. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8397. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8398. const AllocaInst *AI = ArgCopyIter->second.first;
  8399. int FixedIndex = FINode->getIndex();
  8400. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8401. int OldIndex = AllocaIndex;
  8402. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8403. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8404. LLVM_DEBUG(
  8405. dbgs() << " argument copy elision failed due to bad fixed stack "
  8406. "object size\n");
  8407. return;
  8408. }
  8409. unsigned RequiredAlignment = AI->getAlignment();
  8410. if (!RequiredAlignment) {
  8411. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8412. AI->getAllocatedType());
  8413. }
  8414. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8415. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8416. "greater than stack argument alignment ("
  8417. << RequiredAlignment << " vs "
  8418. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8419. return;
  8420. }
  8421. // Perform the elision. Delete the old stack object and replace its only use
  8422. // in the variable info map. Mark the stack object as mutable.
  8423. LLVM_DEBUG({
  8424. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8425. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8426. << '\n';
  8427. });
  8428. MFI.RemoveStackObject(OldIndex);
  8429. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8430. AllocaIndex = FixedIndex;
  8431. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8432. Chains.push_back(ArgVal.getValue(1));
  8433. // Avoid emitting code for the store implementing the copy.
  8434. const StoreInst *SI = ArgCopyIter->second.second;
  8435. ElidedArgCopyInstrs.insert(SI);
  8436. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8437. // if it is't used by anything other than the store.
  8438. for (const Value *U : Arg.users()) {
  8439. if (U != SI) {
  8440. ArgHasUses = true;
  8441. break;
  8442. }
  8443. }
  8444. }
  8445. void SelectionDAGISel::LowerArguments(const Function &F) {
  8446. SelectionDAG &DAG = SDB->DAG;
  8447. SDLoc dl = SDB->getCurSDLoc();
  8448. const DataLayout &DL = DAG.getDataLayout();
  8449. SmallVector<ISD::InputArg, 16> Ins;
  8450. if (!FuncInfo->CanLowerReturn) {
  8451. // Put in an sret pointer parameter before all the other parameters.
  8452. SmallVector<EVT, 1> ValueVTs;
  8453. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8454. F.getReturnType()->getPointerTo(
  8455. DAG.getDataLayout().getAllocaAddrSpace()),
  8456. ValueVTs);
  8457. // NOTE: Assuming that a pointer will never break down to more than one VT
  8458. // or one register.
  8459. ISD::ArgFlagsTy Flags;
  8460. Flags.setSRet();
  8461. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8462. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8463. ISD::InputArg::NoArgIndex, 0);
  8464. Ins.push_back(RetArg);
  8465. }
  8466. // Look for stores of arguments to static allocas. Mark such arguments with a
  8467. // flag to ask the target to give us the memory location of that argument if
  8468. // available.
  8469. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8470. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8471. // Set up the incoming argument description vector.
  8472. for (const Argument &Arg : F.args()) {
  8473. unsigned ArgNo = Arg.getArgNo();
  8474. SmallVector<EVT, 4> ValueVTs;
  8475. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8476. bool isArgValueUsed = !Arg.use_empty();
  8477. unsigned PartBase = 0;
  8478. Type *FinalType = Arg.getType();
  8479. if (Arg.hasAttribute(Attribute::ByVal))
  8480. FinalType = Arg.getParamByValType();
  8481. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8482. FinalType, F.getCallingConv(), F.isVarArg());
  8483. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8484. Value != NumValues; ++Value) {
  8485. EVT VT = ValueVTs[Value];
  8486. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8487. ISD::ArgFlagsTy Flags;
  8488. // Certain targets (such as MIPS), may have a different ABI alignment
  8489. // for a type depending on the context. Give the target a chance to
  8490. // specify the alignment it wants.
  8491. unsigned OriginalAlignment =
  8492. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8493. if (Arg.getType()->isPointerTy()) {
  8494. Flags.setPointer();
  8495. Flags.setPointerAddrSpace(
  8496. cast<PointerType>(Arg.getType())->getAddressSpace());
  8497. }
  8498. if (Arg.hasAttribute(Attribute::ZExt))
  8499. Flags.setZExt();
  8500. if (Arg.hasAttribute(Attribute::SExt))
  8501. Flags.setSExt();
  8502. if (Arg.hasAttribute(Attribute::InReg)) {
  8503. // If we are using vectorcall calling convention, a structure that is
  8504. // passed InReg - is surely an HVA
  8505. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8506. isa<StructType>(Arg.getType())) {
  8507. // The first value of a structure is marked
  8508. if (0 == Value)
  8509. Flags.setHvaStart();
  8510. Flags.setHva();
  8511. }
  8512. // Set InReg Flag
  8513. Flags.setInReg();
  8514. }
  8515. if (Arg.hasAttribute(Attribute::StructRet))
  8516. Flags.setSRet();
  8517. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8518. Flags.setSwiftSelf();
  8519. if (Arg.hasAttribute(Attribute::SwiftError))
  8520. Flags.setSwiftError();
  8521. if (Arg.hasAttribute(Attribute::ByVal))
  8522. Flags.setByVal();
  8523. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8524. Flags.setInAlloca();
  8525. // Set the byval flag for CCAssignFn callbacks that don't know about
  8526. // inalloca. This way we can know how many bytes we should've allocated
  8527. // and how many bytes a callee cleanup function will pop. If we port
  8528. // inalloca to more targets, we'll have to add custom inalloca handling
  8529. // in the various CC lowering callbacks.
  8530. Flags.setByVal();
  8531. }
  8532. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8533. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8534. if (ArgNo == 0)
  8535. Flags.setByVal();
  8536. }
  8537. if (Flags.isByVal() || Flags.isInAlloca()) {
  8538. Type *ElementTy = Arg.getParamByValType();
  8539. // For ByVal, size and alignment should be passed from FE. BE will
  8540. // guess if this info is not there but there are cases it cannot get
  8541. // right.
  8542. unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
  8543. Flags.setByValSize(FrameSize);
  8544. unsigned FrameAlign;
  8545. if (Arg.getParamAlignment())
  8546. FrameAlign = Arg.getParamAlignment();
  8547. else
  8548. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8549. Flags.setByValAlign(FrameAlign);
  8550. }
  8551. if (Arg.hasAttribute(Attribute::Nest))
  8552. Flags.setNest();
  8553. if (NeedsRegBlock)
  8554. Flags.setInConsecutiveRegs();
  8555. Flags.setOrigAlign(OriginalAlignment);
  8556. if (ArgCopyElisionCandidates.count(&Arg))
  8557. Flags.setCopyElisionCandidate();
  8558. if (Arg.hasAttribute(Attribute::Returned))
  8559. Flags.setReturned();
  8560. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8561. *CurDAG->getContext(), F.getCallingConv(), VT);
  8562. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8563. *CurDAG->getContext(), F.getCallingConv(), VT);
  8564. for (unsigned i = 0; i != NumRegs; ++i) {
  8565. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8566. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8567. if (NumRegs > 1 && i == 0)
  8568. MyFlags.Flags.setSplit();
  8569. // if it isn't first piece, alignment must be 1
  8570. else if (i > 0) {
  8571. MyFlags.Flags.setOrigAlign(1);
  8572. if (i == NumRegs - 1)
  8573. MyFlags.Flags.setSplitEnd();
  8574. }
  8575. Ins.push_back(MyFlags);
  8576. }
  8577. if (NeedsRegBlock && Value == NumValues - 1)
  8578. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8579. PartBase += VT.getStoreSize();
  8580. }
  8581. }
  8582. // Call the target to set up the argument values.
  8583. SmallVector<SDValue, 8> InVals;
  8584. SDValue NewRoot = TLI->LowerFormalArguments(
  8585. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8586. // Verify that the target's LowerFormalArguments behaved as expected.
  8587. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8588. "LowerFormalArguments didn't return a valid chain!");
  8589. assert(InVals.size() == Ins.size() &&
  8590. "LowerFormalArguments didn't emit the correct number of values!");
  8591. LLVM_DEBUG({
  8592. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8593. assert(InVals[i].getNode() &&
  8594. "LowerFormalArguments emitted a null value!");
  8595. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8596. "LowerFormalArguments emitted a value with the wrong type!");
  8597. }
  8598. });
  8599. // Update the DAG with the new chain value resulting from argument lowering.
  8600. DAG.setRoot(NewRoot);
  8601. // Set up the argument values.
  8602. unsigned i = 0;
  8603. if (!FuncInfo->CanLowerReturn) {
  8604. // Create a virtual register for the sret pointer, and put in a copy
  8605. // from the sret argument into it.
  8606. SmallVector<EVT, 1> ValueVTs;
  8607. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8608. F.getReturnType()->getPointerTo(
  8609. DAG.getDataLayout().getAllocaAddrSpace()),
  8610. ValueVTs);
  8611. MVT VT = ValueVTs[0].getSimpleVT();
  8612. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8613. Optional<ISD::NodeType> AssertOp = None;
  8614. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8615. nullptr, F.getCallingConv(), AssertOp);
  8616. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8617. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8618. Register SRetReg =
  8619. RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8620. FuncInfo->DemoteRegister = SRetReg;
  8621. NewRoot =
  8622. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8623. DAG.setRoot(NewRoot);
  8624. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8625. ++i;
  8626. }
  8627. SmallVector<SDValue, 4> Chains;
  8628. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8629. for (const Argument &Arg : F.args()) {
  8630. SmallVector<SDValue, 4> ArgValues;
  8631. SmallVector<EVT, 4> ValueVTs;
  8632. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8633. unsigned NumValues = ValueVTs.size();
  8634. if (NumValues == 0)
  8635. continue;
  8636. bool ArgHasUses = !Arg.use_empty();
  8637. // Elide the copying store if the target loaded this argument from a
  8638. // suitable fixed stack object.
  8639. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8640. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8641. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8642. InVals[i], ArgHasUses);
  8643. }
  8644. // If this argument is unused then remember its value. It is used to generate
  8645. // debugging information.
  8646. bool isSwiftErrorArg =
  8647. TLI->supportSwiftError() &&
  8648. Arg.hasAttribute(Attribute::SwiftError);
  8649. if (!ArgHasUses && !isSwiftErrorArg) {
  8650. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8651. // Also remember any frame index for use in FastISel.
  8652. if (FrameIndexSDNode *FI =
  8653. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8654. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8655. }
  8656. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8657. EVT VT = ValueVTs[Val];
  8658. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8659. F.getCallingConv(), VT);
  8660. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8661. *CurDAG->getContext(), F.getCallingConv(), VT);
  8662. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8663. // we do generate a copy for it that can be used on return from the
  8664. // function.
  8665. if (ArgHasUses || isSwiftErrorArg) {
  8666. Optional<ISD::NodeType> AssertOp;
  8667. if (Arg.hasAttribute(Attribute::SExt))
  8668. AssertOp = ISD::AssertSext;
  8669. else if (Arg.hasAttribute(Attribute::ZExt))
  8670. AssertOp = ISD::AssertZext;
  8671. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8672. PartVT, VT, nullptr,
  8673. F.getCallingConv(), AssertOp));
  8674. }
  8675. i += NumParts;
  8676. }
  8677. // We don't need to do anything else for unused arguments.
  8678. if (ArgValues.empty())
  8679. continue;
  8680. // Note down frame index.
  8681. if (FrameIndexSDNode *FI =
  8682. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8683. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8684. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8685. SDB->getCurSDLoc());
  8686. SDB->setValue(&Arg, Res);
  8687. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8688. // We want to associate the argument with the frame index, among
  8689. // involved operands, that correspond to the lowest address. The
  8690. // getCopyFromParts function, called earlier, is swapping the order of
  8691. // the operands to BUILD_PAIR depending on endianness. The result of
  8692. // that swapping is that the least significant bits of the argument will
  8693. // be in the first operand of the BUILD_PAIR node, and the most
  8694. // significant bits will be in the second operand.
  8695. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8696. if (LoadSDNode *LNode =
  8697. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8698. if (FrameIndexSDNode *FI =
  8699. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8700. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8701. }
  8702. // Update the SwiftErrorVRegDefMap.
  8703. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8704. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8705. if (Register::isVirtualRegister(Reg))
  8706. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  8707. Reg);
  8708. }
  8709. // If this argument is live outside of the entry block, insert a copy from
  8710. // wherever we got it to the vreg that other BB's will reference it as.
  8711. if (Res.getOpcode() == ISD::CopyFromReg) {
  8712. // If we can, though, try to skip creating an unnecessary vreg.
  8713. // FIXME: This isn't very clean... it would be nice to make this more
  8714. // general.
  8715. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8716. if (Register::isVirtualRegister(Reg)) {
  8717. FuncInfo->ValueMap[&Arg] = Reg;
  8718. continue;
  8719. }
  8720. }
  8721. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8722. FuncInfo->InitializeRegForValue(&Arg);
  8723. SDB->CopyToExportRegsIfNeeded(&Arg);
  8724. }
  8725. }
  8726. if (!Chains.empty()) {
  8727. Chains.push_back(NewRoot);
  8728. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8729. }
  8730. DAG.setRoot(NewRoot);
  8731. assert(i == InVals.size() && "Argument register count mismatch!");
  8732. // If any argument copy elisions occurred and we have debug info, update the
  8733. // stale frame indices used in the dbg.declare variable info table.
  8734. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8735. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8736. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8737. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8738. if (I != ArgCopyElisionFrameIndexMap.end())
  8739. VI.Slot = I->second;
  8740. }
  8741. }
  8742. // Finally, if the target has anything special to do, allow it to do so.
  8743. EmitFunctionEntryCode();
  8744. }
  8745. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8746. /// ensure constants are generated when needed. Remember the virtual registers
  8747. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8748. /// directly add them, because expansion might result in multiple MBB's for one
  8749. /// BB. As such, the start of the BB might correspond to a different MBB than
  8750. /// the end.
  8751. void
  8752. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8753. const Instruction *TI = LLVMBB->getTerminator();
  8754. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8755. // Check PHI nodes in successors that expect a value to be available from this
  8756. // block.
  8757. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8758. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8759. if (!isa<PHINode>(SuccBB->begin())) continue;
  8760. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8761. // If this terminator has multiple identical successors (common for
  8762. // switches), only handle each succ once.
  8763. if (!SuccsHandled.insert(SuccMBB).second)
  8764. continue;
  8765. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8766. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8767. // nodes and Machine PHI nodes, but the incoming operands have not been
  8768. // emitted yet.
  8769. for (const PHINode &PN : SuccBB->phis()) {
  8770. // Ignore dead phi's.
  8771. if (PN.use_empty())
  8772. continue;
  8773. // Skip empty types
  8774. if (PN.getType()->isEmptyTy())
  8775. continue;
  8776. unsigned Reg;
  8777. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8778. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8779. unsigned &RegOut = ConstantsOut[C];
  8780. if (RegOut == 0) {
  8781. RegOut = FuncInfo.CreateRegs(C);
  8782. CopyValueToVirtualRegister(C, RegOut);
  8783. }
  8784. Reg = RegOut;
  8785. } else {
  8786. DenseMap<const Value *, unsigned>::iterator I =
  8787. FuncInfo.ValueMap.find(PHIOp);
  8788. if (I != FuncInfo.ValueMap.end())
  8789. Reg = I->second;
  8790. else {
  8791. assert(isa<AllocaInst>(PHIOp) &&
  8792. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8793. "Didn't codegen value into a register!??");
  8794. Reg = FuncInfo.CreateRegs(PHIOp);
  8795. CopyValueToVirtualRegister(PHIOp, Reg);
  8796. }
  8797. }
  8798. // Remember that this register needs to added to the machine PHI node as
  8799. // the input for this MBB.
  8800. SmallVector<EVT, 4> ValueVTs;
  8801. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8802. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8803. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8804. EVT VT = ValueVTs[vti];
  8805. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8806. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8807. FuncInfo.PHINodesToUpdate.push_back(
  8808. std::make_pair(&*MBBI++, Reg + i));
  8809. Reg += NumRegisters;
  8810. }
  8811. }
  8812. }
  8813. ConstantsOut.clear();
  8814. }
  8815. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8816. /// is 0.
  8817. MachineBasicBlock *
  8818. SelectionDAGBuilder::StackProtectorDescriptor::
  8819. AddSuccessorMBB(const BasicBlock *BB,
  8820. MachineBasicBlock *ParentMBB,
  8821. bool IsLikely,
  8822. MachineBasicBlock *SuccMBB) {
  8823. // If SuccBB has not been created yet, create it.
  8824. if (!SuccMBB) {
  8825. MachineFunction *MF = ParentMBB->getParent();
  8826. MachineFunction::iterator BBI(ParentMBB);
  8827. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8828. MF->insert(++BBI, SuccMBB);
  8829. }
  8830. // Add it as a successor of ParentMBB.
  8831. ParentMBB->addSuccessor(
  8832. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8833. return SuccMBB;
  8834. }
  8835. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8836. MachineFunction::iterator I(MBB);
  8837. if (++I == FuncInfo.MF->end())
  8838. return nullptr;
  8839. return &*I;
  8840. }
  8841. /// During lowering new call nodes can be created (such as memset, etc.).
  8842. /// Those will become new roots of the current DAG, but complications arise
  8843. /// when they are tail calls. In such cases, the call lowering will update
  8844. /// the root, but the builder still needs to know that a tail call has been
  8845. /// lowered in order to avoid generating an additional return.
  8846. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8847. // If the node is null, we do have a tail call.
  8848. if (MaybeTC.getNode() != nullptr)
  8849. DAG.setRoot(MaybeTC);
  8850. else
  8851. HasTailCall = true;
  8852. }
  8853. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8854. MachineBasicBlock *SwitchMBB,
  8855. MachineBasicBlock *DefaultMBB) {
  8856. MachineFunction *CurMF = FuncInfo.MF;
  8857. MachineBasicBlock *NextMBB = nullptr;
  8858. MachineFunction::iterator BBI(W.MBB);
  8859. if (++BBI != FuncInfo.MF->end())
  8860. NextMBB = &*BBI;
  8861. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8862. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8863. if (Size == 2 && W.MBB == SwitchMBB) {
  8864. // If any two of the cases has the same destination, and if one value
  8865. // is the same as the other, but has one bit unset that the other has set,
  8866. // use bit manipulation to do two compares at once. For example:
  8867. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8868. // TODO: This could be extended to merge any 2 cases in switches with 3
  8869. // cases.
  8870. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8871. CaseCluster &Small = *W.FirstCluster;
  8872. CaseCluster &Big = *W.LastCluster;
  8873. if (Small.Low == Small.High && Big.Low == Big.High &&
  8874. Small.MBB == Big.MBB) {
  8875. const APInt &SmallValue = Small.Low->getValue();
  8876. const APInt &BigValue = Big.Low->getValue();
  8877. // Check that there is only one bit different.
  8878. APInt CommonBit = BigValue ^ SmallValue;
  8879. if (CommonBit.isPowerOf2()) {
  8880. SDValue CondLHS = getValue(Cond);
  8881. EVT VT = CondLHS.getValueType();
  8882. SDLoc DL = getCurSDLoc();
  8883. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8884. DAG.getConstant(CommonBit, DL, VT));
  8885. SDValue Cond = DAG.getSetCC(
  8886. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8887. ISD::SETEQ);
  8888. // Update successor info.
  8889. // Both Small and Big will jump to Small.BB, so we sum up the
  8890. // probabilities.
  8891. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8892. if (BPI)
  8893. addSuccessorWithProb(
  8894. SwitchMBB, DefaultMBB,
  8895. // The default destination is the first successor in IR.
  8896. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8897. else
  8898. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8899. // Insert the true branch.
  8900. SDValue BrCond =
  8901. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8902. DAG.getBasicBlock(Small.MBB));
  8903. // Insert the false branch.
  8904. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8905. DAG.getBasicBlock(DefaultMBB));
  8906. DAG.setRoot(BrCond);
  8907. return;
  8908. }
  8909. }
  8910. }
  8911. if (TM.getOptLevel() != CodeGenOpt::None) {
  8912. // Here, we order cases by probability so the most likely case will be
  8913. // checked first. However, two clusters can have the same probability in
  8914. // which case their relative ordering is non-deterministic. So we use Low
  8915. // as a tie-breaker as clusters are guaranteed to never overlap.
  8916. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  8917. [](const CaseCluster &a, const CaseCluster &b) {
  8918. return a.Prob != b.Prob ?
  8919. a.Prob > b.Prob :
  8920. a.Low->getValue().slt(b.Low->getValue());
  8921. });
  8922. // Rearrange the case blocks so that the last one falls through if possible
  8923. // without changing the order of probabilities.
  8924. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8925. --I;
  8926. if (I->Prob > W.LastCluster->Prob)
  8927. break;
  8928. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8929. std::swap(*I, *W.LastCluster);
  8930. break;
  8931. }
  8932. }
  8933. }
  8934. // Compute total probability.
  8935. BranchProbability DefaultProb = W.DefaultProb;
  8936. BranchProbability UnhandledProbs = DefaultProb;
  8937. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8938. UnhandledProbs += I->Prob;
  8939. MachineBasicBlock *CurMBB = W.MBB;
  8940. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8941. bool FallthroughUnreachable = false;
  8942. MachineBasicBlock *Fallthrough;
  8943. if (I == W.LastCluster) {
  8944. // For the last cluster, fall through to the default destination.
  8945. Fallthrough = DefaultMBB;
  8946. FallthroughUnreachable = isa<UnreachableInst>(
  8947. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  8948. } else {
  8949. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8950. CurMF->insert(BBI, Fallthrough);
  8951. // Put Cond in a virtual register to make it available from the new blocks.
  8952. ExportFromCurrentBlock(Cond);
  8953. }
  8954. UnhandledProbs -= I->Prob;
  8955. switch (I->Kind) {
  8956. case CC_JumpTable: {
  8957. // FIXME: Optimize away range check based on pivot comparisons.
  8958. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  8959. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  8960. // The jump block hasn't been inserted yet; insert it here.
  8961. MachineBasicBlock *JumpMBB = JT->MBB;
  8962. CurMF->insert(BBI, JumpMBB);
  8963. auto JumpProb = I->Prob;
  8964. auto FallthroughProb = UnhandledProbs;
  8965. // If the default statement is a target of the jump table, we evenly
  8966. // distribute the default probability to successors of CurMBB. Also
  8967. // update the probability on the edge from JumpMBB to Fallthrough.
  8968. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8969. SE = JumpMBB->succ_end();
  8970. SI != SE; ++SI) {
  8971. if (*SI == DefaultMBB) {
  8972. JumpProb += DefaultProb / 2;
  8973. FallthroughProb -= DefaultProb / 2;
  8974. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8975. JumpMBB->normalizeSuccProbs();
  8976. break;
  8977. }
  8978. }
  8979. if (FallthroughUnreachable) {
  8980. // Skip the range check if the fallthrough block is unreachable.
  8981. JTH->OmitRangeCheck = true;
  8982. }
  8983. if (!JTH->OmitRangeCheck)
  8984. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8985. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8986. CurMBB->normalizeSuccProbs();
  8987. // The jump table header will be inserted in our current block, do the
  8988. // range check, and fall through to our fallthrough block.
  8989. JTH->HeaderBB = CurMBB;
  8990. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8991. // If we're in the right place, emit the jump table header right now.
  8992. if (CurMBB == SwitchMBB) {
  8993. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  8994. JTH->Emitted = true;
  8995. }
  8996. break;
  8997. }
  8998. case CC_BitTests: {
  8999. // FIXME: If Fallthrough is unreachable, skip the range check.
  9000. // FIXME: Optimize away range check based on pivot comparisons.
  9001. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  9002. // The bit test blocks haven't been inserted yet; insert them here.
  9003. for (BitTestCase &BTC : BTB->Cases)
  9004. CurMF->insert(BBI, BTC.ThisBB);
  9005. // Fill in fields of the BitTestBlock.
  9006. BTB->Parent = CurMBB;
  9007. BTB->Default = Fallthrough;
  9008. BTB->DefaultProb = UnhandledProbs;
  9009. // If the cases in bit test don't form a contiguous range, we evenly
  9010. // distribute the probability on the edge to Fallthrough to two
  9011. // successors of CurMBB.
  9012. if (!BTB->ContiguousRange) {
  9013. BTB->Prob += DefaultProb / 2;
  9014. BTB->DefaultProb -= DefaultProb / 2;
  9015. }
  9016. // If we're in the right place, emit the bit test header right now.
  9017. if (CurMBB == SwitchMBB) {
  9018. visitBitTestHeader(*BTB, SwitchMBB);
  9019. BTB->Emitted = true;
  9020. }
  9021. break;
  9022. }
  9023. case CC_Range: {
  9024. const Value *RHS, *LHS, *MHS;
  9025. ISD::CondCode CC;
  9026. if (I->Low == I->High) {
  9027. // Check Cond == I->Low.
  9028. CC = ISD::SETEQ;
  9029. LHS = Cond;
  9030. RHS=I->Low;
  9031. MHS = nullptr;
  9032. } else {
  9033. // Check I->Low <= Cond <= I->High.
  9034. CC = ISD::SETLE;
  9035. LHS = I->Low;
  9036. MHS = Cond;
  9037. RHS = I->High;
  9038. }
  9039. // If Fallthrough is unreachable, fold away the comparison.
  9040. if (FallthroughUnreachable)
  9041. CC = ISD::SETTRUE;
  9042. // The false probability is the sum of all unhandled cases.
  9043. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9044. getCurSDLoc(), I->Prob, UnhandledProbs);
  9045. if (CurMBB == SwitchMBB)
  9046. visitSwitchCase(CB, SwitchMBB);
  9047. else
  9048. SL->SwitchCases.push_back(CB);
  9049. break;
  9050. }
  9051. }
  9052. CurMBB = Fallthrough;
  9053. }
  9054. }
  9055. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9056. CaseClusterIt First,
  9057. CaseClusterIt Last) {
  9058. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9059. if (X.Prob != CC.Prob)
  9060. return X.Prob > CC.Prob;
  9061. // Ties are broken by comparing the case value.
  9062. return X.Low->getValue().slt(CC.Low->getValue());
  9063. });
  9064. }
  9065. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9066. const SwitchWorkListItem &W,
  9067. Value *Cond,
  9068. MachineBasicBlock *SwitchMBB) {
  9069. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9070. "Clusters not sorted?");
  9071. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9072. // Balance the tree based on branch probabilities to create a near-optimal (in
  9073. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9074. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9075. CaseClusterIt LastLeft = W.FirstCluster;
  9076. CaseClusterIt FirstRight = W.LastCluster;
  9077. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9078. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9079. // Move LastLeft and FirstRight towards each other from opposite directions to
  9080. // find a partitioning of the clusters which balances the probability on both
  9081. // sides. If LeftProb and RightProb are equal, alternate which side is
  9082. // taken to ensure 0-probability nodes are distributed evenly.
  9083. unsigned I = 0;
  9084. while (LastLeft + 1 < FirstRight) {
  9085. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9086. LeftProb += (++LastLeft)->Prob;
  9087. else
  9088. RightProb += (--FirstRight)->Prob;
  9089. I++;
  9090. }
  9091. while (true) {
  9092. // Our binary search tree differs from a typical BST in that ours can have up
  9093. // to three values in each leaf. The pivot selection above doesn't take that
  9094. // into account, which means the tree might require more nodes and be less
  9095. // efficient. We compensate for this here.
  9096. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9097. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9098. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9099. // If one side has less than 3 clusters, and the other has more than 3,
  9100. // consider taking a cluster from the other side.
  9101. if (NumLeft < NumRight) {
  9102. // Consider moving the first cluster on the right to the left side.
  9103. CaseCluster &CC = *FirstRight;
  9104. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9105. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9106. if (LeftSideRank <= RightSideRank) {
  9107. // Moving the cluster to the left does not demote it.
  9108. ++LastLeft;
  9109. ++FirstRight;
  9110. continue;
  9111. }
  9112. } else {
  9113. assert(NumRight < NumLeft);
  9114. // Consider moving the last element on the left to the right side.
  9115. CaseCluster &CC = *LastLeft;
  9116. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9117. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9118. if (RightSideRank <= LeftSideRank) {
  9119. // Moving the cluster to the right does not demot it.
  9120. --LastLeft;
  9121. --FirstRight;
  9122. continue;
  9123. }
  9124. }
  9125. }
  9126. break;
  9127. }
  9128. assert(LastLeft + 1 == FirstRight);
  9129. assert(LastLeft >= W.FirstCluster);
  9130. assert(FirstRight <= W.LastCluster);
  9131. // Use the first element on the right as pivot since we will make less-than
  9132. // comparisons against it.
  9133. CaseClusterIt PivotCluster = FirstRight;
  9134. assert(PivotCluster > W.FirstCluster);
  9135. assert(PivotCluster <= W.LastCluster);
  9136. CaseClusterIt FirstLeft = W.FirstCluster;
  9137. CaseClusterIt LastRight = W.LastCluster;
  9138. const ConstantInt *Pivot = PivotCluster->Low;
  9139. // New blocks will be inserted immediately after the current one.
  9140. MachineFunction::iterator BBI(W.MBB);
  9141. ++BBI;
  9142. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9143. // we can branch to its destination directly if it's squeezed exactly in
  9144. // between the known lower bound and Pivot - 1.
  9145. MachineBasicBlock *LeftMBB;
  9146. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9147. FirstLeft->Low == W.GE &&
  9148. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9149. LeftMBB = FirstLeft->MBB;
  9150. } else {
  9151. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9152. FuncInfo.MF->insert(BBI, LeftMBB);
  9153. WorkList.push_back(
  9154. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9155. // Put Cond in a virtual register to make it available from the new blocks.
  9156. ExportFromCurrentBlock(Cond);
  9157. }
  9158. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9159. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9160. // directly if RHS.High equals the current upper bound.
  9161. MachineBasicBlock *RightMBB;
  9162. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9163. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9164. RightMBB = FirstRight->MBB;
  9165. } else {
  9166. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9167. FuncInfo.MF->insert(BBI, RightMBB);
  9168. WorkList.push_back(
  9169. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9170. // Put Cond in a virtual register to make it available from the new blocks.
  9171. ExportFromCurrentBlock(Cond);
  9172. }
  9173. // Create the CaseBlock record that will be used to lower the branch.
  9174. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9175. getCurSDLoc(), LeftProb, RightProb);
  9176. if (W.MBB == SwitchMBB)
  9177. visitSwitchCase(CB, SwitchMBB);
  9178. else
  9179. SL->SwitchCases.push_back(CB);
  9180. }
  9181. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9182. // from the swith statement.
  9183. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9184. BranchProbability PeeledCaseProb) {
  9185. if (PeeledCaseProb == BranchProbability::getOne())
  9186. return BranchProbability::getZero();
  9187. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9188. uint32_t Numerator = CaseProb.getNumerator();
  9189. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9190. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9191. }
  9192. // Try to peel the top probability case if it exceeds the threshold.
  9193. // Return current MachineBasicBlock for the switch statement if the peeling
  9194. // does not occur.
  9195. // If the peeling is performed, return the newly created MachineBasicBlock
  9196. // for the peeled switch statement. Also update Clusters to remove the peeled
  9197. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9198. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9199. const SwitchInst &SI, CaseClusterVector &Clusters,
  9200. BranchProbability &PeeledCaseProb) {
  9201. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9202. // Don't perform if there is only one cluster or optimizing for size.
  9203. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9204. TM.getOptLevel() == CodeGenOpt::None ||
  9205. SwitchMBB->getParent()->getFunction().hasMinSize())
  9206. return SwitchMBB;
  9207. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9208. unsigned PeeledCaseIndex = 0;
  9209. bool SwitchPeeled = false;
  9210. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9211. CaseCluster &CC = Clusters[Index];
  9212. if (CC.Prob < TopCaseProb)
  9213. continue;
  9214. TopCaseProb = CC.Prob;
  9215. PeeledCaseIndex = Index;
  9216. SwitchPeeled = true;
  9217. }
  9218. if (!SwitchPeeled)
  9219. return SwitchMBB;
  9220. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9221. << TopCaseProb << "\n");
  9222. // Record the MBB for the peeled switch statement.
  9223. MachineFunction::iterator BBI(SwitchMBB);
  9224. ++BBI;
  9225. MachineBasicBlock *PeeledSwitchMBB =
  9226. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9227. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9228. ExportFromCurrentBlock(SI.getCondition());
  9229. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9230. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9231. nullptr, nullptr, TopCaseProb.getCompl()};
  9232. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9233. Clusters.erase(PeeledCaseIt);
  9234. for (CaseCluster &CC : Clusters) {
  9235. LLVM_DEBUG(
  9236. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9237. << CC.Prob << "\n");
  9238. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9239. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9240. }
  9241. PeeledCaseProb = TopCaseProb;
  9242. return PeeledSwitchMBB;
  9243. }
  9244. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9245. // Extract cases from the switch.
  9246. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9247. CaseClusterVector Clusters;
  9248. Clusters.reserve(SI.getNumCases());
  9249. for (auto I : SI.cases()) {
  9250. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9251. const ConstantInt *CaseVal = I.getCaseValue();
  9252. BranchProbability Prob =
  9253. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9254. : BranchProbability(1, SI.getNumCases() + 1);
  9255. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9256. }
  9257. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9258. // Cluster adjacent cases with the same destination. We do this at all
  9259. // optimization levels because it's cheap to do and will make codegen faster
  9260. // if there are many clusters.
  9261. sortAndRangeify(Clusters);
  9262. // The branch probablity of the peeled case.
  9263. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9264. MachineBasicBlock *PeeledSwitchMBB =
  9265. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9266. // If there is only the default destination, jump there directly.
  9267. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9268. if (Clusters.empty()) {
  9269. assert(PeeledSwitchMBB == SwitchMBB);
  9270. SwitchMBB->addSuccessor(DefaultMBB);
  9271. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9272. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9273. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9274. }
  9275. return;
  9276. }
  9277. SL->findJumpTables(Clusters, &SI, DefaultMBB);
  9278. SL->findBitTestClusters(Clusters, &SI);
  9279. LLVM_DEBUG({
  9280. dbgs() << "Case clusters: ";
  9281. for (const CaseCluster &C : Clusters) {
  9282. if (C.Kind == CC_JumpTable)
  9283. dbgs() << "JT:";
  9284. if (C.Kind == CC_BitTests)
  9285. dbgs() << "BT:";
  9286. C.Low->getValue().print(dbgs(), true);
  9287. if (C.Low != C.High) {
  9288. dbgs() << '-';
  9289. C.High->getValue().print(dbgs(), true);
  9290. }
  9291. dbgs() << ' ';
  9292. }
  9293. dbgs() << '\n';
  9294. });
  9295. assert(!Clusters.empty());
  9296. SwitchWorkList WorkList;
  9297. CaseClusterIt First = Clusters.begin();
  9298. CaseClusterIt Last = Clusters.end() - 1;
  9299. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9300. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9301. // DefaultMBB is not replaced.
  9302. if (PeeledCaseProb != BranchProbability::getZero() &&
  9303. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9304. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9305. WorkList.push_back(
  9306. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9307. while (!WorkList.empty()) {
  9308. SwitchWorkListItem W = WorkList.back();
  9309. WorkList.pop_back();
  9310. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9311. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9312. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9313. // For optimized builds, lower large range as a balanced binary tree.
  9314. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9315. continue;
  9316. }
  9317. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9318. }
  9319. }