SelectionDAGBuilder.cpp 418 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751
  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/TargetFrameLowering.h"
  57. #include "llvm/CodeGen/TargetInstrInfo.h"
  58. #include "llvm/CodeGen/TargetLowering.h"
  59. #include "llvm/CodeGen/TargetOpcodes.h"
  60. #include "llvm/CodeGen/TargetRegisterInfo.h"
  61. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  62. #include "llvm/CodeGen/ValueTypes.h"
  63. #include "llvm/CodeGen/WinEHFuncInfo.h"
  64. #include "llvm/IR/Argument.h"
  65. #include "llvm/IR/Attributes.h"
  66. #include "llvm/IR/BasicBlock.h"
  67. #include "llvm/IR/CFG.h"
  68. #include "llvm/IR/CallSite.h"
  69. #include "llvm/IR/CallingConv.h"
  70. #include "llvm/IR/Constant.h"
  71. #include "llvm/IR/ConstantRange.h"
  72. #include "llvm/IR/Constants.h"
  73. #include "llvm/IR/DataLayout.h"
  74. #include "llvm/IR/DebugInfoMetadata.h"
  75. #include "llvm/IR/DebugLoc.h"
  76. #include "llvm/IR/DerivedTypes.h"
  77. #include "llvm/IR/Function.h"
  78. #include "llvm/IR/GetElementPtrTypeIterator.h"
  79. #include "llvm/IR/InlineAsm.h"
  80. #include "llvm/IR/InstrTypes.h"
  81. #include "llvm/IR/Instruction.h"
  82. #include "llvm/IR/Instructions.h"
  83. #include "llvm/IR/IntrinsicInst.h"
  84. #include "llvm/IR/Intrinsics.h"
  85. #include "llvm/IR/LLVMContext.h"
  86. #include "llvm/IR/Metadata.h"
  87. #include "llvm/IR/Module.h"
  88. #include "llvm/IR/Operator.h"
  89. #include "llvm/IR/PatternMatch.h"
  90. #include "llvm/IR/Statepoint.h"
  91. #include "llvm/IR/Type.h"
  92. #include "llvm/IR/User.h"
  93. #include "llvm/IR/Value.h"
  94. #include "llvm/MC/MCContext.h"
  95. #include "llvm/MC/MCSymbol.h"
  96. #include "llvm/Support/AtomicOrdering.h"
  97. #include "llvm/Support/BranchProbability.h"
  98. #include "llvm/Support/Casting.h"
  99. #include "llvm/Support/CodeGen.h"
  100. #include "llvm/Support/CommandLine.h"
  101. #include "llvm/Support/Compiler.h"
  102. #include "llvm/Support/Debug.h"
  103. #include "llvm/Support/ErrorHandling.h"
  104. #include "llvm/Support/MachineValueType.h"
  105. #include "llvm/Support/MathExtras.h"
  106. #include "llvm/Support/raw_ostream.h"
  107. #include "llvm/Target/TargetIntrinsicInfo.h"
  108. #include "llvm/Target/TargetMachine.h"
  109. #include "llvm/Target/TargetOptions.h"
  110. #include "llvm/Transforms/Utils/Local.h"
  111. #include <algorithm>
  112. #include <cassert>
  113. #include <cstddef>
  114. #include <cstdint>
  115. #include <cstring>
  116. #include <iterator>
  117. #include <limits>
  118. #include <numeric>
  119. #include <tuple>
  120. #include <utility>
  121. #include <vector>
  122. using namespace llvm;
  123. using namespace PatternMatch;
  124. #define DEBUG_TYPE "isel"
  125. /// LimitFloatPrecision - Generate low-precision inline sequences for
  126. /// some float libcalls (6, 8 or 12 bits).
  127. static unsigned LimitFloatPrecision;
  128. static cl::opt<unsigned, true>
  129. LimitFPPrecision("limit-float-precision",
  130. cl::desc("Generate low-precision inline sequences "
  131. "for some float libcalls"),
  132. cl::location(LimitFloatPrecision), cl::Hidden,
  133. cl::init(0));
  134. static cl::opt<unsigned> SwitchPeelThreshold(
  135. "switch-peel-threshold", cl::Hidden, cl::init(66),
  136. cl::desc("Set the case probability threshold for peeling the case from a "
  137. "switch statement. A value greater than 100 will void this "
  138. "optimization"));
  139. // Limit the width of DAG chains. This is important in general to prevent
  140. // DAG-based analysis from blowing up. For example, alias analysis and
  141. // load clustering may not complete in reasonable time. It is difficult to
  142. // recognize and avoid this situation within each individual analysis, and
  143. // future analyses are likely to have the same behavior. Limiting DAG width is
  144. // the safe approach and will be especially important with global DAGs.
  145. //
  146. // MaxParallelChains default is arbitrarily high to avoid affecting
  147. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  148. // sequence over this should have been converted to llvm.memcpy by the
  149. // frontend. It is easy to induce this behavior with .ll code such as:
  150. // %buffer = alloca [4096 x i8]
  151. // %data = load [4096 x i8]* %argPtr
  152. // store [4096 x i8] %data, [4096 x i8]* %buffer
  153. static const unsigned MaxParallelChains = 64;
  154. // Return the calling convention if the Value passed requires ABI mangling as it
  155. // is a parameter to a function or a return value from a function which is not
  156. // an intrinsic.
  157. static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
  158. if (auto *R = dyn_cast<ReturnInst>(V))
  159. return R->getParent()->getParent()->getCallingConv();
  160. if (auto *CI = dyn_cast<CallInst>(V)) {
  161. const bool IsInlineAsm = CI->isInlineAsm();
  162. const bool IsIndirectFunctionCall =
  163. !IsInlineAsm && !CI->getCalledFunction();
  164. // It is possible that the call instruction is an inline asm statement or an
  165. // indirect function call in which case the return value of
  166. // getCalledFunction() would be nullptr.
  167. const bool IsInstrinsicCall =
  168. !IsInlineAsm && !IsIndirectFunctionCall &&
  169. CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
  170. if (!IsInlineAsm && !IsInstrinsicCall)
  171. return CI->getCallingConv();
  172. }
  173. return None;
  174. }
  175. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  176. const SDValue *Parts, unsigned NumParts,
  177. MVT PartVT, EVT ValueVT, const Value *V,
  178. Optional<CallingConv::ID> CC);
  179. /// getCopyFromParts - Create a value that contains the specified legal parts
  180. /// combined into the value they represent. If the parts combine to a type
  181. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  182. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  183. /// (ISD::AssertSext).
  184. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  185. const SDValue *Parts, unsigned NumParts,
  186. MVT PartVT, EVT ValueVT, const Value *V,
  187. Optional<CallingConv::ID> CC = None,
  188. Optional<ISD::NodeType> AssertOp = None) {
  189. if (ValueVT.isVector())
  190. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  191. CC);
  192. assert(NumParts > 0 && "No parts to assemble!");
  193. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  194. SDValue Val = Parts[0];
  195. if (NumParts > 1) {
  196. // Assemble the value from multiple parts.
  197. if (ValueVT.isInteger()) {
  198. unsigned PartBits = PartVT.getSizeInBits();
  199. unsigned ValueBits = ValueVT.getSizeInBits();
  200. // Assemble the power of 2 part.
  201. unsigned RoundParts = NumParts & (NumParts - 1) ?
  202. 1 << Log2_32(NumParts) : NumParts;
  203. unsigned RoundBits = PartBits * RoundParts;
  204. EVT RoundVT = RoundBits == ValueBits ?
  205. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  206. SDValue Lo, Hi;
  207. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  208. if (RoundParts > 2) {
  209. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  210. PartVT, HalfVT, V);
  211. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  212. RoundParts / 2, PartVT, HalfVT, V);
  213. } else {
  214. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  215. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  216. }
  217. if (DAG.getDataLayout().isBigEndian())
  218. std::swap(Lo, Hi);
  219. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  220. if (RoundParts < NumParts) {
  221. // Assemble the trailing non-power-of-2 part.
  222. unsigned OddParts = NumParts - RoundParts;
  223. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  224. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  225. OddVT, V, CC);
  226. // Combine the round and odd parts.
  227. Lo = Val;
  228. if (DAG.getDataLayout().isBigEndian())
  229. std::swap(Lo, Hi);
  230. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  231. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  232. Hi =
  233. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  234. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  235. TLI.getPointerTy(DAG.getDataLayout())));
  236. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  237. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  238. }
  239. } else if (PartVT.isFloatingPoint()) {
  240. // FP split into multiple FP parts (for ppcf128)
  241. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  242. "Unexpected split");
  243. SDValue Lo, Hi;
  244. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  245. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  246. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  247. std::swap(Lo, Hi);
  248. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  249. } else {
  250. // FP split into integer parts (soft fp)
  251. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  252. !PartVT.isVector() && "Unexpected split");
  253. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  254. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  255. }
  256. }
  257. // There is now one part, held in Val. Correct it to match ValueVT.
  258. // PartEVT is the type of the register class that holds the value.
  259. // ValueVT is the type of the inline asm operation.
  260. EVT PartEVT = Val.getValueType();
  261. if (PartEVT == ValueVT)
  262. return Val;
  263. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  264. ValueVT.bitsLT(PartEVT)) {
  265. // For an FP value in an integer part, we need to truncate to the right
  266. // width first.
  267. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  268. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  269. }
  270. // Handle types that have the same size.
  271. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  272. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  273. // Handle types with different sizes.
  274. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  275. if (ValueVT.bitsLT(PartEVT)) {
  276. // For a truncate, see if we have any information to
  277. // indicate whether the truncated bits will always be
  278. // zero or sign-extension.
  279. if (AssertOp.hasValue())
  280. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  281. DAG.getValueType(ValueVT));
  282. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  283. }
  284. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  285. }
  286. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  287. // FP_ROUND's are always exact here.
  288. if (ValueVT.bitsLT(Val.getValueType()))
  289. return DAG.getNode(
  290. ISD::FP_ROUND, DL, ValueVT, Val,
  291. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  292. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  293. }
  294. llvm_unreachable("Unknown mismatch!");
  295. }
  296. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  297. const Twine &ErrMsg) {
  298. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  299. if (!V)
  300. return Ctx.emitError(ErrMsg);
  301. const char *AsmError = ", possible invalid constraint for vector type";
  302. if (const CallInst *CI = dyn_cast<CallInst>(I))
  303. if (isa<InlineAsm>(CI->getCalledValue()))
  304. return Ctx.emitError(I, ErrMsg + AsmError);
  305. return Ctx.emitError(I, ErrMsg);
  306. }
  307. /// getCopyFromPartsVector - Create a value that contains the specified legal
  308. /// parts combined into the value they represent. If the parts combine to a
  309. /// type larger than ValueVT then AssertOp can be used to specify whether the
  310. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  311. /// ValueVT (ISD::AssertSext).
  312. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  313. const SDValue *Parts, unsigned NumParts,
  314. MVT PartVT, EVT ValueVT, const Value *V,
  315. Optional<CallingConv::ID> CallConv) {
  316. assert(ValueVT.isVector() && "Not a vector value");
  317. assert(NumParts > 0 && "No parts to assemble!");
  318. const bool IsABIRegCopy = CallConv.hasValue();
  319. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  320. SDValue Val = Parts[0];
  321. // Handle a multi-element vector.
  322. if (NumParts > 1) {
  323. EVT IntermediateVT;
  324. MVT RegisterVT;
  325. unsigned NumIntermediates;
  326. unsigned NumRegs;
  327. if (IsABIRegCopy) {
  328. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  329. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  330. NumIntermediates, RegisterVT);
  331. } else {
  332. NumRegs =
  333. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  334. NumIntermediates, RegisterVT);
  335. }
  336. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  337. NumParts = NumRegs; // Silence a compiler warning.
  338. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  339. assert(RegisterVT.getSizeInBits() ==
  340. Parts[0].getSimpleValueType().getSizeInBits() &&
  341. "Part type sizes don't match!");
  342. // Assemble the parts into intermediate operands.
  343. SmallVector<SDValue, 8> Ops(NumIntermediates);
  344. if (NumIntermediates == NumParts) {
  345. // If the register was not expanded, truncate or copy the value,
  346. // as appropriate.
  347. for (unsigned i = 0; i != NumParts; ++i)
  348. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  349. PartVT, IntermediateVT, V);
  350. } else if (NumParts > 0) {
  351. // If the intermediate type was expanded, build the intermediate
  352. // operands from the parts.
  353. assert(NumParts % NumIntermediates == 0 &&
  354. "Must expand into a divisible number of parts!");
  355. unsigned Factor = NumParts / NumIntermediates;
  356. for (unsigned i = 0; i != NumIntermediates; ++i)
  357. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  358. PartVT, IntermediateVT, V);
  359. }
  360. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  361. // intermediate operands.
  362. EVT BuiltVectorTy =
  363. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  364. (IntermediateVT.isVector()
  365. ? IntermediateVT.getVectorNumElements() * NumParts
  366. : NumIntermediates));
  367. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  368. : ISD::BUILD_VECTOR,
  369. DL, BuiltVectorTy, Ops);
  370. }
  371. // There is now one part, held in Val. Correct it to match ValueVT.
  372. EVT PartEVT = Val.getValueType();
  373. if (PartEVT == ValueVT)
  374. return Val;
  375. if (PartEVT.isVector()) {
  376. // If the element type of the source/dest vectors are the same, but the
  377. // parts vector has more elements than the value vector, then we have a
  378. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  379. // elements we want.
  380. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  381. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  382. "Cannot narrow, it would be a lossy transformation");
  383. return DAG.getNode(
  384. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  385. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  386. }
  387. // Vector/Vector bitcast.
  388. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  389. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  390. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  391. "Cannot handle this kind of promotion");
  392. // Promoted vector extract
  393. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  394. }
  395. // Trivial bitcast if the types are the same size and the destination
  396. // vector type is legal.
  397. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  398. TLI.isTypeLegal(ValueVT))
  399. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  400. if (ValueVT.getVectorNumElements() != 1) {
  401. // Certain ABIs require that vectors are passed as integers. For vectors
  402. // are the same size, this is an obvious bitcast.
  403. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  404. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  405. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  406. // Bitcast Val back the original type and extract the corresponding
  407. // vector we want.
  408. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  409. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  410. ValueVT.getVectorElementType(), Elts);
  411. Val = DAG.getBitcast(WiderVecType, Val);
  412. return DAG.getNode(
  413. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  414. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  415. }
  416. diagnosePossiblyInvalidConstraint(
  417. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  418. return DAG.getUNDEF(ValueVT);
  419. }
  420. // Handle cases such as i8 -> <1 x i1>
  421. EVT ValueSVT = ValueVT.getVectorElementType();
  422. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  423. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  424. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  425. return DAG.getBuildVector(ValueVT, DL, Val);
  426. }
  427. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  428. SDValue Val, SDValue *Parts, unsigned NumParts,
  429. MVT PartVT, const Value *V,
  430. Optional<CallingConv::ID> CallConv);
  431. /// getCopyToParts - Create a series of nodes that contain the specified value
  432. /// split into legal parts. If the parts contain more bits than Val, then, for
  433. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  434. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  435. SDValue *Parts, unsigned NumParts, MVT PartVT,
  436. const Value *V,
  437. Optional<CallingConv::ID> CallConv = None,
  438. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  439. EVT ValueVT = Val.getValueType();
  440. // Handle the vector case separately.
  441. if (ValueVT.isVector())
  442. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  443. CallConv);
  444. unsigned PartBits = PartVT.getSizeInBits();
  445. unsigned OrigNumParts = NumParts;
  446. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  447. "Copying to an illegal type!");
  448. if (NumParts == 0)
  449. return;
  450. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  451. EVT PartEVT = PartVT;
  452. if (PartEVT == ValueVT) {
  453. assert(NumParts == 1 && "No-op copy with multiple parts!");
  454. Parts[0] = Val;
  455. return;
  456. }
  457. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  458. // If the parts cover more bits than the value has, promote the value.
  459. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  460. assert(NumParts == 1 && "Do not know what to promote to!");
  461. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  462. } else {
  463. if (ValueVT.isFloatingPoint()) {
  464. // FP values need to be bitcast, then extended if they are being put
  465. // into a larger container.
  466. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  467. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  468. }
  469. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  470. ValueVT.isInteger() &&
  471. "Unknown mismatch!");
  472. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  473. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  474. if (PartVT == MVT::x86mmx)
  475. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  476. }
  477. } else if (PartBits == ValueVT.getSizeInBits()) {
  478. // Different types of the same size.
  479. assert(NumParts == 1 && PartEVT != ValueVT);
  480. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  481. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  482. // If the parts cover less bits than value has, truncate the value.
  483. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  484. ValueVT.isInteger() &&
  485. "Unknown mismatch!");
  486. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  487. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  488. if (PartVT == MVT::x86mmx)
  489. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  490. }
  491. // The value may have changed - recompute ValueVT.
  492. ValueVT = Val.getValueType();
  493. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  494. "Failed to tile the value with PartVT!");
  495. if (NumParts == 1) {
  496. if (PartEVT != ValueVT) {
  497. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  498. "scalar-to-vector conversion failed");
  499. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  500. }
  501. Parts[0] = Val;
  502. return;
  503. }
  504. // Expand the value into multiple parts.
  505. if (NumParts & (NumParts - 1)) {
  506. // The number of parts is not a power of 2. Split off and copy the tail.
  507. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  508. "Do not know what to expand to!");
  509. unsigned RoundParts = 1 << Log2_32(NumParts);
  510. unsigned RoundBits = RoundParts * PartBits;
  511. unsigned OddParts = NumParts - RoundParts;
  512. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  513. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  514. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  515. CallConv);
  516. if (DAG.getDataLayout().isBigEndian())
  517. // The odd parts were reversed by getCopyToParts - unreverse them.
  518. std::reverse(Parts + RoundParts, Parts + NumParts);
  519. NumParts = RoundParts;
  520. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  521. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  522. }
  523. // The number of parts is a power of 2. Repeatedly bisect the value using
  524. // EXTRACT_ELEMENT.
  525. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  526. EVT::getIntegerVT(*DAG.getContext(),
  527. ValueVT.getSizeInBits()),
  528. Val);
  529. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  530. for (unsigned i = 0; i < NumParts; i += StepSize) {
  531. unsigned ThisBits = StepSize * PartBits / 2;
  532. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  533. SDValue &Part0 = Parts[i];
  534. SDValue &Part1 = Parts[i+StepSize/2];
  535. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  536. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  537. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  538. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  539. if (ThisBits == PartBits && ThisVT != PartVT) {
  540. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  541. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  542. }
  543. }
  544. }
  545. if (DAG.getDataLayout().isBigEndian())
  546. std::reverse(Parts, Parts + OrigNumParts);
  547. }
  548. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  549. SDValue Val, const SDLoc &DL, EVT PartVT) {
  550. if (!PartVT.isVector())
  551. return SDValue();
  552. EVT ValueVT = Val.getValueType();
  553. unsigned PartNumElts = PartVT.getVectorNumElements();
  554. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  555. if (PartNumElts > ValueNumElts &&
  556. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  557. EVT ElementVT = PartVT.getVectorElementType();
  558. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  559. // undef elements.
  560. SmallVector<SDValue, 16> Ops;
  561. DAG.ExtractVectorElements(Val, Ops);
  562. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  563. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  564. Ops.push_back(EltUndef);
  565. // FIXME: Use CONCAT for 2x -> 4x.
  566. return DAG.getBuildVector(PartVT, DL, Ops);
  567. }
  568. return SDValue();
  569. }
  570. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  571. /// value split into legal parts.
  572. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  573. SDValue Val, SDValue *Parts, unsigned NumParts,
  574. MVT PartVT, const Value *V,
  575. Optional<CallingConv::ID> CallConv) {
  576. EVT ValueVT = Val.getValueType();
  577. assert(ValueVT.isVector() && "Not a vector");
  578. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  579. const bool IsABIRegCopy = CallConv.hasValue();
  580. if (NumParts == 1) {
  581. EVT PartEVT = PartVT;
  582. if (PartEVT == ValueVT) {
  583. // Nothing to do.
  584. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  585. // Bitconvert vector->vector case.
  586. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  587. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  588. Val = Widened;
  589. } else if (PartVT.isVector() &&
  590. PartEVT.getVectorElementType().bitsGE(
  591. ValueVT.getVectorElementType()) &&
  592. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  593. // Promoted vector extract
  594. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  595. } else {
  596. if (ValueVT.getVectorNumElements() == 1) {
  597. Val = DAG.getNode(
  598. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  599. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  600. } else {
  601. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  602. "lossy conversion of vector to scalar type");
  603. EVT IntermediateType =
  604. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  605. Val = DAG.getBitcast(IntermediateType, Val);
  606. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  607. }
  608. }
  609. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  610. Parts[0] = Val;
  611. return;
  612. }
  613. // Handle a multi-element vector.
  614. EVT IntermediateVT;
  615. MVT RegisterVT;
  616. unsigned NumIntermediates;
  617. unsigned NumRegs;
  618. if (IsABIRegCopy) {
  619. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  620. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  621. NumIntermediates, RegisterVT);
  622. } else {
  623. NumRegs =
  624. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  625. NumIntermediates, RegisterVT);
  626. }
  627. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  628. NumParts = NumRegs; // Silence a compiler warning.
  629. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  630. unsigned IntermediateNumElts = IntermediateVT.isVector() ?
  631. IntermediateVT.getVectorNumElements() : 1;
  632. // Convert the vector to the appropiate type if necessary.
  633. unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
  634. EVT BuiltVectorTy = EVT::getVectorVT(
  635. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  636. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  637. if (ValueVT != BuiltVectorTy) {
  638. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  639. Val = Widened;
  640. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  641. }
  642. // Split the vector into intermediate operands.
  643. SmallVector<SDValue, 8> Ops(NumIntermediates);
  644. for (unsigned i = 0; i != NumIntermediates; ++i) {
  645. if (IntermediateVT.isVector()) {
  646. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  647. DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
  648. } else {
  649. Ops[i] = DAG.getNode(
  650. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  651. DAG.getConstant(i, DL, IdxVT));
  652. }
  653. }
  654. // Split the intermediate operands into legal parts.
  655. if (NumParts == NumIntermediates) {
  656. // If the register was not expanded, promote or copy the value,
  657. // as appropriate.
  658. for (unsigned i = 0; i != NumParts; ++i)
  659. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  660. } else if (NumParts > 0) {
  661. // If the intermediate type was expanded, split each the value into
  662. // legal parts.
  663. assert(NumIntermediates != 0 && "division by zero");
  664. assert(NumParts % NumIntermediates == 0 &&
  665. "Must expand into a divisible number of parts!");
  666. unsigned Factor = NumParts / NumIntermediates;
  667. for (unsigned i = 0; i != NumIntermediates; ++i)
  668. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  669. CallConv);
  670. }
  671. }
  672. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  673. EVT valuevt, Optional<CallingConv::ID> CC)
  674. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  675. RegCount(1, regs.size()), CallConv(CC) {}
  676. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  677. const DataLayout &DL, unsigned Reg, Type *Ty,
  678. Optional<CallingConv::ID> CC) {
  679. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  680. CallConv = CC;
  681. for (EVT ValueVT : ValueVTs) {
  682. unsigned NumRegs =
  683. isABIMangled()
  684. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  685. : TLI.getNumRegisters(Context, ValueVT);
  686. MVT RegisterVT =
  687. isABIMangled()
  688. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  689. : TLI.getRegisterType(Context, ValueVT);
  690. for (unsigned i = 0; i != NumRegs; ++i)
  691. Regs.push_back(Reg + i);
  692. RegVTs.push_back(RegisterVT);
  693. RegCount.push_back(NumRegs);
  694. Reg += NumRegs;
  695. }
  696. }
  697. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  698. FunctionLoweringInfo &FuncInfo,
  699. const SDLoc &dl, SDValue &Chain,
  700. SDValue *Flag, const Value *V) const {
  701. // A Value with type {} or [0 x %t] needs no registers.
  702. if (ValueVTs.empty())
  703. return SDValue();
  704. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  705. // Assemble the legal parts into the final values.
  706. SmallVector<SDValue, 4> Values(ValueVTs.size());
  707. SmallVector<SDValue, 8> Parts;
  708. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  709. // Copy the legal parts from the registers.
  710. EVT ValueVT = ValueVTs[Value];
  711. unsigned NumRegs = RegCount[Value];
  712. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  713. *DAG.getContext(),
  714. CallConv.getValue(), RegVTs[Value])
  715. : RegVTs[Value];
  716. Parts.resize(NumRegs);
  717. for (unsigned i = 0; i != NumRegs; ++i) {
  718. SDValue P;
  719. if (!Flag) {
  720. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  721. } else {
  722. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  723. *Flag = P.getValue(2);
  724. }
  725. Chain = P.getValue(1);
  726. Parts[i] = P;
  727. // If the source register was virtual and if we know something about it,
  728. // add an assert node.
  729. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  730. !RegisterVT.isInteger())
  731. continue;
  732. const FunctionLoweringInfo::LiveOutInfo *LOI =
  733. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  734. if (!LOI)
  735. continue;
  736. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  737. unsigned NumSignBits = LOI->NumSignBits;
  738. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  739. if (NumZeroBits == RegSize) {
  740. // The current value is a zero.
  741. // Explicitly express that as it would be easier for
  742. // optimizations to kick in.
  743. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  744. continue;
  745. }
  746. // FIXME: We capture more information than the dag can represent. For
  747. // now, just use the tightest assertzext/assertsext possible.
  748. bool isSExt;
  749. EVT FromVT(MVT::Other);
  750. if (NumZeroBits) {
  751. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  752. isSExt = false;
  753. } else if (NumSignBits > 1) {
  754. FromVT =
  755. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  756. isSExt = true;
  757. } else {
  758. continue;
  759. }
  760. // Add an assertion node.
  761. assert(FromVT != MVT::Other);
  762. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  763. RegisterVT, P, DAG.getValueType(FromVT));
  764. }
  765. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  766. RegisterVT, ValueVT, V, CallConv);
  767. Part += NumRegs;
  768. Parts.clear();
  769. }
  770. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  771. }
  772. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  773. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  774. const Value *V,
  775. ISD::NodeType PreferredExtendType) const {
  776. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  777. ISD::NodeType ExtendKind = PreferredExtendType;
  778. // Get the list of the values's legal parts.
  779. unsigned NumRegs = Regs.size();
  780. SmallVector<SDValue, 8> Parts(NumRegs);
  781. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  782. unsigned NumParts = RegCount[Value];
  783. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  784. *DAG.getContext(),
  785. CallConv.getValue(), RegVTs[Value])
  786. : RegVTs[Value];
  787. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  788. ExtendKind = ISD::ZERO_EXTEND;
  789. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  790. NumParts, RegisterVT, V, CallConv, ExtendKind);
  791. Part += NumParts;
  792. }
  793. // Copy the parts into the registers.
  794. SmallVector<SDValue, 8> Chains(NumRegs);
  795. for (unsigned i = 0; i != NumRegs; ++i) {
  796. SDValue Part;
  797. if (!Flag) {
  798. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  799. } else {
  800. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  801. *Flag = Part.getValue(1);
  802. }
  803. Chains[i] = Part.getValue(0);
  804. }
  805. if (NumRegs == 1 || Flag)
  806. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  807. // flagged to it. That is the CopyToReg nodes and the user are considered
  808. // a single scheduling unit. If we create a TokenFactor and return it as
  809. // chain, then the TokenFactor is both a predecessor (operand) of the
  810. // user as well as a successor (the TF operands are flagged to the user).
  811. // c1, f1 = CopyToReg
  812. // c2, f2 = CopyToReg
  813. // c3 = TokenFactor c1, c2
  814. // ...
  815. // = op c3, ..., f2
  816. Chain = Chains[NumRegs-1];
  817. else
  818. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  819. }
  820. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  821. unsigned MatchingIdx, const SDLoc &dl,
  822. SelectionDAG &DAG,
  823. std::vector<SDValue> &Ops) const {
  824. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  825. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  826. if (HasMatching)
  827. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  828. else if (!Regs.empty() &&
  829. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  830. // Put the register class of the virtual registers in the flag word. That
  831. // way, later passes can recompute register class constraints for inline
  832. // assembly as well as normal instructions.
  833. // Don't do this for tied operands that can use the regclass information
  834. // from the def.
  835. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  836. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  837. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  838. }
  839. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  840. Ops.push_back(Res);
  841. if (Code == InlineAsm::Kind_Clobber) {
  842. // Clobbers should always have a 1:1 mapping with registers, and may
  843. // reference registers that have illegal (e.g. vector) types. Hence, we
  844. // shouldn't try to apply any sort of splitting logic to them.
  845. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  846. "No 1:1 mapping from clobbers to regs?");
  847. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  848. (void)SP;
  849. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  850. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  851. assert(
  852. (Regs[I] != SP ||
  853. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  854. "If we clobbered the stack pointer, MFI should know about it.");
  855. }
  856. return;
  857. }
  858. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  859. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  860. MVT RegisterVT = RegVTs[Value];
  861. for (unsigned i = 0; i != NumRegs; ++i) {
  862. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  863. unsigned TheReg = Regs[Reg++];
  864. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  865. }
  866. }
  867. }
  868. SmallVector<std::pair<unsigned, unsigned>, 4>
  869. RegsForValue::getRegsAndSizes() const {
  870. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  871. unsigned I = 0;
  872. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  873. unsigned RegCount = std::get<0>(CountAndVT);
  874. MVT RegisterVT = std::get<1>(CountAndVT);
  875. unsigned RegisterSize = RegisterVT.getSizeInBits();
  876. for (unsigned E = I + RegCount; I != E; ++I)
  877. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  878. }
  879. return OutVec;
  880. }
  881. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  882. const TargetLibraryInfo *li) {
  883. AA = aa;
  884. GFI = gfi;
  885. LibInfo = li;
  886. DL = &DAG.getDataLayout();
  887. Context = DAG.getContext();
  888. LPadToCallSiteMap.clear();
  889. }
  890. void SelectionDAGBuilder::clear() {
  891. NodeMap.clear();
  892. UnusedArgNodeMap.clear();
  893. PendingLoads.clear();
  894. PendingExports.clear();
  895. CurInst = nullptr;
  896. HasTailCall = false;
  897. SDNodeOrder = LowestSDNodeOrder;
  898. StatepointLowering.clear();
  899. }
  900. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  901. DanglingDebugInfoMap.clear();
  902. }
  903. SDValue SelectionDAGBuilder::getRoot() {
  904. if (PendingLoads.empty())
  905. return DAG.getRoot();
  906. if (PendingLoads.size() == 1) {
  907. SDValue Root = PendingLoads[0];
  908. DAG.setRoot(Root);
  909. PendingLoads.clear();
  910. return Root;
  911. }
  912. // Otherwise, we have to make a token factor node.
  913. SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
  914. PendingLoads.clear();
  915. DAG.setRoot(Root);
  916. return Root;
  917. }
  918. SDValue SelectionDAGBuilder::getControlRoot() {
  919. SDValue Root = DAG.getRoot();
  920. if (PendingExports.empty())
  921. return Root;
  922. // Turn all of the CopyToReg chains into one factored node.
  923. if (Root.getOpcode() != ISD::EntryToken) {
  924. unsigned i = 0, e = PendingExports.size();
  925. for (; i != e; ++i) {
  926. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  927. if (PendingExports[i].getNode()->getOperand(0) == Root)
  928. break; // Don't add the root if we already indirectly depend on it.
  929. }
  930. if (i == e)
  931. PendingExports.push_back(Root);
  932. }
  933. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  934. PendingExports);
  935. PendingExports.clear();
  936. DAG.setRoot(Root);
  937. return Root;
  938. }
  939. void SelectionDAGBuilder::visit(const Instruction &I) {
  940. // Set up outgoing PHI node register values before emitting the terminator.
  941. if (I.isTerminator()) {
  942. HandlePHINodesInSuccessorBlocks(I.getParent());
  943. }
  944. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  945. if (!isa<DbgInfoIntrinsic>(I))
  946. ++SDNodeOrder;
  947. CurInst = &I;
  948. visit(I.getOpcode(), I);
  949. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  950. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  951. // maps to this instruction.
  952. // TODO: We could handle all flags (nsw, etc) here.
  953. // TODO: If an IR instruction maps to >1 node, only the final node will have
  954. // flags set.
  955. if (SDNode *Node = getNodeForIRValue(&I)) {
  956. SDNodeFlags IncomingFlags;
  957. IncomingFlags.copyFMF(*FPMO);
  958. if (!Node->getFlags().isDefined())
  959. Node->setFlags(IncomingFlags);
  960. else
  961. Node->intersectFlagsWith(IncomingFlags);
  962. }
  963. }
  964. if (!I.isTerminator() && !HasTailCall &&
  965. !isStatepoint(&I)) // statepoints handle their exports internally
  966. CopyToExportRegsIfNeeded(&I);
  967. CurInst = nullptr;
  968. }
  969. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  970. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  971. }
  972. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  973. // Note: this doesn't use InstVisitor, because it has to work with
  974. // ConstantExpr's in addition to instructions.
  975. switch (Opcode) {
  976. default: llvm_unreachable("Unknown instruction type encountered!");
  977. // Build the switch statement using the Instruction.def file.
  978. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  979. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  980. #include "llvm/IR/Instruction.def"
  981. }
  982. }
  983. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  984. const DIExpression *Expr) {
  985. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  986. const DbgValueInst *DI = DDI.getDI();
  987. DIVariable *DanglingVariable = DI->getVariable();
  988. DIExpression *DanglingExpr = DI->getExpression();
  989. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  990. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  991. return true;
  992. }
  993. return false;
  994. };
  995. for (auto &DDIMI : DanglingDebugInfoMap) {
  996. DanglingDebugInfoVector &DDIV = DDIMI.second;
  997. // If debug info is to be dropped, run it through final checks to see
  998. // whether it can be salvaged.
  999. for (auto &DDI : DDIV)
  1000. if (isMatchingDbgValue(DDI))
  1001. salvageUnresolvedDbgValue(DDI);
  1002. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  1003. }
  1004. }
  1005. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1006. // generate the debug data structures now that we've seen its definition.
  1007. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1008. SDValue Val) {
  1009. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1010. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1011. return;
  1012. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1013. for (auto &DDI : DDIV) {
  1014. const DbgValueInst *DI = DDI.getDI();
  1015. assert(DI && "Ill-formed DanglingDebugInfo");
  1016. DebugLoc dl = DDI.getdl();
  1017. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1018. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1019. DILocalVariable *Variable = DI->getVariable();
  1020. DIExpression *Expr = DI->getExpression();
  1021. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1022. "Expected inlined-at fields to agree");
  1023. SDDbgValue *SDV;
  1024. if (Val.getNode()) {
  1025. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1026. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1027. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1028. // in the first place we should not be more successful here). Unless we
  1029. // have some test case that prove this to be correct we should avoid
  1030. // calling EmitFuncArgumentDbgValue here.
  1031. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1032. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1033. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1034. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1035. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1036. // inserted after the definition of Val when emitting the instructions
  1037. // after ISel. An alternative could be to teach
  1038. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1039. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1040. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1041. << ValSDNodeOrder << "\n");
  1042. SDV = getDbgValue(Val, Variable, Expr, dl,
  1043. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1044. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1045. } else
  1046. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1047. << "in EmitFuncArgumentDbgValue\n");
  1048. } else {
  1049. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1050. auto Undef =
  1051. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1052. auto SDV =
  1053. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1054. DAG.AddDbgValue(SDV, nullptr, false);
  1055. }
  1056. }
  1057. DDIV.clear();
  1058. }
  1059. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1060. Value *V = DDI.getDI()->getValue();
  1061. DILocalVariable *Var = DDI.getDI()->getVariable();
  1062. DIExpression *Expr = DDI.getDI()->getExpression();
  1063. DebugLoc DL = DDI.getdl();
  1064. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1065. unsigned SDOrder = DDI.getSDNodeOrder();
  1066. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1067. // that DW_OP_stack_value is desired.
  1068. assert(isa<DbgValueInst>(DDI.getDI()));
  1069. bool StackValue = true;
  1070. // Can this Value can be encoded without any further work?
  1071. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1072. return;
  1073. // Attempt to salvage back through as many instructions as possible. Bail if
  1074. // a non-instruction is seen, such as a constant expression or global
  1075. // variable. FIXME: Further work could recover those too.
  1076. while (isa<Instruction>(V)) {
  1077. Instruction &VAsInst = *cast<Instruction>(V);
  1078. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1079. // If we cannot salvage any further, and haven't yet found a suitable debug
  1080. // expression, bail out.
  1081. if (!NewExpr)
  1082. break;
  1083. // New value and expr now represent this debuginfo.
  1084. V = VAsInst.getOperand(0);
  1085. Expr = NewExpr;
  1086. // Some kind of simplification occurred: check whether the operand of the
  1087. // salvaged debug expression can be encoded in this DAG.
  1088. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1089. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1090. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1091. return;
  1092. }
  1093. }
  1094. // This was the final opportunity to salvage this debug information, and it
  1095. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1096. // any earlier variable location.
  1097. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1098. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1099. DAG.AddDbgValue(SDV, nullptr, false);
  1100. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1101. << "\n");
  1102. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1103. << "\n");
  1104. }
  1105. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1106. DIExpression *Expr, DebugLoc dl,
  1107. DebugLoc InstDL, unsigned Order) {
  1108. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1109. SDDbgValue *SDV;
  1110. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1111. isa<ConstantPointerNull>(V)) {
  1112. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1113. DAG.AddDbgValue(SDV, nullptr, false);
  1114. return true;
  1115. }
  1116. // If the Value is a frame index, we can create a FrameIndex debug value
  1117. // without relying on the DAG at all.
  1118. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1119. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1120. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1121. auto SDV =
  1122. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1123. /*IsIndirect*/ false, dl, SDNodeOrder);
  1124. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1125. // is still available even if the SDNode gets optimized out.
  1126. DAG.AddDbgValue(SDV, nullptr, false);
  1127. return true;
  1128. }
  1129. }
  1130. // Do not use getValue() in here; we don't want to generate code at
  1131. // this point if it hasn't been done yet.
  1132. SDValue N = NodeMap[V];
  1133. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1134. N = UnusedArgNodeMap[V];
  1135. if (N.getNode()) {
  1136. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1137. return true;
  1138. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1139. DAG.AddDbgValue(SDV, N.getNode(), false);
  1140. return true;
  1141. }
  1142. // Special rules apply for the first dbg.values of parameter variables in a
  1143. // function. Identify them by the fact they reference Argument Values, that
  1144. // they're parameters, and they are parameters of the current function. We
  1145. // need to let them dangle until they get an SDNode.
  1146. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1147. !InstDL.getInlinedAt();
  1148. if (!IsParamOfFunc) {
  1149. // The value is not used in this block yet (or it would have an SDNode).
  1150. // We still want the value to appear for the user if possible -- if it has
  1151. // an associated VReg, we can refer to that instead.
  1152. auto VMI = FuncInfo.ValueMap.find(V);
  1153. if (VMI != FuncInfo.ValueMap.end()) {
  1154. unsigned Reg = VMI->second;
  1155. // If this is a PHI node, it may be split up into several MI PHI nodes
  1156. // (in FunctionLoweringInfo::set).
  1157. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1158. V->getType(), None);
  1159. if (RFV.occupiesMultipleRegs()) {
  1160. unsigned Offset = 0;
  1161. unsigned BitsToDescribe = 0;
  1162. if (auto VarSize = Var->getSizeInBits())
  1163. BitsToDescribe = *VarSize;
  1164. if (auto Fragment = Expr->getFragmentInfo())
  1165. BitsToDescribe = Fragment->SizeInBits;
  1166. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1167. unsigned RegisterSize = RegAndSize.second;
  1168. // Bail out if all bits are described already.
  1169. if (Offset >= BitsToDescribe)
  1170. break;
  1171. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1172. ? BitsToDescribe - Offset
  1173. : RegisterSize;
  1174. auto FragmentExpr = DIExpression::createFragmentExpression(
  1175. Expr, Offset, FragmentSize);
  1176. if (!FragmentExpr)
  1177. continue;
  1178. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1179. false, dl, SDNodeOrder);
  1180. DAG.AddDbgValue(SDV, nullptr, false);
  1181. Offset += RegisterSize;
  1182. }
  1183. } else {
  1184. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1185. DAG.AddDbgValue(SDV, nullptr, false);
  1186. }
  1187. return true;
  1188. }
  1189. }
  1190. return false;
  1191. }
  1192. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1193. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1194. for (auto &Pair : DanglingDebugInfoMap)
  1195. for (auto &DDI : Pair.second)
  1196. salvageUnresolvedDbgValue(DDI);
  1197. clearDanglingDebugInfo();
  1198. }
  1199. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1200. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1201. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1202. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1203. SDValue Result;
  1204. if (It != FuncInfo.ValueMap.end()) {
  1205. unsigned InReg = It->second;
  1206. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1207. DAG.getDataLayout(), InReg, Ty,
  1208. None); // This is not an ABI copy.
  1209. SDValue Chain = DAG.getEntryNode();
  1210. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1211. V);
  1212. resolveDanglingDebugInfo(V, Result);
  1213. }
  1214. return Result;
  1215. }
  1216. /// getValue - Return an SDValue for the given Value.
  1217. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1218. // If we already have an SDValue for this value, use it. It's important
  1219. // to do this first, so that we don't create a CopyFromReg if we already
  1220. // have a regular SDValue.
  1221. SDValue &N = NodeMap[V];
  1222. if (N.getNode()) return N;
  1223. // If there's a virtual register allocated and initialized for this
  1224. // value, use it.
  1225. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1226. return copyFromReg;
  1227. // Otherwise create a new SDValue and remember it.
  1228. SDValue Val = getValueImpl(V);
  1229. NodeMap[V] = Val;
  1230. resolveDanglingDebugInfo(V, Val);
  1231. return Val;
  1232. }
  1233. // Return true if SDValue exists for the given Value
  1234. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1235. return (NodeMap.find(V) != NodeMap.end()) ||
  1236. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1237. }
  1238. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1239. /// don't look in FuncInfo.ValueMap for a virtual register.
  1240. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1241. // If we already have an SDValue for this value, use it.
  1242. SDValue &N = NodeMap[V];
  1243. if (N.getNode()) {
  1244. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1245. // Remove the debug location from the node as the node is about to be used
  1246. // in a location which may differ from the original debug location. This
  1247. // is relevant to Constant and ConstantFP nodes because they can appear
  1248. // as constant expressions inside PHI nodes.
  1249. N->setDebugLoc(DebugLoc());
  1250. }
  1251. return N;
  1252. }
  1253. // Otherwise create a new SDValue and remember it.
  1254. SDValue Val = getValueImpl(V);
  1255. NodeMap[V] = Val;
  1256. resolveDanglingDebugInfo(V, Val);
  1257. return Val;
  1258. }
  1259. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1260. /// Create an SDValue for the given value.
  1261. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1262. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1263. if (const Constant *C = dyn_cast<Constant>(V)) {
  1264. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1265. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1266. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1267. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1268. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1269. if (isa<ConstantPointerNull>(C)) {
  1270. unsigned AS = V->getType()->getPointerAddressSpace();
  1271. return DAG.getConstant(0, getCurSDLoc(),
  1272. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1273. }
  1274. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1275. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1276. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1277. return DAG.getUNDEF(VT);
  1278. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1279. visit(CE->getOpcode(), *CE);
  1280. SDValue N1 = NodeMap[V];
  1281. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1282. return N1;
  1283. }
  1284. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1285. SmallVector<SDValue, 4> Constants;
  1286. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1287. OI != OE; ++OI) {
  1288. SDNode *Val = getValue(*OI).getNode();
  1289. // If the operand is an empty aggregate, there are no values.
  1290. if (!Val) continue;
  1291. // Add each leaf value from the operand to the Constants list
  1292. // to form a flattened list of all the values.
  1293. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1294. Constants.push_back(SDValue(Val, i));
  1295. }
  1296. return DAG.getMergeValues(Constants, getCurSDLoc());
  1297. }
  1298. if (const ConstantDataSequential *CDS =
  1299. dyn_cast<ConstantDataSequential>(C)) {
  1300. SmallVector<SDValue, 4> Ops;
  1301. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1302. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1303. // Add each leaf value from the operand to the Constants list
  1304. // to form a flattened list of all the values.
  1305. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1306. Ops.push_back(SDValue(Val, i));
  1307. }
  1308. if (isa<ArrayType>(CDS->getType()))
  1309. return DAG.getMergeValues(Ops, getCurSDLoc());
  1310. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1311. }
  1312. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1313. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1314. "Unknown struct or array constant!");
  1315. SmallVector<EVT, 4> ValueVTs;
  1316. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1317. unsigned NumElts = ValueVTs.size();
  1318. if (NumElts == 0)
  1319. return SDValue(); // empty struct
  1320. SmallVector<SDValue, 4> Constants(NumElts);
  1321. for (unsigned i = 0; i != NumElts; ++i) {
  1322. EVT EltVT = ValueVTs[i];
  1323. if (isa<UndefValue>(C))
  1324. Constants[i] = DAG.getUNDEF(EltVT);
  1325. else if (EltVT.isFloatingPoint())
  1326. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1327. else
  1328. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1329. }
  1330. return DAG.getMergeValues(Constants, getCurSDLoc());
  1331. }
  1332. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1333. return DAG.getBlockAddress(BA, VT);
  1334. VectorType *VecTy = cast<VectorType>(V->getType());
  1335. unsigned NumElements = VecTy->getNumElements();
  1336. // Now that we know the number and type of the elements, get that number of
  1337. // elements into the Ops array based on what kind of constant it is.
  1338. SmallVector<SDValue, 16> Ops;
  1339. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1340. for (unsigned i = 0; i != NumElements; ++i)
  1341. Ops.push_back(getValue(CV->getOperand(i)));
  1342. } else {
  1343. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1344. EVT EltVT =
  1345. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1346. SDValue Op;
  1347. if (EltVT.isFloatingPoint())
  1348. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1349. else
  1350. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1351. Ops.assign(NumElements, Op);
  1352. }
  1353. // Create a BUILD_VECTOR node.
  1354. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1355. }
  1356. // If this is a static alloca, generate it as the frameindex instead of
  1357. // computation.
  1358. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1359. DenseMap<const AllocaInst*, int>::iterator SI =
  1360. FuncInfo.StaticAllocaMap.find(AI);
  1361. if (SI != FuncInfo.StaticAllocaMap.end())
  1362. return DAG.getFrameIndex(SI->second,
  1363. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1364. }
  1365. // If this is an instruction which fast-isel has deferred, select it now.
  1366. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1367. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1368. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1369. Inst->getType(), getABIRegCopyCC(V));
  1370. SDValue Chain = DAG.getEntryNode();
  1371. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1372. }
  1373. llvm_unreachable("Can't get register for value!");
  1374. }
  1375. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1376. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1377. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1378. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1379. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1380. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1381. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1382. if (!IsSEH)
  1383. CatchPadMBB->setIsEHScopeEntry();
  1384. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1385. if (IsMSVCCXX || IsCoreCLR)
  1386. CatchPadMBB->setIsEHFuncletEntry();
  1387. // Wasm does not need catchpads anymore
  1388. if (!IsWasmCXX)
  1389. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1390. getControlRoot()));
  1391. }
  1392. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1393. // Update machine-CFG edge.
  1394. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1395. FuncInfo.MBB->addSuccessor(TargetMBB);
  1396. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1397. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1398. if (IsSEH) {
  1399. // If this is not a fall-through branch or optimizations are switched off,
  1400. // emit the branch.
  1401. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1402. TM.getOptLevel() == CodeGenOpt::None)
  1403. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1404. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1405. return;
  1406. }
  1407. // Figure out the funclet membership for the catchret's successor.
  1408. // This will be used by the FuncletLayout pass to determine how to order the
  1409. // BB's.
  1410. // A 'catchret' returns to the outer scope's color.
  1411. Value *ParentPad = I.getCatchSwitchParentPad();
  1412. const BasicBlock *SuccessorColor;
  1413. if (isa<ConstantTokenNone>(ParentPad))
  1414. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1415. else
  1416. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1417. assert(SuccessorColor && "No parent funclet for catchret!");
  1418. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1419. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1420. // Create the terminator node.
  1421. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1422. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1423. DAG.getBasicBlock(SuccessorColorMBB));
  1424. DAG.setRoot(Ret);
  1425. }
  1426. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1427. // Don't emit any special code for the cleanuppad instruction. It just marks
  1428. // the start of an EH scope/funclet.
  1429. FuncInfo.MBB->setIsEHScopeEntry();
  1430. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1431. if (Pers != EHPersonality::Wasm_CXX) {
  1432. FuncInfo.MBB->setIsEHFuncletEntry();
  1433. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1434. }
  1435. }
  1436. // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
  1437. // the control flow always stops at the single catch pad, as it does for a
  1438. // cleanup pad. In case the exception caught is not of the types the catch pad
  1439. // catches, it will be rethrown by a rethrow.
  1440. static void findWasmUnwindDestinations(
  1441. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1442. BranchProbability Prob,
  1443. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1444. &UnwindDests) {
  1445. while (EHPadBB) {
  1446. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1447. if (isa<CleanupPadInst>(Pad)) {
  1448. // Stop on cleanup pads.
  1449. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1450. UnwindDests.back().first->setIsEHScopeEntry();
  1451. break;
  1452. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1453. // Add the catchpad handlers to the possible destinations. We don't
  1454. // continue to the unwind destination of the catchswitch for wasm.
  1455. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1456. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1457. UnwindDests.back().first->setIsEHScopeEntry();
  1458. }
  1459. break;
  1460. } else {
  1461. continue;
  1462. }
  1463. }
  1464. }
  1465. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1466. /// many places it could ultimately go. In the IR, we have a single unwind
  1467. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1468. /// This function skips over imaginary basic blocks that hold catchswitch
  1469. /// instructions, and finds all the "real" machine
  1470. /// basic block destinations. As those destinations may not be successors of
  1471. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1472. /// The passed-in Prob is the edge probability to EHPadBB.
  1473. static void findUnwindDestinations(
  1474. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1475. BranchProbability Prob,
  1476. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1477. &UnwindDests) {
  1478. EHPersonality Personality =
  1479. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1480. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1481. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1482. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1483. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1484. if (IsWasmCXX) {
  1485. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1486. assert(UnwindDests.size() <= 1 &&
  1487. "There should be at most one unwind destination for wasm");
  1488. return;
  1489. }
  1490. while (EHPadBB) {
  1491. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1492. BasicBlock *NewEHPadBB = nullptr;
  1493. if (isa<LandingPadInst>(Pad)) {
  1494. // Stop on landingpads. They are not funclets.
  1495. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1496. break;
  1497. } else if (isa<CleanupPadInst>(Pad)) {
  1498. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1499. // personalities.
  1500. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1501. UnwindDests.back().first->setIsEHScopeEntry();
  1502. UnwindDests.back().first->setIsEHFuncletEntry();
  1503. break;
  1504. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1505. // Add the catchpad handlers to the possible destinations.
  1506. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1507. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1508. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1509. if (IsMSVCCXX || IsCoreCLR)
  1510. UnwindDests.back().first->setIsEHFuncletEntry();
  1511. if (!IsSEH)
  1512. UnwindDests.back().first->setIsEHScopeEntry();
  1513. }
  1514. NewEHPadBB = CatchSwitch->getUnwindDest();
  1515. } else {
  1516. continue;
  1517. }
  1518. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1519. if (BPI && NewEHPadBB)
  1520. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1521. EHPadBB = NewEHPadBB;
  1522. }
  1523. }
  1524. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1525. // Update successor info.
  1526. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1527. auto UnwindDest = I.getUnwindDest();
  1528. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1529. BranchProbability UnwindDestProb =
  1530. (BPI && UnwindDest)
  1531. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1532. : BranchProbability::getZero();
  1533. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1534. for (auto &UnwindDest : UnwindDests) {
  1535. UnwindDest.first->setIsEHPad();
  1536. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1537. }
  1538. FuncInfo.MBB->normalizeSuccProbs();
  1539. // Create the terminator node.
  1540. SDValue Ret =
  1541. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1542. DAG.setRoot(Ret);
  1543. }
  1544. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1545. report_fatal_error("visitCatchSwitch not yet implemented!");
  1546. }
  1547. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1548. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1549. auto &DL = DAG.getDataLayout();
  1550. SDValue Chain = getControlRoot();
  1551. SmallVector<ISD::OutputArg, 8> Outs;
  1552. SmallVector<SDValue, 8> OutVals;
  1553. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1554. // lower
  1555. //
  1556. // %val = call <ty> @llvm.experimental.deoptimize()
  1557. // ret <ty> %val
  1558. //
  1559. // differently.
  1560. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1561. LowerDeoptimizingReturn();
  1562. return;
  1563. }
  1564. if (!FuncInfo.CanLowerReturn) {
  1565. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1566. const Function *F = I.getParent()->getParent();
  1567. // Emit a store of the return value through the virtual register.
  1568. // Leave Outs empty so that LowerReturn won't try to load return
  1569. // registers the usual way.
  1570. SmallVector<EVT, 1> PtrValueVTs;
  1571. ComputeValueVTs(TLI, DL,
  1572. F->getReturnType()->getPointerTo(
  1573. DAG.getDataLayout().getAllocaAddrSpace()),
  1574. PtrValueVTs);
  1575. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1576. DemoteReg, PtrValueVTs[0]);
  1577. SDValue RetOp = getValue(I.getOperand(0));
  1578. SmallVector<EVT, 4> ValueVTs;
  1579. SmallVector<uint64_t, 4> Offsets;
  1580. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  1581. unsigned NumValues = ValueVTs.size();
  1582. SmallVector<SDValue, 4> Chains(NumValues);
  1583. for (unsigned i = 0; i != NumValues; ++i) {
  1584. // An aggregate return value cannot wrap around the address space, so
  1585. // offsets to its parts don't wrap either.
  1586. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1587. Chains[i] = DAG.getStore(
  1588. Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  1589. // FIXME: better loc info would be nice.
  1590. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1591. }
  1592. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1593. MVT::Other, Chains);
  1594. } else if (I.getNumOperands() != 0) {
  1595. SmallVector<EVT, 4> ValueVTs;
  1596. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1597. unsigned NumValues = ValueVTs.size();
  1598. if (NumValues) {
  1599. SDValue RetOp = getValue(I.getOperand(0));
  1600. const Function *F = I.getParent()->getParent();
  1601. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1602. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1603. Attribute::SExt))
  1604. ExtendKind = ISD::SIGN_EXTEND;
  1605. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1606. Attribute::ZExt))
  1607. ExtendKind = ISD::ZERO_EXTEND;
  1608. LLVMContext &Context = F->getContext();
  1609. bool RetInReg = F->getAttributes().hasAttribute(
  1610. AttributeList::ReturnIndex, Attribute::InReg);
  1611. for (unsigned j = 0; j != NumValues; ++j) {
  1612. EVT VT = ValueVTs[j];
  1613. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1614. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1615. CallingConv::ID CC = F->getCallingConv();
  1616. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1617. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1618. SmallVector<SDValue, 4> Parts(NumParts);
  1619. getCopyToParts(DAG, getCurSDLoc(),
  1620. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1621. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1622. // 'inreg' on function refers to return value
  1623. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1624. if (RetInReg)
  1625. Flags.setInReg();
  1626. // Propagate extension type if any
  1627. if (ExtendKind == ISD::SIGN_EXTEND)
  1628. Flags.setSExt();
  1629. else if (ExtendKind == ISD::ZERO_EXTEND)
  1630. Flags.setZExt();
  1631. for (unsigned i = 0; i < NumParts; ++i) {
  1632. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1633. VT, /*isfixed=*/true, 0, 0));
  1634. OutVals.push_back(Parts[i]);
  1635. }
  1636. }
  1637. }
  1638. }
  1639. // Push in swifterror virtual register as the last element of Outs. This makes
  1640. // sure swifterror virtual register will be returned in the swifterror
  1641. // physical register.
  1642. const Function *F = I.getParent()->getParent();
  1643. if (TLI.supportSwiftError() &&
  1644. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1645. assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
  1646. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1647. Flags.setSwiftError();
  1648. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1649. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1650. true /*isfixed*/, 1 /*origidx*/,
  1651. 0 /*partOffs*/));
  1652. // Create SDNode for the swifterror virtual register.
  1653. OutVals.push_back(
  1654. DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
  1655. &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
  1656. EVT(TLI.getPointerTy(DL))));
  1657. }
  1658. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1659. CallingConv::ID CallConv =
  1660. DAG.getMachineFunction().getFunction().getCallingConv();
  1661. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1662. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1663. // Verify that the target's LowerReturn behaved as expected.
  1664. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1665. "LowerReturn didn't return a valid chain!");
  1666. // Update the DAG with the new chain value resulting from return lowering.
  1667. DAG.setRoot(Chain);
  1668. }
  1669. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1670. /// created for it, emit nodes to copy the value into the virtual
  1671. /// registers.
  1672. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1673. // Skip empty types
  1674. if (V->getType()->isEmptyTy())
  1675. return;
  1676. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1677. if (VMI != FuncInfo.ValueMap.end()) {
  1678. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1679. CopyValueToVirtualRegister(V, VMI->second);
  1680. }
  1681. }
  1682. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1683. /// the current basic block, add it to ValueMap now so that we'll get a
  1684. /// CopyTo/FromReg.
  1685. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1686. // No need to export constants.
  1687. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1688. // Already exported?
  1689. if (FuncInfo.isExportedInst(V)) return;
  1690. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1691. CopyValueToVirtualRegister(V, Reg);
  1692. }
  1693. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1694. const BasicBlock *FromBB) {
  1695. // The operands of the setcc have to be in this block. We don't know
  1696. // how to export them from some other block.
  1697. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1698. // Can export from current BB.
  1699. if (VI->getParent() == FromBB)
  1700. return true;
  1701. // Is already exported, noop.
  1702. return FuncInfo.isExportedInst(V);
  1703. }
  1704. // If this is an argument, we can export it if the BB is the entry block or
  1705. // if it is already exported.
  1706. if (isa<Argument>(V)) {
  1707. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1708. return true;
  1709. // Otherwise, can only export this if it is already exported.
  1710. return FuncInfo.isExportedInst(V);
  1711. }
  1712. // Otherwise, constants can always be exported.
  1713. return true;
  1714. }
  1715. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1716. BranchProbability
  1717. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1718. const MachineBasicBlock *Dst) const {
  1719. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1720. const BasicBlock *SrcBB = Src->getBasicBlock();
  1721. const BasicBlock *DstBB = Dst->getBasicBlock();
  1722. if (!BPI) {
  1723. // If BPI is not available, set the default probability as 1 / N, where N is
  1724. // the number of successors.
  1725. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1726. return BranchProbability(1, SuccSize);
  1727. }
  1728. return BPI->getEdgeProbability(SrcBB, DstBB);
  1729. }
  1730. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1731. MachineBasicBlock *Dst,
  1732. BranchProbability Prob) {
  1733. if (!FuncInfo.BPI)
  1734. Src->addSuccessorWithoutProb(Dst);
  1735. else {
  1736. if (Prob.isUnknown())
  1737. Prob = getEdgeProbability(Src, Dst);
  1738. Src->addSuccessor(Dst, Prob);
  1739. }
  1740. }
  1741. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1742. if (const Instruction *I = dyn_cast<Instruction>(V))
  1743. return I->getParent() == BB;
  1744. return true;
  1745. }
  1746. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1747. /// This function emits a branch and is used at the leaves of an OR or an
  1748. /// AND operator tree.
  1749. void
  1750. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1751. MachineBasicBlock *TBB,
  1752. MachineBasicBlock *FBB,
  1753. MachineBasicBlock *CurBB,
  1754. MachineBasicBlock *SwitchBB,
  1755. BranchProbability TProb,
  1756. BranchProbability FProb,
  1757. bool InvertCond) {
  1758. const BasicBlock *BB = CurBB->getBasicBlock();
  1759. // If the leaf of the tree is a comparison, merge the condition into
  1760. // the caseblock.
  1761. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1762. // The operands of the cmp have to be in this block. We don't know
  1763. // how to export them from some other block. If this is the first block
  1764. // of the sequence, no exporting is needed.
  1765. if (CurBB == SwitchBB ||
  1766. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1767. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1768. ISD::CondCode Condition;
  1769. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1770. ICmpInst::Predicate Pred =
  1771. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1772. Condition = getICmpCondCode(Pred);
  1773. } else {
  1774. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1775. FCmpInst::Predicate Pred =
  1776. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1777. Condition = getFCmpCondCode(Pred);
  1778. if (TM.Options.NoNaNsFPMath)
  1779. Condition = getFCmpCodeWithoutNaN(Condition);
  1780. }
  1781. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1782. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1783. SwitchCases.push_back(CB);
  1784. return;
  1785. }
  1786. }
  1787. // Create a CaseBlock record representing this branch.
  1788. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1789. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1790. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1791. SwitchCases.push_back(CB);
  1792. }
  1793. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1794. MachineBasicBlock *TBB,
  1795. MachineBasicBlock *FBB,
  1796. MachineBasicBlock *CurBB,
  1797. MachineBasicBlock *SwitchBB,
  1798. Instruction::BinaryOps Opc,
  1799. BranchProbability TProb,
  1800. BranchProbability FProb,
  1801. bool InvertCond) {
  1802. // Skip over not part of the tree and remember to invert op and operands at
  1803. // next level.
  1804. Value *NotCond;
  1805. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1806. InBlock(NotCond, CurBB->getBasicBlock())) {
  1807. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1808. !InvertCond);
  1809. return;
  1810. }
  1811. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1812. // Compute the effective opcode for Cond, taking into account whether it needs
  1813. // to be inverted, e.g.
  1814. // and (not (or A, B)), C
  1815. // gets lowered as
  1816. // and (and (not A, not B), C)
  1817. unsigned BOpc = 0;
  1818. if (BOp) {
  1819. BOpc = BOp->getOpcode();
  1820. if (InvertCond) {
  1821. if (BOpc == Instruction::And)
  1822. BOpc = Instruction::Or;
  1823. else if (BOpc == Instruction::Or)
  1824. BOpc = Instruction::And;
  1825. }
  1826. }
  1827. // If this node is not part of the or/and tree, emit it as a branch.
  1828. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1829. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1830. BOp->getParent() != CurBB->getBasicBlock() ||
  1831. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1832. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1833. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1834. TProb, FProb, InvertCond);
  1835. return;
  1836. }
  1837. // Create TmpBB after CurBB.
  1838. MachineFunction::iterator BBI(CurBB);
  1839. MachineFunction &MF = DAG.getMachineFunction();
  1840. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1841. CurBB->getParent()->insert(++BBI, TmpBB);
  1842. if (Opc == Instruction::Or) {
  1843. // Codegen X | Y as:
  1844. // BB1:
  1845. // jmp_if_X TBB
  1846. // jmp TmpBB
  1847. // TmpBB:
  1848. // jmp_if_Y TBB
  1849. // jmp FBB
  1850. //
  1851. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1852. // The requirement is that
  1853. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1854. // = TrueProb for original BB.
  1855. // Assuming the original probabilities are A and B, one choice is to set
  1856. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1857. // A/(1+B) and 2B/(1+B). This choice assumes that
  1858. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1859. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1860. // TmpBB, but the math is more complicated.
  1861. auto NewTrueProb = TProb / 2;
  1862. auto NewFalseProb = TProb / 2 + FProb;
  1863. // Emit the LHS condition.
  1864. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1865. NewTrueProb, NewFalseProb, InvertCond);
  1866. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1867. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1868. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1869. // Emit the RHS condition into TmpBB.
  1870. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1871. Probs[0], Probs[1], InvertCond);
  1872. } else {
  1873. assert(Opc == Instruction::And && "Unknown merge op!");
  1874. // Codegen X & Y as:
  1875. // BB1:
  1876. // jmp_if_X TmpBB
  1877. // jmp FBB
  1878. // TmpBB:
  1879. // jmp_if_Y TBB
  1880. // jmp FBB
  1881. //
  1882. // This requires creation of TmpBB after CurBB.
  1883. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1884. // The requirement is that
  1885. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1886. // = FalseProb for original BB.
  1887. // Assuming the original probabilities are A and B, one choice is to set
  1888. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1889. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1890. // TrueProb for BB1 * FalseProb for TmpBB.
  1891. auto NewTrueProb = TProb + FProb / 2;
  1892. auto NewFalseProb = FProb / 2;
  1893. // Emit the LHS condition.
  1894. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1895. NewTrueProb, NewFalseProb, InvertCond);
  1896. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1897. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1898. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1899. // Emit the RHS condition into TmpBB.
  1900. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1901. Probs[0], Probs[1], InvertCond);
  1902. }
  1903. }
  1904. /// If the set of cases should be emitted as a series of branches, return true.
  1905. /// If we should emit this as a bunch of and/or'd together conditions, return
  1906. /// false.
  1907. bool
  1908. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1909. if (Cases.size() != 2) return true;
  1910. // If this is two comparisons of the same values or'd or and'd together, they
  1911. // will get folded into a single comparison, so don't emit two blocks.
  1912. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1913. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1914. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1915. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1916. return false;
  1917. }
  1918. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1919. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1920. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1921. Cases[0].CC == Cases[1].CC &&
  1922. isa<Constant>(Cases[0].CmpRHS) &&
  1923. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1924. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1925. return false;
  1926. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1927. return false;
  1928. }
  1929. return true;
  1930. }
  1931. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1932. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1933. // Update machine-CFG edges.
  1934. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1935. if (I.isUnconditional()) {
  1936. // Update machine-CFG edges.
  1937. BrMBB->addSuccessor(Succ0MBB);
  1938. // If this is not a fall-through branch or optimizations are switched off,
  1939. // emit the branch.
  1940. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1941. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1942. MVT::Other, getControlRoot(),
  1943. DAG.getBasicBlock(Succ0MBB)));
  1944. return;
  1945. }
  1946. // If this condition is one of the special cases we handle, do special stuff
  1947. // now.
  1948. const Value *CondVal = I.getCondition();
  1949. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1950. // If this is a series of conditions that are or'd or and'd together, emit
  1951. // this as a sequence of branches instead of setcc's with and/or operations.
  1952. // As long as jumps are not expensive, this should improve performance.
  1953. // For example, instead of something like:
  1954. // cmp A, B
  1955. // C = seteq
  1956. // cmp D, E
  1957. // F = setle
  1958. // or C, F
  1959. // jnz foo
  1960. // Emit:
  1961. // cmp A, B
  1962. // je foo
  1963. // cmp D, E
  1964. // jle foo
  1965. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1966. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1967. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1968. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1969. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1970. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1971. Opcode,
  1972. getEdgeProbability(BrMBB, Succ0MBB),
  1973. getEdgeProbability(BrMBB, Succ1MBB),
  1974. /*InvertCond=*/false);
  1975. // If the compares in later blocks need to use values not currently
  1976. // exported from this block, export them now. This block should always
  1977. // be the first entry.
  1978. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1979. // Allow some cases to be rejected.
  1980. if (ShouldEmitAsBranches(SwitchCases)) {
  1981. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1982. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1983. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1984. }
  1985. // Emit the branch for this block.
  1986. visitSwitchCase(SwitchCases[0], BrMBB);
  1987. SwitchCases.erase(SwitchCases.begin());
  1988. return;
  1989. }
  1990. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1991. // SwitchCases.
  1992. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1993. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1994. SwitchCases.clear();
  1995. }
  1996. }
  1997. // Create a CaseBlock record representing this branch.
  1998. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1999. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2000. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2001. // cond branch.
  2002. visitSwitchCase(CB, BrMBB);
  2003. }
  2004. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2005. /// the binary search tree resulting from lowering a switch instruction.
  2006. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2007. MachineBasicBlock *SwitchBB) {
  2008. SDValue Cond;
  2009. SDValue CondLHS = getValue(CB.CmpLHS);
  2010. SDLoc dl = CB.DL;
  2011. if (CB.CC == ISD::SETTRUE) {
  2012. // Branch or fall through to TrueBB.
  2013. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2014. SwitchBB->normalizeSuccProbs();
  2015. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2016. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2017. DAG.getBasicBlock(CB.TrueBB)));
  2018. }
  2019. return;
  2020. }
  2021. // Build the setcc now.
  2022. if (!CB.CmpMHS) {
  2023. // Fold "(X == true)" to X and "(X == false)" to !X to
  2024. // handle common cases produced by branch lowering.
  2025. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2026. CB.CC == ISD::SETEQ)
  2027. Cond = CondLHS;
  2028. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2029. CB.CC == ISD::SETEQ) {
  2030. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2031. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2032. } else
  2033. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  2034. } else {
  2035. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2036. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2037. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2038. SDValue CmpOp = getValue(CB.CmpMHS);
  2039. EVT VT = CmpOp.getValueType();
  2040. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2041. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2042. ISD::SETLE);
  2043. } else {
  2044. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2045. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2046. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2047. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2048. }
  2049. }
  2050. // Update successor info
  2051. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2052. // TrueBB and FalseBB are always different unless the incoming IR is
  2053. // degenerate. This only happens when running llc on weird IR.
  2054. if (CB.TrueBB != CB.FalseBB)
  2055. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2056. SwitchBB->normalizeSuccProbs();
  2057. // If the lhs block is the next block, invert the condition so that we can
  2058. // fall through to the lhs instead of the rhs block.
  2059. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2060. std::swap(CB.TrueBB, CB.FalseBB);
  2061. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2062. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2063. }
  2064. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2065. MVT::Other, getControlRoot(), Cond,
  2066. DAG.getBasicBlock(CB.TrueBB));
  2067. // Insert the false branch. Do this even if it's a fall through branch,
  2068. // this makes it easier to do DAG optimizations which require inverting
  2069. // the branch condition.
  2070. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2071. DAG.getBasicBlock(CB.FalseBB));
  2072. DAG.setRoot(BrCond);
  2073. }
  2074. /// visitJumpTable - Emit JumpTable node in the current MBB
  2075. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  2076. // Emit the code for the jump table
  2077. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2078. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2079. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2080. JT.Reg, PTy);
  2081. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2082. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2083. MVT::Other, Index.getValue(1),
  2084. Table, Index);
  2085. DAG.setRoot(BrJumpTable);
  2086. }
  2087. /// visitJumpTableHeader - This function emits necessary code to produce index
  2088. /// in the JumpTable from switch case.
  2089. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  2090. JumpTableHeader &JTH,
  2091. MachineBasicBlock *SwitchBB) {
  2092. SDLoc dl = getCurSDLoc();
  2093. // Subtract the lowest switch case value from the value being switched on.
  2094. SDValue SwitchOp = getValue(JTH.SValue);
  2095. EVT VT = SwitchOp.getValueType();
  2096. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2097. DAG.getConstant(JTH.First, dl, VT));
  2098. // The SDNode we just created, which holds the value being switched on minus
  2099. // the smallest case value, needs to be copied to a virtual register so it
  2100. // can be used as an index into the jump table in a subsequent basic block.
  2101. // This value may be smaller or larger than the target's pointer type, and
  2102. // therefore require extension or truncating.
  2103. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2104. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2105. unsigned JumpTableReg =
  2106. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2107. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2108. JumpTableReg, SwitchOp);
  2109. JT.Reg = JumpTableReg;
  2110. if (!JTH.OmitRangeCheck) {
  2111. // Emit the range check for the jump table, and branch to the default block
  2112. // for the switch statement if the value being switched on exceeds the
  2113. // largest case in the switch.
  2114. SDValue CMP = DAG.getSetCC(
  2115. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2116. Sub.getValueType()),
  2117. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2118. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2119. MVT::Other, CopyTo, CMP,
  2120. DAG.getBasicBlock(JT.Default));
  2121. // Avoid emitting unnecessary branches to the next block.
  2122. if (JT.MBB != NextBlock(SwitchBB))
  2123. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2124. DAG.getBasicBlock(JT.MBB));
  2125. DAG.setRoot(BrCond);
  2126. } else {
  2127. // Avoid emitting unnecessary branches to the next block.
  2128. if (JT.MBB != NextBlock(SwitchBB))
  2129. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2130. DAG.getBasicBlock(JT.MBB)));
  2131. else
  2132. DAG.setRoot(CopyTo);
  2133. }
  2134. }
  2135. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2136. /// variable if there exists one.
  2137. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2138. SDValue &Chain) {
  2139. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2140. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2141. MachineFunction &MF = DAG.getMachineFunction();
  2142. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2143. MachineSDNode *Node =
  2144. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2145. if (Global) {
  2146. MachinePointerInfo MPInfo(Global);
  2147. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2148. MachineMemOperand::MODereferenceable;
  2149. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2150. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  2151. DAG.setNodeMemRefs(Node, {MemRef});
  2152. }
  2153. return SDValue(Node, 0);
  2154. }
  2155. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2156. /// tail spliced into a stack protector check success bb.
  2157. ///
  2158. /// For a high level explanation of how this fits into the stack protector
  2159. /// generation see the comment on the declaration of class
  2160. /// StackProtectorDescriptor.
  2161. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2162. MachineBasicBlock *ParentBB) {
  2163. // First create the loads to the guard/stack slot for the comparison.
  2164. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2165. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2166. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2167. int FI = MFI.getStackProtectorIndex();
  2168. SDValue Guard;
  2169. SDLoc dl = getCurSDLoc();
  2170. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2171. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2172. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  2173. // Generate code to load the content of the guard slot.
  2174. SDValue GuardVal = DAG.getLoad(
  2175. PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2176. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2177. MachineMemOperand::MOVolatile);
  2178. if (TLI.useStackGuardXorFP())
  2179. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2180. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2181. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2182. // The target provides a guard check function to validate the guard value.
  2183. // Generate a call to that function with the content of the guard slot as
  2184. // argument.
  2185. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2186. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2187. TargetLowering::ArgListTy Args;
  2188. TargetLowering::ArgListEntry Entry;
  2189. Entry.Node = GuardVal;
  2190. Entry.Ty = FnTy->getParamType(0);
  2191. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2192. Entry.IsInReg = true;
  2193. Args.push_back(Entry);
  2194. TargetLowering::CallLoweringInfo CLI(DAG);
  2195. CLI.setDebugLoc(getCurSDLoc())
  2196. .setChain(DAG.getEntryNode())
  2197. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2198. getValue(GuardCheckFn), std::move(Args));
  2199. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2200. DAG.setRoot(Result.second);
  2201. return;
  2202. }
  2203. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2204. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2205. SDValue Chain = DAG.getEntryNode();
  2206. if (TLI.useLoadStackGuardNode()) {
  2207. Guard = getLoadStackGuard(DAG, dl, Chain);
  2208. } else {
  2209. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2210. SDValue GuardPtr = getValue(IRGuard);
  2211. Guard =
  2212. DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
  2213. Align, MachineMemOperand::MOVolatile);
  2214. }
  2215. // Perform the comparison via a subtract/getsetcc.
  2216. EVT VT = Guard.getValueType();
  2217. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2218. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2219. *DAG.getContext(),
  2220. Sub.getValueType()),
  2221. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2222. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2223. // branch to failure MBB.
  2224. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2225. MVT::Other, GuardVal.getOperand(0),
  2226. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2227. // Otherwise branch to success MBB.
  2228. SDValue Br = DAG.getNode(ISD::BR, dl,
  2229. MVT::Other, BrCond,
  2230. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2231. DAG.setRoot(Br);
  2232. }
  2233. /// Codegen the failure basic block for a stack protector check.
  2234. ///
  2235. /// A failure stack protector machine basic block consists simply of a call to
  2236. /// __stack_chk_fail().
  2237. ///
  2238. /// For a high level explanation of how this fits into the stack protector
  2239. /// generation see the comment on the declaration of class
  2240. /// StackProtectorDescriptor.
  2241. void
  2242. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2243. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2244. SDValue Chain =
  2245. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2246. None, false, getCurSDLoc(), false, false).second;
  2247. // On PS4, the "return address" must still be within the calling function,
  2248. // even if it's at the very end, so emit an explicit TRAP here.
  2249. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2250. if (TM.getTargetTriple().isPS4CPU())
  2251. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2252. DAG.setRoot(Chain);
  2253. }
  2254. /// visitBitTestHeader - This function emits necessary code to produce value
  2255. /// suitable for "bit tests"
  2256. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2257. MachineBasicBlock *SwitchBB) {
  2258. SDLoc dl = getCurSDLoc();
  2259. // Subtract the minimum value
  2260. SDValue SwitchOp = getValue(B.SValue);
  2261. EVT VT = SwitchOp.getValueType();
  2262. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2263. DAG.getConstant(B.First, dl, VT));
  2264. // Check range
  2265. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2266. SDValue RangeCmp = DAG.getSetCC(
  2267. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2268. Sub.getValueType()),
  2269. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2270. // Determine the type of the test operands.
  2271. bool UsePtrType = false;
  2272. if (!TLI.isTypeLegal(VT))
  2273. UsePtrType = true;
  2274. else {
  2275. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2276. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2277. // Switch table case range are encoded into series of masks.
  2278. // Just use pointer type, it's guaranteed to fit.
  2279. UsePtrType = true;
  2280. break;
  2281. }
  2282. }
  2283. if (UsePtrType) {
  2284. VT = TLI.getPointerTy(DAG.getDataLayout());
  2285. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2286. }
  2287. B.RegVT = VT.getSimpleVT();
  2288. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2289. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2290. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2291. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2292. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2293. SwitchBB->normalizeSuccProbs();
  2294. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2295. MVT::Other, CopyTo, RangeCmp,
  2296. DAG.getBasicBlock(B.Default));
  2297. // Avoid emitting unnecessary branches to the next block.
  2298. if (MBB != NextBlock(SwitchBB))
  2299. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2300. DAG.getBasicBlock(MBB));
  2301. DAG.setRoot(BrRange);
  2302. }
  2303. /// visitBitTestCase - this function produces one "bit test"
  2304. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2305. MachineBasicBlock* NextMBB,
  2306. BranchProbability BranchProbToNext,
  2307. unsigned Reg,
  2308. BitTestCase &B,
  2309. MachineBasicBlock *SwitchBB) {
  2310. SDLoc dl = getCurSDLoc();
  2311. MVT VT = BB.RegVT;
  2312. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2313. SDValue Cmp;
  2314. unsigned PopCount = countPopulation(B.Mask);
  2315. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2316. if (PopCount == 1) {
  2317. // Testing for a single bit; just compare the shift count with what it
  2318. // would need to be to shift a 1 bit in that position.
  2319. Cmp = DAG.getSetCC(
  2320. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2321. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2322. ISD::SETEQ);
  2323. } else if (PopCount == BB.Range) {
  2324. // There is only one zero bit in the range, test for it directly.
  2325. Cmp = DAG.getSetCC(
  2326. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2327. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2328. ISD::SETNE);
  2329. } else {
  2330. // Make desired shift
  2331. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2332. DAG.getConstant(1, dl, VT), ShiftOp);
  2333. // Emit bit tests and jumps
  2334. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2335. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2336. Cmp = DAG.getSetCC(
  2337. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2338. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2339. }
  2340. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2341. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2342. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2343. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2344. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2345. // one as they are relative probabilities (and thus work more like weights),
  2346. // and hence we need to normalize them to let the sum of them become one.
  2347. SwitchBB->normalizeSuccProbs();
  2348. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2349. MVT::Other, getControlRoot(),
  2350. Cmp, DAG.getBasicBlock(B.TargetBB));
  2351. // Avoid emitting unnecessary branches to the next block.
  2352. if (NextMBB != NextBlock(SwitchBB))
  2353. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2354. DAG.getBasicBlock(NextMBB));
  2355. DAG.setRoot(BrAnd);
  2356. }
  2357. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2358. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2359. // Retrieve successors. Look through artificial IR level blocks like
  2360. // catchswitch for successors.
  2361. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2362. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2363. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2364. // have to do anything here to lower funclet bundles.
  2365. assert(!I.hasOperandBundlesOtherThan(
  2366. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2367. "Cannot lower invokes with arbitrary operand bundles yet!");
  2368. const Value *Callee(I.getCalledValue());
  2369. const Function *Fn = dyn_cast<Function>(Callee);
  2370. if (isa<InlineAsm>(Callee))
  2371. visitInlineAsm(&I);
  2372. else if (Fn && Fn->isIntrinsic()) {
  2373. switch (Fn->getIntrinsicID()) {
  2374. default:
  2375. llvm_unreachable("Cannot invoke this intrinsic");
  2376. case Intrinsic::donothing:
  2377. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2378. break;
  2379. case Intrinsic::experimental_patchpoint_void:
  2380. case Intrinsic::experimental_patchpoint_i64:
  2381. visitPatchpoint(&I, EHPadBB);
  2382. break;
  2383. case Intrinsic::experimental_gc_statepoint:
  2384. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2385. break;
  2386. case Intrinsic::wasm_rethrow_in_catch: {
  2387. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2388. // special because it can be invoked, so we manually lower it to a DAG
  2389. // node here.
  2390. SmallVector<SDValue, 8> Ops;
  2391. Ops.push_back(getRoot()); // inchain
  2392. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2393. Ops.push_back(
  2394. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2395. TLI.getPointerTy(DAG.getDataLayout())));
  2396. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2397. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2398. break;
  2399. }
  2400. }
  2401. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2402. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2403. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2404. // intrinsic, and right now there are no plans to support other intrinsics
  2405. // with deopt state.
  2406. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2407. } else {
  2408. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2409. }
  2410. // If the value of the invoke is used outside of its defining block, make it
  2411. // available as a virtual register.
  2412. // We already took care of the exported value for the statepoint instruction
  2413. // during call to the LowerStatepoint.
  2414. if (!isStatepoint(I)) {
  2415. CopyToExportRegsIfNeeded(&I);
  2416. }
  2417. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2418. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2419. BranchProbability EHPadBBProb =
  2420. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2421. : BranchProbability::getZero();
  2422. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2423. // Update successor info.
  2424. addSuccessorWithProb(InvokeMBB, Return);
  2425. for (auto &UnwindDest : UnwindDests) {
  2426. UnwindDest.first->setIsEHPad();
  2427. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2428. }
  2429. InvokeMBB->normalizeSuccProbs();
  2430. // Drop into normal successor.
  2431. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2432. DAG.getBasicBlock(Return)));
  2433. }
  2434. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2435. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2436. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2437. // have to do anything here to lower funclet bundles.
  2438. assert(!I.hasOperandBundlesOtherThan(
  2439. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2440. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2441. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2442. "Only know how to handle inlineasm callbr");
  2443. visitInlineAsm(&I);
  2444. // Retrieve successors.
  2445. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2446. // Update successor info.
  2447. addSuccessorWithProb(CallBrMBB, Return);
  2448. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2449. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2450. addSuccessorWithProb(CallBrMBB, Target);
  2451. }
  2452. CallBrMBB->normalizeSuccProbs();
  2453. // Drop into default successor.
  2454. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2455. MVT::Other, getControlRoot(),
  2456. DAG.getBasicBlock(Return)));
  2457. }
  2458. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2459. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2460. }
  2461. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2462. assert(FuncInfo.MBB->isEHPad() &&
  2463. "Call to landingpad not in landing pad!");
  2464. // If there aren't registers to copy the values into (e.g., during SjLj
  2465. // exceptions), then don't bother to create these DAG nodes.
  2466. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2467. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2468. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2469. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2470. return;
  2471. // If landingpad's return type is token type, we don't create DAG nodes
  2472. // for its exception pointer and selector value. The extraction of exception
  2473. // pointer or selector value from token type landingpads is not currently
  2474. // supported.
  2475. if (LP.getType()->isTokenTy())
  2476. return;
  2477. SmallVector<EVT, 2> ValueVTs;
  2478. SDLoc dl = getCurSDLoc();
  2479. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2480. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2481. // Get the two live-in registers as SDValues. The physregs have already been
  2482. // copied into virtual registers.
  2483. SDValue Ops[2];
  2484. if (FuncInfo.ExceptionPointerVirtReg) {
  2485. Ops[0] = DAG.getZExtOrTrunc(
  2486. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2487. FuncInfo.ExceptionPointerVirtReg,
  2488. TLI.getPointerTy(DAG.getDataLayout())),
  2489. dl, ValueVTs[0]);
  2490. } else {
  2491. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2492. }
  2493. Ops[1] = DAG.getZExtOrTrunc(
  2494. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2495. FuncInfo.ExceptionSelectorVirtReg,
  2496. TLI.getPointerTy(DAG.getDataLayout())),
  2497. dl, ValueVTs[1]);
  2498. // Merge into one.
  2499. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2500. DAG.getVTList(ValueVTs), Ops);
  2501. setValue(&LP, Res);
  2502. }
  2503. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  2504. #ifndef NDEBUG
  2505. for (const CaseCluster &CC : Clusters)
  2506. assert(CC.Low == CC.High && "Input clusters must be single-case");
  2507. #endif
  2508. llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
  2509. return a.Low->getValue().slt(b.Low->getValue());
  2510. });
  2511. // Merge adjacent clusters with the same destination.
  2512. const unsigned N = Clusters.size();
  2513. unsigned DstIndex = 0;
  2514. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  2515. CaseCluster &CC = Clusters[SrcIndex];
  2516. const ConstantInt *CaseVal = CC.Low;
  2517. MachineBasicBlock *Succ = CC.MBB;
  2518. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  2519. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  2520. // If this case has the same successor and is a neighbour, merge it into
  2521. // the previous cluster.
  2522. Clusters[DstIndex - 1].High = CaseVal;
  2523. Clusters[DstIndex - 1].Prob += CC.Prob;
  2524. } else {
  2525. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  2526. sizeof(Clusters[SrcIndex]));
  2527. }
  2528. }
  2529. Clusters.resize(DstIndex);
  2530. }
  2531. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2532. MachineBasicBlock *Last) {
  2533. // Update JTCases.
  2534. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2535. if (JTCases[i].first.HeaderBB == First)
  2536. JTCases[i].first.HeaderBB = Last;
  2537. // Update BitTestCases.
  2538. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2539. if (BitTestCases[i].Parent == First)
  2540. BitTestCases[i].Parent = Last;
  2541. }
  2542. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2543. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2544. // Update machine-CFG edges with unique successors.
  2545. SmallSet<BasicBlock*, 32> Done;
  2546. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2547. BasicBlock *BB = I.getSuccessor(i);
  2548. bool Inserted = Done.insert(BB).second;
  2549. if (!Inserted)
  2550. continue;
  2551. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2552. addSuccessorWithProb(IndirectBrMBB, Succ);
  2553. }
  2554. IndirectBrMBB->normalizeSuccProbs();
  2555. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2556. MVT::Other, getControlRoot(),
  2557. getValue(I.getAddress())));
  2558. }
  2559. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2560. if (!DAG.getTarget().Options.TrapUnreachable)
  2561. return;
  2562. // We may be able to ignore unreachable behind a noreturn call.
  2563. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2564. const BasicBlock &BB = *I.getParent();
  2565. if (&I != &BB.front()) {
  2566. BasicBlock::const_iterator PredI =
  2567. std::prev(BasicBlock::const_iterator(&I));
  2568. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2569. if (Call->doesNotReturn())
  2570. return;
  2571. }
  2572. }
  2573. }
  2574. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2575. }
  2576. void SelectionDAGBuilder::visitFSub(const User &I) {
  2577. // -0.0 - X --> fneg
  2578. Type *Ty = I.getType();
  2579. if (isa<Constant>(I.getOperand(0)) &&
  2580. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2581. SDValue Op2 = getValue(I.getOperand(1));
  2582. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2583. Op2.getValueType(), Op2));
  2584. return;
  2585. }
  2586. visitBinary(I, ISD::FSUB);
  2587. }
  2588. /// Checks if the given instruction performs a vector reduction, in which case
  2589. /// we have the freedom to alter the elements in the result as long as the
  2590. /// reduction of them stays unchanged.
  2591. static bool isVectorReductionOp(const User *I) {
  2592. const Instruction *Inst = dyn_cast<Instruction>(I);
  2593. if (!Inst || !Inst->getType()->isVectorTy())
  2594. return false;
  2595. auto OpCode = Inst->getOpcode();
  2596. switch (OpCode) {
  2597. case Instruction::Add:
  2598. case Instruction::Mul:
  2599. case Instruction::And:
  2600. case Instruction::Or:
  2601. case Instruction::Xor:
  2602. break;
  2603. case Instruction::FAdd:
  2604. case Instruction::FMul:
  2605. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2606. if (FPOp->getFastMathFlags().isFast())
  2607. break;
  2608. LLVM_FALLTHROUGH;
  2609. default:
  2610. return false;
  2611. }
  2612. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2613. // Ensure the reduction size is a power of 2.
  2614. if (!isPowerOf2_32(ElemNum))
  2615. return false;
  2616. unsigned ElemNumToReduce = ElemNum;
  2617. // Do DFS search on the def-use chain from the given instruction. We only
  2618. // allow four kinds of operations during the search until we reach the
  2619. // instruction that extracts the first element from the vector:
  2620. //
  2621. // 1. The reduction operation of the same opcode as the given instruction.
  2622. //
  2623. // 2. PHI node.
  2624. //
  2625. // 3. ShuffleVector instruction together with a reduction operation that
  2626. // does a partial reduction.
  2627. //
  2628. // 4. ExtractElement that extracts the first element from the vector, and we
  2629. // stop searching the def-use chain here.
  2630. //
  2631. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2632. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2633. // a reduction operation if we meet any other instructions other than those
  2634. // listed above.
  2635. SmallVector<const User *, 16> UsersToVisit{Inst};
  2636. SmallPtrSet<const User *, 16> Visited;
  2637. bool ReduxExtracted = false;
  2638. while (!UsersToVisit.empty()) {
  2639. auto User = UsersToVisit.back();
  2640. UsersToVisit.pop_back();
  2641. if (!Visited.insert(User).second)
  2642. continue;
  2643. for (const auto &U : User->users()) {
  2644. auto Inst = dyn_cast<Instruction>(U);
  2645. if (!Inst)
  2646. return false;
  2647. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2648. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2649. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2650. return false;
  2651. UsersToVisit.push_back(U);
  2652. } else if (const ShuffleVectorInst *ShufInst =
  2653. dyn_cast<ShuffleVectorInst>(U)) {
  2654. // Detect the following pattern: A ShuffleVector instruction together
  2655. // with a reduction that do partial reduction on the first and second
  2656. // ElemNumToReduce / 2 elements, and store the result in
  2657. // ElemNumToReduce / 2 elements in another vector.
  2658. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2659. if (ResultElements < ElemNum)
  2660. return false;
  2661. if (ElemNumToReduce == 1)
  2662. return false;
  2663. if (!isa<UndefValue>(U->getOperand(1)))
  2664. return false;
  2665. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2666. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2667. return false;
  2668. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2669. if (ShufInst->getMaskValue(i) != -1)
  2670. return false;
  2671. // There is only one user of this ShuffleVector instruction, which
  2672. // must be a reduction operation.
  2673. if (!U->hasOneUse())
  2674. return false;
  2675. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2676. if (!U2 || U2->getOpcode() != OpCode)
  2677. return false;
  2678. // Check operands of the reduction operation.
  2679. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2680. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2681. UsersToVisit.push_back(U2);
  2682. ElemNumToReduce /= 2;
  2683. } else
  2684. return false;
  2685. } else if (isa<ExtractElementInst>(U)) {
  2686. // At this moment we should have reduced all elements in the vector.
  2687. if (ElemNumToReduce != 1)
  2688. return false;
  2689. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2690. if (!Val || !Val->isZero())
  2691. return false;
  2692. ReduxExtracted = true;
  2693. } else
  2694. return false;
  2695. }
  2696. }
  2697. return ReduxExtracted;
  2698. }
  2699. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2700. SDNodeFlags Flags;
  2701. SDValue Op = getValue(I.getOperand(0));
  2702. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2703. Op, Flags);
  2704. setValue(&I, UnNodeValue);
  2705. }
  2706. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2707. SDNodeFlags Flags;
  2708. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2709. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2710. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2711. }
  2712. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2713. Flags.setExact(ExactOp->isExact());
  2714. }
  2715. if (isVectorReductionOp(&I)) {
  2716. Flags.setVectorReduction(true);
  2717. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2718. }
  2719. SDValue Op1 = getValue(I.getOperand(0));
  2720. SDValue Op2 = getValue(I.getOperand(1));
  2721. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2722. Op1, Op2, Flags);
  2723. setValue(&I, BinNodeValue);
  2724. }
  2725. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2726. SDValue Op1 = getValue(I.getOperand(0));
  2727. SDValue Op2 = getValue(I.getOperand(1));
  2728. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2729. Op1.getValueType(), DAG.getDataLayout());
  2730. // Coerce the shift amount to the right type if we can.
  2731. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2732. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2733. unsigned Op2Size = Op2.getValueSizeInBits();
  2734. SDLoc DL = getCurSDLoc();
  2735. // If the operand is smaller than the shift count type, promote it.
  2736. if (ShiftSize > Op2Size)
  2737. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2738. // If the operand is larger than the shift count type but the shift
  2739. // count type has enough bits to represent any shift value, truncate
  2740. // it now. This is a common case and it exposes the truncate to
  2741. // optimization early.
  2742. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2743. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2744. // Otherwise we'll need to temporarily settle for some other convenient
  2745. // type. Type legalization will make adjustments once the shiftee is split.
  2746. else
  2747. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2748. }
  2749. bool nuw = false;
  2750. bool nsw = false;
  2751. bool exact = false;
  2752. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2753. if (const OverflowingBinaryOperator *OFBinOp =
  2754. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2755. nuw = OFBinOp->hasNoUnsignedWrap();
  2756. nsw = OFBinOp->hasNoSignedWrap();
  2757. }
  2758. if (const PossiblyExactOperator *ExactOp =
  2759. dyn_cast<const PossiblyExactOperator>(&I))
  2760. exact = ExactOp->isExact();
  2761. }
  2762. SDNodeFlags Flags;
  2763. Flags.setExact(exact);
  2764. Flags.setNoSignedWrap(nsw);
  2765. Flags.setNoUnsignedWrap(nuw);
  2766. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2767. Flags);
  2768. setValue(&I, Res);
  2769. }
  2770. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2771. SDValue Op1 = getValue(I.getOperand(0));
  2772. SDValue Op2 = getValue(I.getOperand(1));
  2773. SDNodeFlags Flags;
  2774. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2775. cast<PossiblyExactOperator>(&I)->isExact());
  2776. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2777. Op2, Flags));
  2778. }
  2779. void SelectionDAGBuilder::visitICmp(const User &I) {
  2780. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2781. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2782. predicate = IC->getPredicate();
  2783. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2784. predicate = ICmpInst::Predicate(IC->getPredicate());
  2785. SDValue Op1 = getValue(I.getOperand(0));
  2786. SDValue Op2 = getValue(I.getOperand(1));
  2787. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2788. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2789. I.getType());
  2790. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2791. }
  2792. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2793. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2794. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2795. predicate = FC->getPredicate();
  2796. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2797. predicate = FCmpInst::Predicate(FC->getPredicate());
  2798. SDValue Op1 = getValue(I.getOperand(0));
  2799. SDValue Op2 = getValue(I.getOperand(1));
  2800. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2801. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2802. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2803. Condition = getFCmpCodeWithoutNaN(Condition);
  2804. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2805. I.getType());
  2806. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2807. }
  2808. // Check if the condition of the select has one use or two users that are both
  2809. // selects with the same condition.
  2810. static bool hasOnlySelectUsers(const Value *Cond) {
  2811. return llvm::all_of(Cond->users(), [](const Value *V) {
  2812. return isa<SelectInst>(V);
  2813. });
  2814. }
  2815. void SelectionDAGBuilder::visitSelect(const User &I) {
  2816. SmallVector<EVT, 4> ValueVTs;
  2817. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2818. ValueVTs);
  2819. unsigned NumValues = ValueVTs.size();
  2820. if (NumValues == 0) return;
  2821. SmallVector<SDValue, 4> Values(NumValues);
  2822. SDValue Cond = getValue(I.getOperand(0));
  2823. SDValue LHSVal = getValue(I.getOperand(1));
  2824. SDValue RHSVal = getValue(I.getOperand(2));
  2825. auto BaseOps = {Cond};
  2826. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2827. ISD::VSELECT : ISD::SELECT;
  2828. bool IsUnaryAbs = false;
  2829. // Min/max matching is only viable if all output VTs are the same.
  2830. if (is_splat(ValueVTs)) {
  2831. EVT VT = ValueVTs[0];
  2832. LLVMContext &Ctx = *DAG.getContext();
  2833. auto &TLI = DAG.getTargetLoweringInfo();
  2834. // We care about the legality of the operation after it has been type
  2835. // legalized.
  2836. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2837. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2838. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2839. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2840. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2841. // min/max is legal on the scalar type.
  2842. bool UseScalarMinMax = VT.isVector() &&
  2843. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2844. Value *LHS, *RHS;
  2845. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2846. ISD::NodeType Opc = ISD::DELETED_NODE;
  2847. switch (SPR.Flavor) {
  2848. case SPF_UMAX: Opc = ISD::UMAX; break;
  2849. case SPF_UMIN: Opc = ISD::UMIN; break;
  2850. case SPF_SMAX: Opc = ISD::SMAX; break;
  2851. case SPF_SMIN: Opc = ISD::SMIN; break;
  2852. case SPF_FMINNUM:
  2853. switch (SPR.NaNBehavior) {
  2854. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2855. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2856. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2857. case SPNB_RETURNS_ANY: {
  2858. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2859. Opc = ISD::FMINNUM;
  2860. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2861. Opc = ISD::FMINIMUM;
  2862. else if (UseScalarMinMax)
  2863. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2864. ISD::FMINNUM : ISD::FMINIMUM;
  2865. break;
  2866. }
  2867. }
  2868. break;
  2869. case SPF_FMAXNUM:
  2870. switch (SPR.NaNBehavior) {
  2871. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2872. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2873. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2874. case SPNB_RETURNS_ANY:
  2875. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2876. Opc = ISD::FMAXNUM;
  2877. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2878. Opc = ISD::FMAXIMUM;
  2879. else if (UseScalarMinMax)
  2880. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2881. ISD::FMAXNUM : ISD::FMAXIMUM;
  2882. break;
  2883. }
  2884. break;
  2885. case SPF_ABS:
  2886. IsUnaryAbs = true;
  2887. Opc = ISD::ABS;
  2888. break;
  2889. case SPF_NABS:
  2890. // TODO: we need to produce sub(0, abs(X)).
  2891. default: break;
  2892. }
  2893. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2894. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2895. (UseScalarMinMax &&
  2896. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2897. // If the underlying comparison instruction is used by any other
  2898. // instruction, the consumed instructions won't be destroyed, so it is
  2899. // not profitable to convert to a min/max.
  2900. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2901. OpCode = Opc;
  2902. LHSVal = getValue(LHS);
  2903. RHSVal = getValue(RHS);
  2904. BaseOps = {};
  2905. }
  2906. if (IsUnaryAbs) {
  2907. OpCode = Opc;
  2908. LHSVal = getValue(LHS);
  2909. BaseOps = {};
  2910. }
  2911. }
  2912. if (IsUnaryAbs) {
  2913. for (unsigned i = 0; i != NumValues; ++i) {
  2914. Values[i] =
  2915. DAG.getNode(OpCode, getCurSDLoc(),
  2916. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2917. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2918. }
  2919. } else {
  2920. for (unsigned i = 0; i != NumValues; ++i) {
  2921. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2922. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2923. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2924. Values[i] = DAG.getNode(
  2925. OpCode, getCurSDLoc(),
  2926. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2927. }
  2928. }
  2929. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2930. DAG.getVTList(ValueVTs), Values));
  2931. }
  2932. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2933. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2934. SDValue N = getValue(I.getOperand(0));
  2935. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2936. I.getType());
  2937. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2938. }
  2939. void SelectionDAGBuilder::visitZExt(const User &I) {
  2940. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2941. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2942. SDValue N = getValue(I.getOperand(0));
  2943. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2944. I.getType());
  2945. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2946. }
  2947. void SelectionDAGBuilder::visitSExt(const User &I) {
  2948. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2949. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2950. SDValue N = getValue(I.getOperand(0));
  2951. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2952. I.getType());
  2953. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2954. }
  2955. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2956. // FPTrunc is never a no-op cast, no need to check
  2957. SDValue N = getValue(I.getOperand(0));
  2958. SDLoc dl = getCurSDLoc();
  2959. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2960. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2961. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2962. DAG.getTargetConstant(
  2963. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2964. }
  2965. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2966. // FPExt is never a no-op cast, no need to check
  2967. SDValue N = getValue(I.getOperand(0));
  2968. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2969. I.getType());
  2970. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2971. }
  2972. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2973. // FPToUI is never a no-op cast, no need to check
  2974. SDValue N = getValue(I.getOperand(0));
  2975. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2976. I.getType());
  2977. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  2978. }
  2979. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2980. // FPToSI is never a no-op cast, no need to check
  2981. SDValue N = getValue(I.getOperand(0));
  2982. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2983. I.getType());
  2984. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  2985. }
  2986. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2987. // UIToFP is never a no-op cast, no need to check
  2988. SDValue N = getValue(I.getOperand(0));
  2989. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2990. I.getType());
  2991. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  2992. }
  2993. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  2994. // SIToFP is never a no-op cast, no need to check
  2995. SDValue N = getValue(I.getOperand(0));
  2996. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2997. I.getType());
  2998. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  2999. }
  3000. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3001. // What to do depends on the size of the integer and the size of the pointer.
  3002. // We can either truncate, zero extend, or no-op, accordingly.
  3003. SDValue N = getValue(I.getOperand(0));
  3004. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3005. I.getType());
  3006. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  3007. }
  3008. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3009. // What to do depends on the size of the integer and the size of the pointer.
  3010. // We can either truncate, zero extend, or no-op, accordingly.
  3011. SDValue N = getValue(I.getOperand(0));
  3012. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3013. I.getType());
  3014. setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
  3015. }
  3016. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3017. SDValue N = getValue(I.getOperand(0));
  3018. SDLoc dl = getCurSDLoc();
  3019. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3020. I.getType());
  3021. // BitCast assures us that source and destination are the same size so this is
  3022. // either a BITCAST or a no-op.
  3023. if (DestVT != N.getValueType())
  3024. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3025. DestVT, N)); // convert types.
  3026. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3027. // might fold any kind of constant expression to an integer constant and that
  3028. // is not what we are looking for. Only recognize a bitcast of a genuine
  3029. // constant integer as an opaque constant.
  3030. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3031. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3032. /*isOpaque*/true));
  3033. else
  3034. setValue(&I, N); // noop cast.
  3035. }
  3036. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3037. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3038. const Value *SV = I.getOperand(0);
  3039. SDValue N = getValue(SV);
  3040. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3041. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3042. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3043. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3044. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3045. setValue(&I, N);
  3046. }
  3047. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3048. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3049. SDValue InVec = getValue(I.getOperand(0));
  3050. SDValue InVal = getValue(I.getOperand(1));
  3051. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3052. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3053. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3054. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3055. InVec, InVal, InIdx));
  3056. }
  3057. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3058. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3059. SDValue InVec = getValue(I.getOperand(0));
  3060. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3061. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3062. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3063. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3064. InVec, InIdx));
  3065. }
  3066. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3067. SDValue Src1 = getValue(I.getOperand(0));
  3068. SDValue Src2 = getValue(I.getOperand(1));
  3069. SDLoc DL = getCurSDLoc();
  3070. SmallVector<int, 8> Mask;
  3071. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3072. unsigned MaskNumElts = Mask.size();
  3073. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3074. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3075. EVT SrcVT = Src1.getValueType();
  3076. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3077. if (SrcNumElts == MaskNumElts) {
  3078. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3079. return;
  3080. }
  3081. // Normalize the shuffle vector since mask and vector length don't match.
  3082. if (SrcNumElts < MaskNumElts) {
  3083. // Mask is longer than the source vectors. We can use concatenate vector to
  3084. // make the mask and vectors lengths match.
  3085. if (MaskNumElts % SrcNumElts == 0) {
  3086. // Mask length is a multiple of the source vector length.
  3087. // Check if the shuffle is some kind of concatenation of the input
  3088. // vectors.
  3089. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3090. bool IsConcat = true;
  3091. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3092. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3093. int Idx = Mask[i];
  3094. if (Idx < 0)
  3095. continue;
  3096. // Ensure the indices in each SrcVT sized piece are sequential and that
  3097. // the same source is used for the whole piece.
  3098. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3099. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3100. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3101. IsConcat = false;
  3102. break;
  3103. }
  3104. // Remember which source this index came from.
  3105. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3106. }
  3107. // The shuffle is concatenating multiple vectors together. Just emit
  3108. // a CONCAT_VECTORS operation.
  3109. if (IsConcat) {
  3110. SmallVector<SDValue, 8> ConcatOps;
  3111. for (auto Src : ConcatSrcs) {
  3112. if (Src < 0)
  3113. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3114. else if (Src == 0)
  3115. ConcatOps.push_back(Src1);
  3116. else
  3117. ConcatOps.push_back(Src2);
  3118. }
  3119. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3120. return;
  3121. }
  3122. }
  3123. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3124. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3125. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3126. PaddedMaskNumElts);
  3127. // Pad both vectors with undefs to make them the same length as the mask.
  3128. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3129. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3130. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3131. MOps1[0] = Src1;
  3132. MOps2[0] = Src2;
  3133. Src1 = Src1.isUndef()
  3134. ? DAG.getUNDEF(PaddedVT)
  3135. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3136. Src2 = Src2.isUndef()
  3137. ? DAG.getUNDEF(PaddedVT)
  3138. : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3139. // Readjust mask for new input vector length.
  3140. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3141. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3142. int Idx = Mask[i];
  3143. if (Idx >= (int)SrcNumElts)
  3144. Idx -= SrcNumElts - PaddedMaskNumElts;
  3145. MappedOps[i] = Idx;
  3146. }
  3147. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3148. // If the concatenated vector was padded, extract a subvector with the
  3149. // correct number of elements.
  3150. if (MaskNumElts != PaddedMaskNumElts)
  3151. Result = DAG.getNode(
  3152. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3153. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3154. setValue(&I, Result);
  3155. return;
  3156. }
  3157. if (SrcNumElts > MaskNumElts) {
  3158. // Analyze the access pattern of the vector to see if we can extract
  3159. // two subvectors and do the shuffle.
  3160. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3161. bool CanExtract = true;
  3162. for (int Idx : Mask) {
  3163. unsigned Input = 0;
  3164. if (Idx < 0)
  3165. continue;
  3166. if (Idx >= (int)SrcNumElts) {
  3167. Input = 1;
  3168. Idx -= SrcNumElts;
  3169. }
  3170. // If all the indices come from the same MaskNumElts sized portion of
  3171. // the sources we can use extract. Also make sure the extract wouldn't
  3172. // extract past the end of the source.
  3173. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3174. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3175. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3176. CanExtract = false;
  3177. // Make sure we always update StartIdx as we use it to track if all
  3178. // elements are undef.
  3179. StartIdx[Input] = NewStartIdx;
  3180. }
  3181. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3182. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3183. return;
  3184. }
  3185. if (CanExtract) {
  3186. // Extract appropriate subvector and generate a vector shuffle
  3187. for (unsigned Input = 0; Input < 2; ++Input) {
  3188. SDValue &Src = Input == 0 ? Src1 : Src2;
  3189. if (StartIdx[Input] < 0)
  3190. Src = DAG.getUNDEF(VT);
  3191. else {
  3192. Src = DAG.getNode(
  3193. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3194. DAG.getConstant(StartIdx[Input], DL,
  3195. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3196. }
  3197. }
  3198. // Calculate new mask.
  3199. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3200. for (int &Idx : MappedOps) {
  3201. if (Idx >= (int)SrcNumElts)
  3202. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3203. else if (Idx >= 0)
  3204. Idx -= StartIdx[0];
  3205. }
  3206. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3207. return;
  3208. }
  3209. }
  3210. // We can't use either concat vectors or extract subvectors so fall back to
  3211. // replacing the shuffle with extract and build vector.
  3212. // to insert and build vector.
  3213. EVT EltVT = VT.getVectorElementType();
  3214. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3215. SmallVector<SDValue,8> Ops;
  3216. for (int Idx : Mask) {
  3217. SDValue Res;
  3218. if (Idx < 0) {
  3219. Res = DAG.getUNDEF(EltVT);
  3220. } else {
  3221. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3222. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3223. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3224. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3225. }
  3226. Ops.push_back(Res);
  3227. }
  3228. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3229. }
  3230. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3231. ArrayRef<unsigned> Indices;
  3232. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3233. Indices = IV->getIndices();
  3234. else
  3235. Indices = cast<ConstantExpr>(&I)->getIndices();
  3236. const Value *Op0 = I.getOperand(0);
  3237. const Value *Op1 = I.getOperand(1);
  3238. Type *AggTy = I.getType();
  3239. Type *ValTy = Op1->getType();
  3240. bool IntoUndef = isa<UndefValue>(Op0);
  3241. bool FromUndef = isa<UndefValue>(Op1);
  3242. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3243. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3244. SmallVector<EVT, 4> AggValueVTs;
  3245. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3246. SmallVector<EVT, 4> ValValueVTs;
  3247. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3248. unsigned NumAggValues = AggValueVTs.size();
  3249. unsigned NumValValues = ValValueVTs.size();
  3250. SmallVector<SDValue, 4> Values(NumAggValues);
  3251. // Ignore an insertvalue that produces an empty object
  3252. if (!NumAggValues) {
  3253. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3254. return;
  3255. }
  3256. SDValue Agg = getValue(Op0);
  3257. unsigned i = 0;
  3258. // Copy the beginning value(s) from the original aggregate.
  3259. for (; i != LinearIndex; ++i)
  3260. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3261. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3262. // Copy values from the inserted value(s).
  3263. if (NumValValues) {
  3264. SDValue Val = getValue(Op1);
  3265. for (; i != LinearIndex + NumValValues; ++i)
  3266. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3267. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3268. }
  3269. // Copy remaining value(s) from the original aggregate.
  3270. for (; i != NumAggValues; ++i)
  3271. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3272. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3273. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3274. DAG.getVTList(AggValueVTs), Values));
  3275. }
  3276. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3277. ArrayRef<unsigned> Indices;
  3278. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3279. Indices = EV->getIndices();
  3280. else
  3281. Indices = cast<ConstantExpr>(&I)->getIndices();
  3282. const Value *Op0 = I.getOperand(0);
  3283. Type *AggTy = Op0->getType();
  3284. Type *ValTy = I.getType();
  3285. bool OutOfUndef = isa<UndefValue>(Op0);
  3286. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3287. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3288. SmallVector<EVT, 4> ValValueVTs;
  3289. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3290. unsigned NumValValues = ValValueVTs.size();
  3291. // Ignore a extractvalue that produces an empty object
  3292. if (!NumValValues) {
  3293. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3294. return;
  3295. }
  3296. SmallVector<SDValue, 4> Values(NumValValues);
  3297. SDValue Agg = getValue(Op0);
  3298. // Copy out the selected value(s).
  3299. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3300. Values[i - LinearIndex] =
  3301. OutOfUndef ?
  3302. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3303. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3304. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3305. DAG.getVTList(ValValueVTs), Values));
  3306. }
  3307. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3308. Value *Op0 = I.getOperand(0);
  3309. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3310. // element which holds a pointer.
  3311. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3312. SDValue N = getValue(Op0);
  3313. SDLoc dl = getCurSDLoc();
  3314. // Normalize Vector GEP - all scalar operands should be converted to the
  3315. // splat vector.
  3316. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3317. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  3318. if (VectorWidth && !N.getValueType().isVector()) {
  3319. LLVMContext &Context = *DAG.getContext();
  3320. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3321. N = DAG.getSplatBuildVector(VT, dl, N);
  3322. }
  3323. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3324. GTI != E; ++GTI) {
  3325. const Value *Idx = GTI.getOperand();
  3326. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3327. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3328. if (Field) {
  3329. // N = N + Offset
  3330. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3331. // In an inbounds GEP with an offset that is nonnegative even when
  3332. // interpreted as signed, assume there is no unsigned overflow.
  3333. SDNodeFlags Flags;
  3334. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3335. Flags.setNoUnsignedWrap(true);
  3336. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3337. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3338. }
  3339. } else {
  3340. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3341. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3342. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3343. // If this is a scalar constant or a splat vector of constants,
  3344. // handle it quickly.
  3345. const auto *CI = dyn_cast<ConstantInt>(Idx);
  3346. if (!CI && isa<ConstantDataVector>(Idx) &&
  3347. cast<ConstantDataVector>(Idx)->getSplatValue())
  3348. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  3349. if (CI) {
  3350. if (CI->isZero())
  3351. continue;
  3352. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3353. LLVMContext &Context = *DAG.getContext();
  3354. SDValue OffsVal = VectorWidth ?
  3355. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3356. DAG.getConstant(Offs, dl, IdxTy);
  3357. // In an inbouds GEP with an offset that is nonnegative even when
  3358. // interpreted as signed, assume there is no unsigned overflow.
  3359. SDNodeFlags Flags;
  3360. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3361. Flags.setNoUnsignedWrap(true);
  3362. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3363. continue;
  3364. }
  3365. // N = N + Idx * ElementSize;
  3366. SDValue IdxN = getValue(Idx);
  3367. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3368. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3369. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3370. }
  3371. // If the index is smaller or larger than intptr_t, truncate or extend
  3372. // it.
  3373. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3374. // If this is a multiply by a power of two, turn it into a shl
  3375. // immediately. This is a very common case.
  3376. if (ElementSize != 1) {
  3377. if (ElementSize.isPowerOf2()) {
  3378. unsigned Amt = ElementSize.logBase2();
  3379. IdxN = DAG.getNode(ISD::SHL, dl,
  3380. N.getValueType(), IdxN,
  3381. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3382. } else {
  3383. SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
  3384. IdxN = DAG.getNode(ISD::MUL, dl,
  3385. N.getValueType(), IdxN, Scale);
  3386. }
  3387. }
  3388. N = DAG.getNode(ISD::ADD, dl,
  3389. N.getValueType(), N, IdxN);
  3390. }
  3391. }
  3392. setValue(&I, N);
  3393. }
  3394. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3395. // If this is a fixed sized alloca in the entry block of the function,
  3396. // allocate it statically on the stack.
  3397. if (FuncInfo.StaticAllocaMap.count(&I))
  3398. return; // getValue will auto-populate this.
  3399. SDLoc dl = getCurSDLoc();
  3400. Type *Ty = I.getAllocatedType();
  3401. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3402. auto &DL = DAG.getDataLayout();
  3403. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3404. unsigned Align =
  3405. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3406. SDValue AllocSize = getValue(I.getArraySize());
  3407. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3408. if (AllocSize.getValueType() != IntPtr)
  3409. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3410. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3411. AllocSize,
  3412. DAG.getConstant(TySize, dl, IntPtr));
  3413. // Handle alignment. If the requested alignment is less than or equal to
  3414. // the stack alignment, ignore it. If the size is greater than or equal to
  3415. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3416. unsigned StackAlign =
  3417. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3418. if (Align <= StackAlign)
  3419. Align = 0;
  3420. // Round the size of the allocation up to the stack alignment size
  3421. // by add SA-1 to the size. This doesn't overflow because we're computing
  3422. // an address inside an alloca.
  3423. SDNodeFlags Flags;
  3424. Flags.setNoUnsignedWrap(true);
  3425. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3426. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3427. // Mask out the low bits for alignment purposes.
  3428. AllocSize =
  3429. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3430. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3431. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3432. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3433. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3434. setValue(&I, DSA);
  3435. DAG.setRoot(DSA.getValue(1));
  3436. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3437. }
  3438. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3439. if (I.isAtomic())
  3440. return visitAtomicLoad(I);
  3441. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3442. const Value *SV = I.getOperand(0);
  3443. if (TLI.supportSwiftError()) {
  3444. // Swifterror values can come from either a function parameter with
  3445. // swifterror attribute or an alloca with swifterror attribute.
  3446. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3447. if (Arg->hasSwiftErrorAttr())
  3448. return visitLoadFromSwiftError(I);
  3449. }
  3450. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3451. if (Alloca->isSwiftError())
  3452. return visitLoadFromSwiftError(I);
  3453. }
  3454. }
  3455. SDValue Ptr = getValue(SV);
  3456. Type *Ty = I.getType();
  3457. bool isVolatile = I.isVolatile();
  3458. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3459. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3460. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3461. unsigned Alignment = I.getAlignment();
  3462. AAMDNodes AAInfo;
  3463. I.getAAMetadata(AAInfo);
  3464. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3465. SmallVector<EVT, 4> ValueVTs;
  3466. SmallVector<uint64_t, 4> Offsets;
  3467. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
  3468. unsigned NumValues = ValueVTs.size();
  3469. if (NumValues == 0)
  3470. return;
  3471. SDValue Root;
  3472. bool ConstantMemory = false;
  3473. if (isVolatile || NumValues > MaxParallelChains)
  3474. // Serialize volatile loads with other side effects.
  3475. Root = getRoot();
  3476. else if (AA &&
  3477. AA->pointsToConstantMemory(MemoryLocation(
  3478. SV,
  3479. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3480. AAInfo))) {
  3481. // Do not serialize (non-volatile) loads of constant memory with anything.
  3482. Root = DAG.getEntryNode();
  3483. ConstantMemory = true;
  3484. } else {
  3485. // Do not serialize non-volatile loads against each other.
  3486. Root = DAG.getRoot();
  3487. }
  3488. SDLoc dl = getCurSDLoc();
  3489. if (isVolatile)
  3490. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3491. // An aggregate load cannot wrap around the address space, so offsets to its
  3492. // parts don't wrap either.
  3493. SDNodeFlags Flags;
  3494. Flags.setNoUnsignedWrap(true);
  3495. SmallVector<SDValue, 4> Values(NumValues);
  3496. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3497. EVT PtrVT = Ptr.getValueType();
  3498. unsigned ChainI = 0;
  3499. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3500. // Serializing loads here may result in excessive register pressure, and
  3501. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3502. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3503. // they are side-effect free or do not alias. The optimizer should really
  3504. // avoid this case by converting large object/array copies to llvm.memcpy
  3505. // (MaxParallelChains should always remain as failsafe).
  3506. if (ChainI == MaxParallelChains) {
  3507. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3508. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3509. makeArrayRef(Chains.data(), ChainI));
  3510. Root = Chain;
  3511. ChainI = 0;
  3512. }
  3513. SDValue A = DAG.getNode(ISD::ADD, dl,
  3514. PtrVT, Ptr,
  3515. DAG.getConstant(Offsets[i], dl, PtrVT),
  3516. Flags);
  3517. auto MMOFlags = MachineMemOperand::MONone;
  3518. if (isVolatile)
  3519. MMOFlags |= MachineMemOperand::MOVolatile;
  3520. if (isNonTemporal)
  3521. MMOFlags |= MachineMemOperand::MONonTemporal;
  3522. if (isInvariant)
  3523. MMOFlags |= MachineMemOperand::MOInvariant;
  3524. if (isDereferenceable)
  3525. MMOFlags |= MachineMemOperand::MODereferenceable;
  3526. MMOFlags |= TLI.getMMOFlags(I);
  3527. SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
  3528. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3529. MMOFlags, AAInfo, Ranges);
  3530. Values[i] = L;
  3531. Chains[ChainI] = L.getValue(1);
  3532. }
  3533. if (!ConstantMemory) {
  3534. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3535. makeArrayRef(Chains.data(), ChainI));
  3536. if (isVolatile)
  3537. DAG.setRoot(Chain);
  3538. else
  3539. PendingLoads.push_back(Chain);
  3540. }
  3541. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3542. DAG.getVTList(ValueVTs), Values));
  3543. }
  3544. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3545. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3546. "call visitStoreToSwiftError when backend supports swifterror");
  3547. SmallVector<EVT, 4> ValueVTs;
  3548. SmallVector<uint64_t, 4> Offsets;
  3549. const Value *SrcV = I.getOperand(0);
  3550. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3551. SrcV->getType(), ValueVTs, &Offsets);
  3552. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3553. "expect a single EVT for swifterror");
  3554. SDValue Src = getValue(SrcV);
  3555. // Create a virtual register, then update the virtual register.
  3556. unsigned VReg; bool CreatedVReg;
  3557. std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
  3558. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3559. // Chain can be getRoot or getControlRoot.
  3560. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3561. SDValue(Src.getNode(), Src.getResNo()));
  3562. DAG.setRoot(CopyNode);
  3563. if (CreatedVReg)
  3564. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
  3565. }
  3566. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3567. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3568. "call visitLoadFromSwiftError when backend supports swifterror");
  3569. assert(!I.isVolatile() &&
  3570. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3571. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3572. "Support volatile, non temporal, invariant for load_from_swift_error");
  3573. const Value *SV = I.getOperand(0);
  3574. Type *Ty = I.getType();
  3575. AAMDNodes AAInfo;
  3576. I.getAAMetadata(AAInfo);
  3577. assert(
  3578. (!AA ||
  3579. !AA->pointsToConstantMemory(MemoryLocation(
  3580. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3581. AAInfo))) &&
  3582. "load_from_swift_error should not be constant memory");
  3583. SmallVector<EVT, 4> ValueVTs;
  3584. SmallVector<uint64_t, 4> Offsets;
  3585. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3586. ValueVTs, &Offsets);
  3587. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3588. "expect a single EVT for swifterror");
  3589. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3590. SDValue L = DAG.getCopyFromReg(
  3591. getRoot(), getCurSDLoc(),
  3592. FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
  3593. ValueVTs[0]);
  3594. setValue(&I, L);
  3595. }
  3596. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3597. if (I.isAtomic())
  3598. return visitAtomicStore(I);
  3599. const Value *SrcV = I.getOperand(0);
  3600. const Value *PtrV = I.getOperand(1);
  3601. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3602. if (TLI.supportSwiftError()) {
  3603. // Swifterror values can come from either a function parameter with
  3604. // swifterror attribute or an alloca with swifterror attribute.
  3605. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3606. if (Arg->hasSwiftErrorAttr())
  3607. return visitStoreToSwiftError(I);
  3608. }
  3609. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3610. if (Alloca->isSwiftError())
  3611. return visitStoreToSwiftError(I);
  3612. }
  3613. }
  3614. SmallVector<EVT, 4> ValueVTs;
  3615. SmallVector<uint64_t, 4> Offsets;
  3616. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3617. SrcV->getType(), ValueVTs, &Offsets);
  3618. unsigned NumValues = ValueVTs.size();
  3619. if (NumValues == 0)
  3620. return;
  3621. // Get the lowered operands. Note that we do this after
  3622. // checking if NumResults is zero, because with zero results
  3623. // the operands won't have values in the map.
  3624. SDValue Src = getValue(SrcV);
  3625. SDValue Ptr = getValue(PtrV);
  3626. SDValue Root = getRoot();
  3627. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3628. SDLoc dl = getCurSDLoc();
  3629. EVT PtrVT = Ptr.getValueType();
  3630. unsigned Alignment = I.getAlignment();
  3631. AAMDNodes AAInfo;
  3632. I.getAAMetadata(AAInfo);
  3633. auto MMOFlags = MachineMemOperand::MONone;
  3634. if (I.isVolatile())
  3635. MMOFlags |= MachineMemOperand::MOVolatile;
  3636. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3637. MMOFlags |= MachineMemOperand::MONonTemporal;
  3638. MMOFlags |= TLI.getMMOFlags(I);
  3639. // An aggregate load cannot wrap around the address space, so offsets to its
  3640. // parts don't wrap either.
  3641. SDNodeFlags Flags;
  3642. Flags.setNoUnsignedWrap(true);
  3643. unsigned ChainI = 0;
  3644. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3645. // See visitLoad comments.
  3646. if (ChainI == MaxParallelChains) {
  3647. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3648. makeArrayRef(Chains.data(), ChainI));
  3649. Root = Chain;
  3650. ChainI = 0;
  3651. }
  3652. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3653. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3654. SDValue St = DAG.getStore(
  3655. Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
  3656. MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
  3657. Chains[ChainI] = St;
  3658. }
  3659. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3660. makeArrayRef(Chains.data(), ChainI));
  3661. DAG.setRoot(StoreNode);
  3662. }
  3663. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3664. bool IsCompressing) {
  3665. SDLoc sdl = getCurSDLoc();
  3666. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3667. unsigned& Alignment) {
  3668. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3669. Src0 = I.getArgOperand(0);
  3670. Ptr = I.getArgOperand(1);
  3671. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3672. Mask = I.getArgOperand(3);
  3673. };
  3674. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3675. unsigned& Alignment) {
  3676. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3677. Src0 = I.getArgOperand(0);
  3678. Ptr = I.getArgOperand(1);
  3679. Mask = I.getArgOperand(2);
  3680. Alignment = 0;
  3681. };
  3682. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3683. unsigned Alignment;
  3684. if (IsCompressing)
  3685. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3686. else
  3687. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3688. SDValue Ptr = getValue(PtrOperand);
  3689. SDValue Src0 = getValue(Src0Operand);
  3690. SDValue Mask = getValue(MaskOperand);
  3691. EVT VT = Src0.getValueType();
  3692. if (!Alignment)
  3693. Alignment = DAG.getEVTAlignment(VT);
  3694. AAMDNodes AAInfo;
  3695. I.getAAMetadata(AAInfo);
  3696. MachineMemOperand *MMO =
  3697. DAG.getMachineFunction().
  3698. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3699. MachineMemOperand::MOStore, VT.getStoreSize(),
  3700. Alignment, AAInfo);
  3701. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3702. MMO, false /* Truncating */,
  3703. IsCompressing);
  3704. DAG.setRoot(StoreNode);
  3705. setValue(&I, StoreNode);
  3706. }
  3707. // Get a uniform base for the Gather/Scatter intrinsic.
  3708. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3709. // We try to represent it as a base pointer + vector of indices.
  3710. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3711. // The first operand of the GEP may be a single pointer or a vector of pointers
  3712. // Example:
  3713. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3714. // or
  3715. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3716. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3717. //
  3718. // When the first GEP operand is a single pointer - it is the uniform base we
  3719. // are looking for. If first operand of the GEP is a splat vector - we
  3720. // extract the splat value and use it as a uniform base.
  3721. // In all other cases the function returns 'false'.
  3722. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3723. SDValue &Scale, SelectionDAGBuilder* SDB) {
  3724. SelectionDAG& DAG = SDB->DAG;
  3725. LLVMContext &Context = *DAG.getContext();
  3726. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3727. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3728. if (!GEP)
  3729. return false;
  3730. const Value *GEPPtr = GEP->getPointerOperand();
  3731. if (!GEPPtr->getType()->isVectorTy())
  3732. Ptr = GEPPtr;
  3733. else if (!(Ptr = getSplatValue(GEPPtr)))
  3734. return false;
  3735. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3736. Value *IndexVal = GEP->getOperand(FinalIndex);
  3737. // Ensure all the other indices are 0.
  3738. for (unsigned i = 1; i < FinalIndex; ++i) {
  3739. auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
  3740. if (!C || !C->isZero())
  3741. return false;
  3742. }
  3743. // The operands of the GEP may be defined in another basic block.
  3744. // In this case we'll not find nodes for the operands.
  3745. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3746. return false;
  3747. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3748. const DataLayout &DL = DAG.getDataLayout();
  3749. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3750. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3751. Base = SDB->getValue(Ptr);
  3752. Index = SDB->getValue(IndexVal);
  3753. if (!Index.getValueType().isVector()) {
  3754. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3755. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3756. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3757. }
  3758. return true;
  3759. }
  3760. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3761. SDLoc sdl = getCurSDLoc();
  3762. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3763. const Value *Ptr = I.getArgOperand(1);
  3764. SDValue Src0 = getValue(I.getArgOperand(0));
  3765. SDValue Mask = getValue(I.getArgOperand(3));
  3766. EVT VT = Src0.getValueType();
  3767. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3768. if (!Alignment)
  3769. Alignment = DAG.getEVTAlignment(VT);
  3770. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3771. AAMDNodes AAInfo;
  3772. I.getAAMetadata(AAInfo);
  3773. SDValue Base;
  3774. SDValue Index;
  3775. SDValue Scale;
  3776. const Value *BasePtr = Ptr;
  3777. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3778. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3779. MachineMemOperand *MMO = DAG.getMachineFunction().
  3780. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3781. MachineMemOperand::MOStore, VT.getStoreSize(),
  3782. Alignment, AAInfo);
  3783. if (!UniformBase) {
  3784. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3785. Index = getValue(Ptr);
  3786. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3787. }
  3788. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3789. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3790. Ops, MMO);
  3791. DAG.setRoot(Scatter);
  3792. setValue(&I, Scatter);
  3793. }
  3794. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3795. SDLoc sdl = getCurSDLoc();
  3796. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3797. unsigned& Alignment) {
  3798. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3799. Ptr = I.getArgOperand(0);
  3800. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3801. Mask = I.getArgOperand(2);
  3802. Src0 = I.getArgOperand(3);
  3803. };
  3804. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3805. unsigned& Alignment) {
  3806. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3807. Ptr = I.getArgOperand(0);
  3808. Alignment = 0;
  3809. Mask = I.getArgOperand(1);
  3810. Src0 = I.getArgOperand(2);
  3811. };
  3812. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3813. unsigned Alignment;
  3814. if (IsExpanding)
  3815. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3816. else
  3817. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3818. SDValue Ptr = getValue(PtrOperand);
  3819. SDValue Src0 = getValue(Src0Operand);
  3820. SDValue Mask = getValue(MaskOperand);
  3821. EVT VT = Src0.getValueType();
  3822. if (!Alignment)
  3823. Alignment = DAG.getEVTAlignment(VT);
  3824. AAMDNodes AAInfo;
  3825. I.getAAMetadata(AAInfo);
  3826. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3827. // Do not serialize masked loads of constant memory with anything.
  3828. bool AddToChain =
  3829. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3830. PtrOperand,
  3831. LocationSize::precise(
  3832. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3833. AAInfo));
  3834. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3835. MachineMemOperand *MMO =
  3836. DAG.getMachineFunction().
  3837. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3838. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3839. Alignment, AAInfo, Ranges);
  3840. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3841. ISD::NON_EXTLOAD, IsExpanding);
  3842. if (AddToChain)
  3843. PendingLoads.push_back(Load.getValue(1));
  3844. setValue(&I, Load);
  3845. }
  3846. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3847. SDLoc sdl = getCurSDLoc();
  3848. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3849. const Value *Ptr = I.getArgOperand(0);
  3850. SDValue Src0 = getValue(I.getArgOperand(3));
  3851. SDValue Mask = getValue(I.getArgOperand(2));
  3852. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3853. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3854. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3855. if (!Alignment)
  3856. Alignment = DAG.getEVTAlignment(VT);
  3857. AAMDNodes AAInfo;
  3858. I.getAAMetadata(AAInfo);
  3859. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3860. SDValue Root = DAG.getRoot();
  3861. SDValue Base;
  3862. SDValue Index;
  3863. SDValue Scale;
  3864. const Value *BasePtr = Ptr;
  3865. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3866. bool ConstantMemory = false;
  3867. if (UniformBase && AA &&
  3868. AA->pointsToConstantMemory(
  3869. MemoryLocation(BasePtr,
  3870. LocationSize::precise(
  3871. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3872. AAInfo))) {
  3873. // Do not serialize (non-volatile) loads of constant memory with anything.
  3874. Root = DAG.getEntryNode();
  3875. ConstantMemory = true;
  3876. }
  3877. MachineMemOperand *MMO =
  3878. DAG.getMachineFunction().
  3879. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3880. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3881. Alignment, AAInfo, Ranges);
  3882. if (!UniformBase) {
  3883. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3884. Index = getValue(Ptr);
  3885. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3886. }
  3887. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3888. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3889. Ops, MMO);
  3890. SDValue OutChain = Gather.getValue(1);
  3891. if (!ConstantMemory)
  3892. PendingLoads.push_back(OutChain);
  3893. setValue(&I, Gather);
  3894. }
  3895. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3896. SDLoc dl = getCurSDLoc();
  3897. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3898. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3899. SyncScope::ID SSID = I.getSyncScopeID();
  3900. SDValue InChain = getRoot();
  3901. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3902. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3903. auto Alignment = DAG.getEVTAlignment(MemVT);
  3904. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3905. if (I.isVolatile())
  3906. Flags |= MachineMemOperand::MOVolatile;
  3907. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3908. MachineFunction &MF = DAG.getMachineFunction();
  3909. MachineMemOperand *MMO =
  3910. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3911. Flags, MemVT.getStoreSize(), Alignment,
  3912. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3913. FailureOrdering);
  3914. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3915. dl, MemVT, VTs, InChain,
  3916. getValue(I.getPointerOperand()),
  3917. getValue(I.getCompareOperand()),
  3918. getValue(I.getNewValOperand()), MMO);
  3919. SDValue OutChain = L.getValue(2);
  3920. setValue(&I, L);
  3921. DAG.setRoot(OutChain);
  3922. }
  3923. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3924. SDLoc dl = getCurSDLoc();
  3925. ISD::NodeType NT;
  3926. switch (I.getOperation()) {
  3927. default: llvm_unreachable("Unknown atomicrmw operation");
  3928. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3929. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3930. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3931. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3932. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3933. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3934. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3935. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3936. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3937. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3938. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3939. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3940. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3941. }
  3942. AtomicOrdering Ordering = I.getOrdering();
  3943. SyncScope::ID SSID = I.getSyncScopeID();
  3944. SDValue InChain = getRoot();
  3945. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3946. auto Alignment = DAG.getEVTAlignment(MemVT);
  3947. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3948. if (I.isVolatile())
  3949. Flags |= MachineMemOperand::MOVolatile;
  3950. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3951. MachineFunction &MF = DAG.getMachineFunction();
  3952. MachineMemOperand *MMO =
  3953. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  3954. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  3955. nullptr, SSID, Ordering);
  3956. SDValue L =
  3957. DAG.getAtomic(NT, dl, MemVT, InChain,
  3958. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  3959. MMO);
  3960. SDValue OutChain = L.getValue(1);
  3961. setValue(&I, L);
  3962. DAG.setRoot(OutChain);
  3963. }
  3964. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  3965. SDLoc dl = getCurSDLoc();
  3966. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3967. SDValue Ops[3];
  3968. Ops[0] = getRoot();
  3969. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  3970. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3971. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  3972. TLI.getFenceOperandTy(DAG.getDataLayout()));
  3973. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  3974. }
  3975. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  3976. SDLoc dl = getCurSDLoc();
  3977. AtomicOrdering Order = I.getOrdering();
  3978. SyncScope::ID SSID = I.getSyncScopeID();
  3979. SDValue InChain = getRoot();
  3980. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3981. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3982. if (!TLI.supportsUnalignedAtomics() &&
  3983. I.getAlignment() < VT.getStoreSize())
  3984. report_fatal_error("Cannot generate unaligned atomic load");
  3985. auto Flags = MachineMemOperand::MOLoad;
  3986. if (I.isVolatile())
  3987. Flags |= MachineMemOperand::MOVolatile;
  3988. if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
  3989. Flags |= MachineMemOperand::MOInvariant;
  3990. if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
  3991. Flags |= MachineMemOperand::MODereferenceable;
  3992. Flags |= TLI.getMMOFlags(I);
  3993. MachineMemOperand *MMO =
  3994. DAG.getMachineFunction().
  3995. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3996. Flags, VT.getStoreSize(),
  3997. I.getAlignment() ? I.getAlignment() :
  3998. DAG.getEVTAlignment(VT),
  3999. AAMDNodes(), nullptr, SSID, Order);
  4000. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4001. SDValue L =
  4002. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
  4003. getValue(I.getPointerOperand()), MMO);
  4004. SDValue OutChain = L.getValue(1);
  4005. setValue(&I, L);
  4006. DAG.setRoot(OutChain);
  4007. }
  4008. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4009. SDLoc dl = getCurSDLoc();
  4010. AtomicOrdering Ordering = I.getOrdering();
  4011. SyncScope::ID SSID = I.getSyncScopeID();
  4012. SDValue InChain = getRoot();
  4013. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4014. EVT VT =
  4015. TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4016. if (I.getAlignment() < VT.getStoreSize())
  4017. report_fatal_error("Cannot generate unaligned atomic store");
  4018. auto Flags = MachineMemOperand::MOStore;
  4019. if (I.isVolatile())
  4020. Flags |= MachineMemOperand::MOVolatile;
  4021. Flags |= TLI.getMMOFlags(I);
  4022. MachineFunction &MF = DAG.getMachineFunction();
  4023. MachineMemOperand *MMO =
  4024. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4025. VT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4026. nullptr, SSID, Ordering);
  4027. SDValue OutChain =
  4028. DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT, InChain,
  4029. getValue(I.getPointerOperand()), getValue(I.getValueOperand()),
  4030. MMO);
  4031. DAG.setRoot(OutChain);
  4032. }
  4033. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4034. /// node.
  4035. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4036. unsigned Intrinsic) {
  4037. // Ignore the callsite's attributes. A specific call site may be marked with
  4038. // readnone, but the lowering code will expect the chain based on the
  4039. // definition.
  4040. const Function *F = I.getCalledFunction();
  4041. bool HasChain = !F->doesNotAccessMemory();
  4042. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4043. // Build the operand list.
  4044. SmallVector<SDValue, 8> Ops;
  4045. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4046. if (OnlyLoad) {
  4047. // We don't need to serialize loads against other loads.
  4048. Ops.push_back(DAG.getRoot());
  4049. } else {
  4050. Ops.push_back(getRoot());
  4051. }
  4052. }
  4053. // Info is set by getTgtMemInstrinsic
  4054. TargetLowering::IntrinsicInfo Info;
  4055. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4056. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4057. DAG.getMachineFunction(),
  4058. Intrinsic);
  4059. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4060. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4061. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4062. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4063. TLI.getPointerTy(DAG.getDataLayout())));
  4064. // Add all operands of the call to the operand list.
  4065. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4066. SDValue Op = getValue(I.getArgOperand(i));
  4067. Ops.push_back(Op);
  4068. }
  4069. SmallVector<EVT, 4> ValueVTs;
  4070. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4071. if (HasChain)
  4072. ValueVTs.push_back(MVT::Other);
  4073. SDVTList VTs = DAG.getVTList(ValueVTs);
  4074. // Create the node.
  4075. SDValue Result;
  4076. if (IsTgtIntrinsic) {
  4077. // This is target intrinsic that touches memory
  4078. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
  4079. Ops, Info.memVT,
  4080. MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
  4081. Info.flags, Info.size);
  4082. } else if (!HasChain) {
  4083. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4084. } else if (!I.getType()->isVoidTy()) {
  4085. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4086. } else {
  4087. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4088. }
  4089. if (HasChain) {
  4090. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4091. if (OnlyLoad)
  4092. PendingLoads.push_back(Chain);
  4093. else
  4094. DAG.setRoot(Chain);
  4095. }
  4096. if (!I.getType()->isVoidTy()) {
  4097. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4098. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4099. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4100. } else
  4101. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4102. setValue(&I, Result);
  4103. }
  4104. }
  4105. /// GetSignificand - Get the significand and build it into a floating-point
  4106. /// number with exponent of 1:
  4107. ///
  4108. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4109. ///
  4110. /// where Op is the hexadecimal representation of floating point value.
  4111. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4112. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4113. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4114. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4115. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4116. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4117. }
  4118. /// GetExponent - Get the exponent:
  4119. ///
  4120. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4121. ///
  4122. /// where Op is the hexadecimal representation of floating point value.
  4123. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4124. const TargetLowering &TLI, const SDLoc &dl) {
  4125. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4126. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4127. SDValue t1 = DAG.getNode(
  4128. ISD::SRL, dl, MVT::i32, t0,
  4129. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4130. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4131. DAG.getConstant(127, dl, MVT::i32));
  4132. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4133. }
  4134. /// getF32Constant - Get 32-bit floating point constant.
  4135. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4136. const SDLoc &dl) {
  4137. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4138. MVT::f32);
  4139. }
  4140. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4141. SelectionDAG &DAG) {
  4142. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4143. // IntegerPartOfX = ((int32_t)(t0);
  4144. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4145. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4146. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4147. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4148. // IntegerPartOfX <<= 23;
  4149. IntegerPartOfX = DAG.getNode(
  4150. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4151. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4152. DAG.getDataLayout())));
  4153. SDValue TwoToFractionalPartOfX;
  4154. if (LimitFloatPrecision <= 6) {
  4155. // For floating-point precision of 6:
  4156. //
  4157. // TwoToFractionalPartOfX =
  4158. // 0.997535578f +
  4159. // (0.735607626f + 0.252464424f * x) * x;
  4160. //
  4161. // error 0.0144103317, which is 6 bits
  4162. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4163. getF32Constant(DAG, 0x3e814304, dl));
  4164. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4165. getF32Constant(DAG, 0x3f3c50c8, dl));
  4166. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4167. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4168. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4169. } else if (LimitFloatPrecision <= 12) {
  4170. // For floating-point precision of 12:
  4171. //
  4172. // TwoToFractionalPartOfX =
  4173. // 0.999892986f +
  4174. // (0.696457318f +
  4175. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4176. //
  4177. // error 0.000107046256, which is 13 to 14 bits
  4178. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4179. getF32Constant(DAG, 0x3da235e3, dl));
  4180. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4181. getF32Constant(DAG, 0x3e65b8f3, dl));
  4182. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4183. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4184. getF32Constant(DAG, 0x3f324b07, dl));
  4185. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4186. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4187. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4188. } else { // LimitFloatPrecision <= 18
  4189. // For floating-point precision of 18:
  4190. //
  4191. // TwoToFractionalPartOfX =
  4192. // 0.999999982f +
  4193. // (0.693148872f +
  4194. // (0.240227044f +
  4195. // (0.554906021e-1f +
  4196. // (0.961591928e-2f +
  4197. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4198. // error 2.47208000*10^(-7), which is better than 18 bits
  4199. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4200. getF32Constant(DAG, 0x3924b03e, dl));
  4201. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4202. getF32Constant(DAG, 0x3ab24b87, dl));
  4203. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4204. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4205. getF32Constant(DAG, 0x3c1d8c17, dl));
  4206. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4207. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4208. getF32Constant(DAG, 0x3d634a1d, dl));
  4209. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4210. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4211. getF32Constant(DAG, 0x3e75fe14, dl));
  4212. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4213. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4214. getF32Constant(DAG, 0x3f317234, dl));
  4215. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4216. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4217. getF32Constant(DAG, 0x3f800000, dl));
  4218. }
  4219. // Add the exponent into the result in integer domain.
  4220. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4221. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4222. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4223. }
  4224. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4225. /// limited-precision mode.
  4226. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4227. const TargetLowering &TLI) {
  4228. if (Op.getValueType() == MVT::f32 &&
  4229. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4230. // Put the exponent in the right bit position for later addition to the
  4231. // final result:
  4232. //
  4233. // #define LOG2OFe 1.4426950f
  4234. // t0 = Op * LOG2OFe
  4235. // TODO: What fast-math-flags should be set here?
  4236. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4237. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4238. return getLimitedPrecisionExp2(t0, dl, DAG);
  4239. }
  4240. // No special expansion.
  4241. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4242. }
  4243. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4244. /// limited-precision mode.
  4245. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4246. const TargetLowering &TLI) {
  4247. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4248. if (Op.getValueType() == MVT::f32 &&
  4249. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4250. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4251. // Scale the exponent by log(2) [0.69314718f].
  4252. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4253. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4254. getF32Constant(DAG, 0x3f317218, dl));
  4255. // Get the significand and build it into a floating-point number with
  4256. // exponent of 1.
  4257. SDValue X = GetSignificand(DAG, Op1, dl);
  4258. SDValue LogOfMantissa;
  4259. if (LimitFloatPrecision <= 6) {
  4260. // For floating-point precision of 6:
  4261. //
  4262. // LogofMantissa =
  4263. // -1.1609546f +
  4264. // (1.4034025f - 0.23903021f * x) * x;
  4265. //
  4266. // error 0.0034276066, which is better than 8 bits
  4267. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4268. getF32Constant(DAG, 0xbe74c456, dl));
  4269. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4270. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4271. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4272. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4273. getF32Constant(DAG, 0x3f949a29, dl));
  4274. } else if (LimitFloatPrecision <= 12) {
  4275. // For floating-point precision of 12:
  4276. //
  4277. // LogOfMantissa =
  4278. // -1.7417939f +
  4279. // (2.8212026f +
  4280. // (-1.4699568f +
  4281. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4282. //
  4283. // error 0.000061011436, which is 14 bits
  4284. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4285. getF32Constant(DAG, 0xbd67b6d6, dl));
  4286. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4287. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4288. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4289. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4290. getF32Constant(DAG, 0x3fbc278b, dl));
  4291. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4292. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4293. getF32Constant(DAG, 0x40348e95, dl));
  4294. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4295. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4296. getF32Constant(DAG, 0x3fdef31a, dl));
  4297. } else { // LimitFloatPrecision <= 18
  4298. // For floating-point precision of 18:
  4299. //
  4300. // LogOfMantissa =
  4301. // -2.1072184f +
  4302. // (4.2372794f +
  4303. // (-3.7029485f +
  4304. // (2.2781945f +
  4305. // (-0.87823314f +
  4306. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4307. //
  4308. // error 0.0000023660568, which is better than 18 bits
  4309. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4310. getF32Constant(DAG, 0xbc91e5ac, dl));
  4311. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4312. getF32Constant(DAG, 0x3e4350aa, dl));
  4313. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4314. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4315. getF32Constant(DAG, 0x3f60d3e3, dl));
  4316. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4317. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4318. getF32Constant(DAG, 0x4011cdf0, dl));
  4319. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4320. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4321. getF32Constant(DAG, 0x406cfd1c, dl));
  4322. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4323. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4324. getF32Constant(DAG, 0x408797cb, dl));
  4325. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4326. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4327. getF32Constant(DAG, 0x4006dcab, dl));
  4328. }
  4329. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4330. }
  4331. // No special expansion.
  4332. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4333. }
  4334. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4335. /// limited-precision mode.
  4336. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4337. const TargetLowering &TLI) {
  4338. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4339. if (Op.getValueType() == MVT::f32 &&
  4340. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4341. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4342. // Get the exponent.
  4343. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4344. // Get the significand and build it into a floating-point number with
  4345. // exponent of 1.
  4346. SDValue X = GetSignificand(DAG, Op1, dl);
  4347. // Different possible minimax approximations of significand in
  4348. // floating-point for various degrees of accuracy over [1,2].
  4349. SDValue Log2ofMantissa;
  4350. if (LimitFloatPrecision <= 6) {
  4351. // For floating-point precision of 6:
  4352. //
  4353. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4354. //
  4355. // error 0.0049451742, which is more than 7 bits
  4356. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4357. getF32Constant(DAG, 0xbeb08fe0, dl));
  4358. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4359. getF32Constant(DAG, 0x40019463, dl));
  4360. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4361. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4362. getF32Constant(DAG, 0x3fd6633d, dl));
  4363. } else if (LimitFloatPrecision <= 12) {
  4364. // For floating-point precision of 12:
  4365. //
  4366. // Log2ofMantissa =
  4367. // -2.51285454f +
  4368. // (4.07009056f +
  4369. // (-2.12067489f +
  4370. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4371. //
  4372. // error 0.0000876136000, which is better than 13 bits
  4373. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4374. getF32Constant(DAG, 0xbda7262e, dl));
  4375. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4376. getF32Constant(DAG, 0x3f25280b, dl));
  4377. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4378. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4379. getF32Constant(DAG, 0x4007b923, dl));
  4380. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4381. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4382. getF32Constant(DAG, 0x40823e2f, dl));
  4383. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4384. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4385. getF32Constant(DAG, 0x4020d29c, dl));
  4386. } else { // LimitFloatPrecision <= 18
  4387. // For floating-point precision of 18:
  4388. //
  4389. // Log2ofMantissa =
  4390. // -3.0400495f +
  4391. // (6.1129976f +
  4392. // (-5.3420409f +
  4393. // (3.2865683f +
  4394. // (-1.2669343f +
  4395. // (0.27515199f -
  4396. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4397. //
  4398. // error 0.0000018516, which is better than 18 bits
  4399. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4400. getF32Constant(DAG, 0xbcd2769e, dl));
  4401. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4402. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4403. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4404. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4405. getF32Constant(DAG, 0x3fa22ae7, dl));
  4406. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4407. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4408. getF32Constant(DAG, 0x40525723, dl));
  4409. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4410. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4411. getF32Constant(DAG, 0x40aaf200, dl));
  4412. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4413. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4414. getF32Constant(DAG, 0x40c39dad, dl));
  4415. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4416. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4417. getF32Constant(DAG, 0x4042902c, dl));
  4418. }
  4419. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4420. }
  4421. // No special expansion.
  4422. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4423. }
  4424. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4425. /// limited-precision mode.
  4426. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4427. const TargetLowering &TLI) {
  4428. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4429. if (Op.getValueType() == MVT::f32 &&
  4430. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4431. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4432. // Scale the exponent by log10(2) [0.30102999f].
  4433. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4434. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4435. getF32Constant(DAG, 0x3e9a209a, dl));
  4436. // Get the significand and build it into a floating-point number with
  4437. // exponent of 1.
  4438. SDValue X = GetSignificand(DAG, Op1, dl);
  4439. SDValue Log10ofMantissa;
  4440. if (LimitFloatPrecision <= 6) {
  4441. // For floating-point precision of 6:
  4442. //
  4443. // Log10ofMantissa =
  4444. // -0.50419619f +
  4445. // (0.60948995f - 0.10380950f * x) * x;
  4446. //
  4447. // error 0.0014886165, which is 6 bits
  4448. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4449. getF32Constant(DAG, 0xbdd49a13, dl));
  4450. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4451. getF32Constant(DAG, 0x3f1c0789, dl));
  4452. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4453. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4454. getF32Constant(DAG, 0x3f011300, dl));
  4455. } else if (LimitFloatPrecision <= 12) {
  4456. // For floating-point precision of 12:
  4457. //
  4458. // Log10ofMantissa =
  4459. // -0.64831180f +
  4460. // (0.91751397f +
  4461. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4462. //
  4463. // error 0.00019228036, which is better than 12 bits
  4464. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4465. getF32Constant(DAG, 0x3d431f31, dl));
  4466. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4467. getF32Constant(DAG, 0x3ea21fb2, dl));
  4468. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4469. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4470. getF32Constant(DAG, 0x3f6ae232, dl));
  4471. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4472. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4473. getF32Constant(DAG, 0x3f25f7c3, dl));
  4474. } else { // LimitFloatPrecision <= 18
  4475. // For floating-point precision of 18:
  4476. //
  4477. // Log10ofMantissa =
  4478. // -0.84299375f +
  4479. // (1.5327582f +
  4480. // (-1.0688956f +
  4481. // (0.49102474f +
  4482. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4483. //
  4484. // error 0.0000037995730, which is better than 18 bits
  4485. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4486. getF32Constant(DAG, 0x3c5d51ce, dl));
  4487. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4488. getF32Constant(DAG, 0x3e00685a, dl));
  4489. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4490. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4491. getF32Constant(DAG, 0x3efb6798, dl));
  4492. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4493. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4494. getF32Constant(DAG, 0x3f88d192, dl));
  4495. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4496. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4497. getF32Constant(DAG, 0x3fc4316c, dl));
  4498. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4499. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4500. getF32Constant(DAG, 0x3f57ce70, dl));
  4501. }
  4502. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4503. }
  4504. // No special expansion.
  4505. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4506. }
  4507. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4508. /// limited-precision mode.
  4509. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4510. const TargetLowering &TLI) {
  4511. if (Op.getValueType() == MVT::f32 &&
  4512. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4513. return getLimitedPrecisionExp2(Op, dl, DAG);
  4514. // No special expansion.
  4515. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4516. }
  4517. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4518. /// limited-precision mode with x == 10.0f.
  4519. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4520. SelectionDAG &DAG, const TargetLowering &TLI) {
  4521. bool IsExp10 = false;
  4522. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4523. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4524. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4525. APFloat Ten(10.0f);
  4526. IsExp10 = LHSC->isExactlyValue(Ten);
  4527. }
  4528. }
  4529. // TODO: What fast-math-flags should be set on the FMUL node?
  4530. if (IsExp10) {
  4531. // Put the exponent in the right bit position for later addition to the
  4532. // final result:
  4533. //
  4534. // #define LOG2OF10 3.3219281f
  4535. // t0 = Op * LOG2OF10;
  4536. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4537. getF32Constant(DAG, 0x40549a78, dl));
  4538. return getLimitedPrecisionExp2(t0, dl, DAG);
  4539. }
  4540. // No special expansion.
  4541. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4542. }
  4543. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4544. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4545. SelectionDAG &DAG) {
  4546. // If RHS is a constant, we can expand this out to a multiplication tree,
  4547. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4548. // optimizing for size, we only want to do this if the expansion would produce
  4549. // a small number of multiplies, otherwise we do the full expansion.
  4550. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4551. // Get the exponent as a positive value.
  4552. unsigned Val = RHSC->getSExtValue();
  4553. if ((int)Val < 0) Val = -Val;
  4554. // powi(x, 0) -> 1.0
  4555. if (Val == 0)
  4556. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4557. const Function &F = DAG.getMachineFunction().getFunction();
  4558. if (!F.hasOptSize() ||
  4559. // If optimizing for size, don't insert too many multiplies.
  4560. // This inserts up to 5 multiplies.
  4561. countPopulation(Val) + Log2_32(Val) < 7) {
  4562. // We use the simple binary decomposition method to generate the multiply
  4563. // sequence. There are more optimal ways to do this (for example,
  4564. // powi(x,15) generates one more multiply than it should), but this has
  4565. // the benefit of being both really simple and much better than a libcall.
  4566. SDValue Res; // Logically starts equal to 1.0
  4567. SDValue CurSquare = LHS;
  4568. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4569. // nodes.
  4570. while (Val) {
  4571. if (Val & 1) {
  4572. if (Res.getNode())
  4573. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4574. else
  4575. Res = CurSquare; // 1.0*CurSquare.
  4576. }
  4577. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4578. CurSquare, CurSquare);
  4579. Val >>= 1;
  4580. }
  4581. // If the original was negative, invert the result, producing 1/(x*x*x).
  4582. if (RHSC->getSExtValue() < 0)
  4583. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4584. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4585. return Res;
  4586. }
  4587. }
  4588. // Otherwise, expand to a libcall.
  4589. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4590. }
  4591. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4592. // bitcasted argument.
  4593. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4594. switch (N.getOpcode()) {
  4595. case ISD::CopyFromReg:
  4596. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4597. case ISD::BITCAST:
  4598. case ISD::AssertZext:
  4599. case ISD::AssertSext:
  4600. case ISD::TRUNCATE:
  4601. return getUnderlyingArgReg(N.getOperand(0));
  4602. default:
  4603. return 0;
  4604. }
  4605. }
  4606. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4607. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4608. /// instruction selection, they will be inserted to the entry BB.
  4609. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4610. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4611. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4612. const Argument *Arg = dyn_cast<Argument>(V);
  4613. if (!Arg)
  4614. return false;
  4615. if (!IsDbgDeclare) {
  4616. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4617. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4618. // the entry block.
  4619. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4620. if (!IsInEntryBlock)
  4621. return false;
  4622. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4623. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4624. // variable that also is a param.
  4625. //
  4626. // Although, if we are at the top of the entry block already, we can still
  4627. // emit using ArgDbgValue. This might catch some situations when the
  4628. // dbg.value refers to an argument that isn't used in the entry block, so
  4629. // any CopyToReg node would be optimized out and the only way to express
  4630. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4631. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4632. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4633. // current function, and the dbg.value intrinsic is found in the entry
  4634. // block.
  4635. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4636. !DL->getInlinedAt();
  4637. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4638. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4639. return false;
  4640. // Here we assume that a function argument on IR level only can be used to
  4641. // describe one input parameter on source level. If we for example have
  4642. // source code like this
  4643. //
  4644. // struct A { long x, y; };
  4645. // void foo(struct A a, long b) {
  4646. // ...
  4647. // b = a.x;
  4648. // ...
  4649. // }
  4650. //
  4651. // and IR like this
  4652. //
  4653. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4654. // entry:
  4655. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4656. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4657. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4658. // ...
  4659. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4660. // ...
  4661. //
  4662. // then the last dbg.value is describing a parameter "b" using a value that
  4663. // is an argument. But since we already has used %a1 to describe a parameter
  4664. // we should not handle that last dbg.value here (that would result in an
  4665. // incorrect hoisting of the DBG_VALUE to the function entry).
  4666. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4667. // for the situation with fragments above.
  4668. if (VariableIsFunctionInputArg) {
  4669. unsigned ArgNo = Arg->getArgNo();
  4670. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4671. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4672. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4673. return false;
  4674. FuncInfo.DescribedArgs.set(ArgNo);
  4675. }
  4676. }
  4677. MachineFunction &MF = DAG.getMachineFunction();
  4678. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4679. bool IsIndirect = false;
  4680. Optional<MachineOperand> Op;
  4681. // Some arguments' frame index is recorded during argument lowering.
  4682. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4683. if (FI != std::numeric_limits<int>::max())
  4684. Op = MachineOperand::CreateFI(FI);
  4685. if (!Op && N.getNode()) {
  4686. unsigned Reg = getUnderlyingArgReg(N);
  4687. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4688. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4689. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4690. if (PR)
  4691. Reg = PR;
  4692. }
  4693. if (Reg) {
  4694. Op = MachineOperand::CreateReg(Reg, false);
  4695. IsIndirect = IsDbgDeclare;
  4696. }
  4697. }
  4698. if (!Op && N.getNode()) {
  4699. // Check if frame index is available.
  4700. SDValue LCandidate = peekThroughBitcasts(N);
  4701. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4702. if (FrameIndexSDNode *FINode =
  4703. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4704. Op = MachineOperand::CreateFI(FINode->getIndex());
  4705. }
  4706. if (!Op) {
  4707. // Check if ValueMap has reg number.
  4708. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4709. if (VMI != FuncInfo.ValueMap.end()) {
  4710. const auto &TLI = DAG.getTargetLoweringInfo();
  4711. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4712. V->getType(), getABIRegCopyCC(V));
  4713. if (RFV.occupiesMultipleRegs()) {
  4714. unsigned Offset = 0;
  4715. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4716. Op = MachineOperand::CreateReg(RegAndSize.first, false);
  4717. auto FragmentExpr = DIExpression::createFragmentExpression(
  4718. Expr, Offset, RegAndSize.second);
  4719. if (!FragmentExpr)
  4720. continue;
  4721. FuncInfo.ArgDbgValues.push_back(
  4722. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4723. Op->getReg(), Variable, *FragmentExpr));
  4724. Offset += RegAndSize.second;
  4725. }
  4726. return true;
  4727. }
  4728. Op = MachineOperand::CreateReg(VMI->second, false);
  4729. IsIndirect = IsDbgDeclare;
  4730. }
  4731. }
  4732. if (!Op)
  4733. return false;
  4734. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4735. "Expected inlined-at fields to agree");
  4736. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4737. FuncInfo.ArgDbgValues.push_back(
  4738. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4739. *Op, Variable, Expr));
  4740. return true;
  4741. }
  4742. /// Return the appropriate SDDbgValue based on N.
  4743. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4744. DILocalVariable *Variable,
  4745. DIExpression *Expr,
  4746. const DebugLoc &dl,
  4747. unsigned DbgSDNodeOrder) {
  4748. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4749. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4750. // stack slot locations.
  4751. //
  4752. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4753. // debug values here after optimization:
  4754. //
  4755. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4756. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4757. //
  4758. // Both describe the direct values of their associated variables.
  4759. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4760. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4761. }
  4762. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4763. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4764. }
  4765. // VisualStudio defines setjmp as _setjmp
  4766. #if defined(_MSC_VER) && defined(setjmp) && \
  4767. !defined(setjmp_undefined_for_msvc)
  4768. # pragma push_macro("setjmp")
  4769. # undef setjmp
  4770. # define setjmp_undefined_for_msvc
  4771. #endif
  4772. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4773. switch (Intrinsic) {
  4774. case Intrinsic::smul_fix:
  4775. return ISD::SMULFIX;
  4776. case Intrinsic::umul_fix:
  4777. return ISD::UMULFIX;
  4778. default:
  4779. llvm_unreachable("Unhandled fixed point intrinsic");
  4780. }
  4781. }
  4782. /// Lower the call to the specified intrinsic function. If we want to emit this
  4783. /// as a call to a named external function, return the name. Otherwise, lower it
  4784. /// and return null.
  4785. const char *
  4786. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  4787. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4788. SDLoc sdl = getCurSDLoc();
  4789. DebugLoc dl = getCurDebugLoc();
  4790. SDValue Res;
  4791. switch (Intrinsic) {
  4792. default:
  4793. // By default, turn this into a target intrinsic node.
  4794. visitTargetIntrinsic(I, Intrinsic);
  4795. return nullptr;
  4796. case Intrinsic::vastart: visitVAStart(I); return nullptr;
  4797. case Intrinsic::vaend: visitVAEnd(I); return nullptr;
  4798. case Intrinsic::vacopy: visitVACopy(I); return nullptr;
  4799. case Intrinsic::returnaddress:
  4800. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4801. TLI.getPointerTy(DAG.getDataLayout()),
  4802. getValue(I.getArgOperand(0))));
  4803. return nullptr;
  4804. case Intrinsic::addressofreturnaddress:
  4805. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4806. TLI.getPointerTy(DAG.getDataLayout())));
  4807. return nullptr;
  4808. case Intrinsic::sponentry:
  4809. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4810. TLI.getPointerTy(DAG.getDataLayout())));
  4811. return nullptr;
  4812. case Intrinsic::frameaddress:
  4813. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4814. TLI.getPointerTy(DAG.getDataLayout()),
  4815. getValue(I.getArgOperand(0))));
  4816. return nullptr;
  4817. case Intrinsic::read_register: {
  4818. Value *Reg = I.getArgOperand(0);
  4819. SDValue Chain = getRoot();
  4820. SDValue RegName =
  4821. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4822. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4823. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4824. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4825. setValue(&I, Res);
  4826. DAG.setRoot(Res.getValue(1));
  4827. return nullptr;
  4828. }
  4829. case Intrinsic::write_register: {
  4830. Value *Reg = I.getArgOperand(0);
  4831. Value *RegValue = I.getArgOperand(1);
  4832. SDValue Chain = getRoot();
  4833. SDValue RegName =
  4834. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4835. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4836. RegName, getValue(RegValue)));
  4837. return nullptr;
  4838. }
  4839. case Intrinsic::setjmp:
  4840. return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
  4841. case Intrinsic::longjmp:
  4842. return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
  4843. case Intrinsic::memcpy: {
  4844. const auto &MCI = cast<MemCpyInst>(I);
  4845. SDValue Op1 = getValue(I.getArgOperand(0));
  4846. SDValue Op2 = getValue(I.getArgOperand(1));
  4847. SDValue Op3 = getValue(I.getArgOperand(2));
  4848. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4849. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4850. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4851. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4852. bool isVol = MCI.isVolatile();
  4853. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4854. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4855. // node.
  4856. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4857. false, isTC,
  4858. MachinePointerInfo(I.getArgOperand(0)),
  4859. MachinePointerInfo(I.getArgOperand(1)));
  4860. updateDAGForMaybeTailCall(MC);
  4861. return nullptr;
  4862. }
  4863. case Intrinsic::memset: {
  4864. const auto &MSI = cast<MemSetInst>(I);
  4865. SDValue Op1 = getValue(I.getArgOperand(0));
  4866. SDValue Op2 = getValue(I.getArgOperand(1));
  4867. SDValue Op3 = getValue(I.getArgOperand(2));
  4868. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4869. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4870. bool isVol = MSI.isVolatile();
  4871. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4872. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4873. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4874. updateDAGForMaybeTailCall(MS);
  4875. return nullptr;
  4876. }
  4877. case Intrinsic::memmove: {
  4878. const auto &MMI = cast<MemMoveInst>(I);
  4879. SDValue Op1 = getValue(I.getArgOperand(0));
  4880. SDValue Op2 = getValue(I.getArgOperand(1));
  4881. SDValue Op3 = getValue(I.getArgOperand(2));
  4882. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4883. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4884. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4885. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4886. bool isVol = MMI.isVolatile();
  4887. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4888. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4889. // node.
  4890. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4891. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4892. MachinePointerInfo(I.getArgOperand(1)));
  4893. updateDAGForMaybeTailCall(MM);
  4894. return nullptr;
  4895. }
  4896. case Intrinsic::memcpy_element_unordered_atomic: {
  4897. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4898. SDValue Dst = getValue(MI.getRawDest());
  4899. SDValue Src = getValue(MI.getRawSource());
  4900. SDValue Length = getValue(MI.getLength());
  4901. unsigned DstAlign = MI.getDestAlignment();
  4902. unsigned SrcAlign = MI.getSourceAlignment();
  4903. Type *LengthTy = MI.getLength()->getType();
  4904. unsigned ElemSz = MI.getElementSizeInBytes();
  4905. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4906. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4907. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4908. MachinePointerInfo(MI.getRawDest()),
  4909. MachinePointerInfo(MI.getRawSource()));
  4910. updateDAGForMaybeTailCall(MC);
  4911. return nullptr;
  4912. }
  4913. case Intrinsic::memmove_element_unordered_atomic: {
  4914. auto &MI = cast<AtomicMemMoveInst>(I);
  4915. SDValue Dst = getValue(MI.getRawDest());
  4916. SDValue Src = getValue(MI.getRawSource());
  4917. SDValue Length = getValue(MI.getLength());
  4918. unsigned DstAlign = MI.getDestAlignment();
  4919. unsigned SrcAlign = MI.getSourceAlignment();
  4920. Type *LengthTy = MI.getLength()->getType();
  4921. unsigned ElemSz = MI.getElementSizeInBytes();
  4922. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4923. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  4924. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4925. MachinePointerInfo(MI.getRawDest()),
  4926. MachinePointerInfo(MI.getRawSource()));
  4927. updateDAGForMaybeTailCall(MC);
  4928. return nullptr;
  4929. }
  4930. case Intrinsic::memset_element_unordered_atomic: {
  4931. auto &MI = cast<AtomicMemSetInst>(I);
  4932. SDValue Dst = getValue(MI.getRawDest());
  4933. SDValue Val = getValue(MI.getValue());
  4934. SDValue Length = getValue(MI.getLength());
  4935. unsigned DstAlign = MI.getDestAlignment();
  4936. Type *LengthTy = MI.getLength()->getType();
  4937. unsigned ElemSz = MI.getElementSizeInBytes();
  4938. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4939. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  4940. LengthTy, ElemSz, isTC,
  4941. MachinePointerInfo(MI.getRawDest()));
  4942. updateDAGForMaybeTailCall(MC);
  4943. return nullptr;
  4944. }
  4945. case Intrinsic::dbg_addr:
  4946. case Intrinsic::dbg_declare: {
  4947. const auto &DI = cast<DbgVariableIntrinsic>(I);
  4948. DILocalVariable *Variable = DI.getVariable();
  4949. DIExpression *Expression = DI.getExpression();
  4950. dropDanglingDebugInfo(Variable, Expression);
  4951. assert(Variable && "Missing variable");
  4952. // Check if address has undef value.
  4953. const Value *Address = DI.getVariableLocation();
  4954. if (!Address || isa<UndefValue>(Address) ||
  4955. (Address->use_empty() && !isa<Argument>(Address))) {
  4956. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  4957. return nullptr;
  4958. }
  4959. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  4960. // Check if this variable can be described by a frame index, typically
  4961. // either as a static alloca or a byval parameter.
  4962. int FI = std::numeric_limits<int>::max();
  4963. if (const auto *AI =
  4964. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  4965. if (AI->isStaticAlloca()) {
  4966. auto I = FuncInfo.StaticAllocaMap.find(AI);
  4967. if (I != FuncInfo.StaticAllocaMap.end())
  4968. FI = I->second;
  4969. }
  4970. } else if (const auto *Arg = dyn_cast<Argument>(
  4971. Address->stripInBoundsConstantOffsets())) {
  4972. FI = FuncInfo.getArgumentFrameIndex(Arg);
  4973. }
  4974. // llvm.dbg.addr is control dependent and always generates indirect
  4975. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  4976. // the MachineFunction variable table.
  4977. if (FI != std::numeric_limits<int>::max()) {
  4978. if (Intrinsic == Intrinsic::dbg_addr) {
  4979. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  4980. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  4981. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  4982. }
  4983. return nullptr;
  4984. }
  4985. SDValue &N = NodeMap[Address];
  4986. if (!N.getNode() && isa<Argument>(Address))
  4987. // Check unused arguments map.
  4988. N = UnusedArgNodeMap[Address];
  4989. SDDbgValue *SDV;
  4990. if (N.getNode()) {
  4991. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  4992. Address = BCI->getOperand(0);
  4993. // Parameters are handled specially.
  4994. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  4995. if (isParameter && FINode) {
  4996. // Byval parameter. We have a frame index at this point.
  4997. SDV =
  4998. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  4999. /*IsIndirect*/ true, dl, SDNodeOrder);
  5000. } else if (isa<Argument>(Address)) {
  5001. // Address is an argument, so try to emit its dbg value using
  5002. // virtual register info from the FuncInfo.ValueMap.
  5003. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5004. return nullptr;
  5005. } else {
  5006. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5007. true, dl, SDNodeOrder);
  5008. }
  5009. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5010. } else {
  5011. // If Address is an argument then try to emit its dbg value using
  5012. // virtual register info from the FuncInfo.ValueMap.
  5013. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5014. N)) {
  5015. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5016. }
  5017. }
  5018. return nullptr;
  5019. }
  5020. case Intrinsic::dbg_label: {
  5021. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5022. DILabel *Label = DI.getLabel();
  5023. assert(Label && "Missing label");
  5024. SDDbgLabel *SDV;
  5025. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5026. DAG.AddDbgLabel(SDV);
  5027. return nullptr;
  5028. }
  5029. case Intrinsic::dbg_value: {
  5030. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5031. assert(DI.getVariable() && "Missing variable");
  5032. DILocalVariable *Variable = DI.getVariable();
  5033. DIExpression *Expression = DI.getExpression();
  5034. dropDanglingDebugInfo(Variable, Expression);
  5035. const Value *V = DI.getValue();
  5036. if (!V)
  5037. return nullptr;
  5038. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5039. SDNodeOrder))
  5040. return nullptr;
  5041. // TODO: Dangling debug info will eventually either be resolved or produce
  5042. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5043. // between the original dbg.value location and its resolved DBG_VALUE, which
  5044. // we should ideally fill with an extra Undef DBG_VALUE.
  5045. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5046. return nullptr;
  5047. }
  5048. case Intrinsic::eh_typeid_for: {
  5049. // Find the type id for the given typeinfo.
  5050. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5051. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5052. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5053. setValue(&I, Res);
  5054. return nullptr;
  5055. }
  5056. case Intrinsic::eh_return_i32:
  5057. case Intrinsic::eh_return_i64:
  5058. DAG.getMachineFunction().setCallsEHReturn(true);
  5059. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5060. MVT::Other,
  5061. getControlRoot(),
  5062. getValue(I.getArgOperand(0)),
  5063. getValue(I.getArgOperand(1))));
  5064. return nullptr;
  5065. case Intrinsic::eh_unwind_init:
  5066. DAG.getMachineFunction().setCallsUnwindInit(true);
  5067. return nullptr;
  5068. case Intrinsic::eh_dwarf_cfa:
  5069. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5070. TLI.getPointerTy(DAG.getDataLayout()),
  5071. getValue(I.getArgOperand(0))));
  5072. return nullptr;
  5073. case Intrinsic::eh_sjlj_callsite: {
  5074. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5075. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5076. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5077. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5078. MMI.setCurrentCallSite(CI->getZExtValue());
  5079. return nullptr;
  5080. }
  5081. case Intrinsic::eh_sjlj_functioncontext: {
  5082. // Get and store the index of the function context.
  5083. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5084. AllocaInst *FnCtx =
  5085. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5086. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5087. MFI.setFunctionContextIndex(FI);
  5088. return nullptr;
  5089. }
  5090. case Intrinsic::eh_sjlj_setjmp: {
  5091. SDValue Ops[2];
  5092. Ops[0] = getRoot();
  5093. Ops[1] = getValue(I.getArgOperand(0));
  5094. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5095. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5096. setValue(&I, Op.getValue(0));
  5097. DAG.setRoot(Op.getValue(1));
  5098. return nullptr;
  5099. }
  5100. case Intrinsic::eh_sjlj_longjmp:
  5101. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5102. getRoot(), getValue(I.getArgOperand(0))));
  5103. return nullptr;
  5104. case Intrinsic::eh_sjlj_setup_dispatch:
  5105. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5106. getRoot()));
  5107. return nullptr;
  5108. case Intrinsic::masked_gather:
  5109. visitMaskedGather(I);
  5110. return nullptr;
  5111. case Intrinsic::masked_load:
  5112. visitMaskedLoad(I);
  5113. return nullptr;
  5114. case Intrinsic::masked_scatter:
  5115. visitMaskedScatter(I);
  5116. return nullptr;
  5117. case Intrinsic::masked_store:
  5118. visitMaskedStore(I);
  5119. return nullptr;
  5120. case Intrinsic::masked_expandload:
  5121. visitMaskedLoad(I, true /* IsExpanding */);
  5122. return nullptr;
  5123. case Intrinsic::masked_compressstore:
  5124. visitMaskedStore(I, true /* IsCompressing */);
  5125. return nullptr;
  5126. case Intrinsic::x86_mmx_pslli_w:
  5127. case Intrinsic::x86_mmx_pslli_d:
  5128. case Intrinsic::x86_mmx_pslli_q:
  5129. case Intrinsic::x86_mmx_psrli_w:
  5130. case Intrinsic::x86_mmx_psrli_d:
  5131. case Intrinsic::x86_mmx_psrli_q:
  5132. case Intrinsic::x86_mmx_psrai_w:
  5133. case Intrinsic::x86_mmx_psrai_d: {
  5134. SDValue ShAmt = getValue(I.getArgOperand(1));
  5135. if (isa<ConstantSDNode>(ShAmt)) {
  5136. visitTargetIntrinsic(I, Intrinsic);
  5137. return nullptr;
  5138. }
  5139. unsigned NewIntrinsic = 0;
  5140. EVT ShAmtVT = MVT::v2i32;
  5141. switch (Intrinsic) {
  5142. case Intrinsic::x86_mmx_pslli_w:
  5143. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  5144. break;
  5145. case Intrinsic::x86_mmx_pslli_d:
  5146. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  5147. break;
  5148. case Intrinsic::x86_mmx_pslli_q:
  5149. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  5150. break;
  5151. case Intrinsic::x86_mmx_psrli_w:
  5152. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  5153. break;
  5154. case Intrinsic::x86_mmx_psrli_d:
  5155. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  5156. break;
  5157. case Intrinsic::x86_mmx_psrli_q:
  5158. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  5159. break;
  5160. case Intrinsic::x86_mmx_psrai_w:
  5161. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  5162. break;
  5163. case Intrinsic::x86_mmx_psrai_d:
  5164. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  5165. break;
  5166. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5167. }
  5168. // The vector shift intrinsics with scalars uses 32b shift amounts but
  5169. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  5170. // to be zero.
  5171. // We must do this early because v2i32 is not a legal type.
  5172. SDValue ShOps[2];
  5173. ShOps[0] = ShAmt;
  5174. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  5175. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  5176. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5177. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  5178. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  5179. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  5180. getValue(I.getArgOperand(0)), ShAmt);
  5181. setValue(&I, Res);
  5182. return nullptr;
  5183. }
  5184. case Intrinsic::powi:
  5185. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5186. getValue(I.getArgOperand(1)), DAG));
  5187. return nullptr;
  5188. case Intrinsic::log:
  5189. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5190. return nullptr;
  5191. case Intrinsic::log2:
  5192. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5193. return nullptr;
  5194. case Intrinsic::log10:
  5195. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5196. return nullptr;
  5197. case Intrinsic::exp:
  5198. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5199. return nullptr;
  5200. case Intrinsic::exp2:
  5201. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5202. return nullptr;
  5203. case Intrinsic::pow:
  5204. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5205. getValue(I.getArgOperand(1)), DAG, TLI));
  5206. return nullptr;
  5207. case Intrinsic::sqrt:
  5208. case Intrinsic::fabs:
  5209. case Intrinsic::sin:
  5210. case Intrinsic::cos:
  5211. case Intrinsic::floor:
  5212. case Intrinsic::ceil:
  5213. case Intrinsic::trunc:
  5214. case Intrinsic::rint:
  5215. case Intrinsic::nearbyint:
  5216. case Intrinsic::round:
  5217. case Intrinsic::canonicalize: {
  5218. unsigned Opcode;
  5219. switch (Intrinsic) {
  5220. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5221. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5222. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5223. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5224. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5225. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5226. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5227. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5228. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5229. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5230. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5231. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5232. }
  5233. setValue(&I, DAG.getNode(Opcode, sdl,
  5234. getValue(I.getArgOperand(0)).getValueType(),
  5235. getValue(I.getArgOperand(0))));
  5236. return nullptr;
  5237. }
  5238. case Intrinsic::minnum: {
  5239. auto VT = getValue(I.getArgOperand(0)).getValueType();
  5240. unsigned Opc =
  5241. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
  5242. ? ISD::FMINIMUM
  5243. : ISD::FMINNUM;
  5244. setValue(&I, DAG.getNode(Opc, sdl, VT,
  5245. getValue(I.getArgOperand(0)),
  5246. getValue(I.getArgOperand(1))));
  5247. return nullptr;
  5248. }
  5249. case Intrinsic::maxnum: {
  5250. auto VT = getValue(I.getArgOperand(0)).getValueType();
  5251. unsigned Opc =
  5252. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
  5253. ? ISD::FMAXIMUM
  5254. : ISD::FMAXNUM;
  5255. setValue(&I, DAG.getNode(Opc, sdl, VT,
  5256. getValue(I.getArgOperand(0)),
  5257. getValue(I.getArgOperand(1))));
  5258. return nullptr;
  5259. }
  5260. case Intrinsic::minimum:
  5261. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5262. getValue(I.getArgOperand(0)).getValueType(),
  5263. getValue(I.getArgOperand(0)),
  5264. getValue(I.getArgOperand(1))));
  5265. return nullptr;
  5266. case Intrinsic::maximum:
  5267. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5268. getValue(I.getArgOperand(0)).getValueType(),
  5269. getValue(I.getArgOperand(0)),
  5270. getValue(I.getArgOperand(1))));
  5271. return nullptr;
  5272. case Intrinsic::copysign:
  5273. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5274. getValue(I.getArgOperand(0)).getValueType(),
  5275. getValue(I.getArgOperand(0)),
  5276. getValue(I.getArgOperand(1))));
  5277. return nullptr;
  5278. case Intrinsic::fma:
  5279. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5280. getValue(I.getArgOperand(0)).getValueType(),
  5281. getValue(I.getArgOperand(0)),
  5282. getValue(I.getArgOperand(1)),
  5283. getValue(I.getArgOperand(2))));
  5284. return nullptr;
  5285. case Intrinsic::experimental_constrained_fadd:
  5286. case Intrinsic::experimental_constrained_fsub:
  5287. case Intrinsic::experimental_constrained_fmul:
  5288. case Intrinsic::experimental_constrained_fdiv:
  5289. case Intrinsic::experimental_constrained_frem:
  5290. case Intrinsic::experimental_constrained_fma:
  5291. case Intrinsic::experimental_constrained_sqrt:
  5292. case Intrinsic::experimental_constrained_pow:
  5293. case Intrinsic::experimental_constrained_powi:
  5294. case Intrinsic::experimental_constrained_sin:
  5295. case Intrinsic::experimental_constrained_cos:
  5296. case Intrinsic::experimental_constrained_exp:
  5297. case Intrinsic::experimental_constrained_exp2:
  5298. case Intrinsic::experimental_constrained_log:
  5299. case Intrinsic::experimental_constrained_log10:
  5300. case Intrinsic::experimental_constrained_log2:
  5301. case Intrinsic::experimental_constrained_rint:
  5302. case Intrinsic::experimental_constrained_nearbyint:
  5303. case Intrinsic::experimental_constrained_maxnum:
  5304. case Intrinsic::experimental_constrained_minnum:
  5305. case Intrinsic::experimental_constrained_ceil:
  5306. case Intrinsic::experimental_constrained_floor:
  5307. case Intrinsic::experimental_constrained_round:
  5308. case Intrinsic::experimental_constrained_trunc:
  5309. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5310. return nullptr;
  5311. case Intrinsic::fmuladd: {
  5312. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5313. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5314. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5315. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5316. getValue(I.getArgOperand(0)).getValueType(),
  5317. getValue(I.getArgOperand(0)),
  5318. getValue(I.getArgOperand(1)),
  5319. getValue(I.getArgOperand(2))));
  5320. } else {
  5321. // TODO: Intrinsic calls should have fast-math-flags.
  5322. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5323. getValue(I.getArgOperand(0)).getValueType(),
  5324. getValue(I.getArgOperand(0)),
  5325. getValue(I.getArgOperand(1)));
  5326. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5327. getValue(I.getArgOperand(0)).getValueType(),
  5328. Mul,
  5329. getValue(I.getArgOperand(2)));
  5330. setValue(&I, Add);
  5331. }
  5332. return nullptr;
  5333. }
  5334. case Intrinsic::convert_to_fp16:
  5335. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5336. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5337. getValue(I.getArgOperand(0)),
  5338. DAG.getTargetConstant(0, sdl,
  5339. MVT::i32))));
  5340. return nullptr;
  5341. case Intrinsic::convert_from_fp16:
  5342. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5343. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5344. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5345. getValue(I.getArgOperand(0)))));
  5346. return nullptr;
  5347. case Intrinsic::pcmarker: {
  5348. SDValue Tmp = getValue(I.getArgOperand(0));
  5349. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5350. return nullptr;
  5351. }
  5352. case Intrinsic::readcyclecounter: {
  5353. SDValue Op = getRoot();
  5354. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5355. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5356. setValue(&I, Res);
  5357. DAG.setRoot(Res.getValue(1));
  5358. return nullptr;
  5359. }
  5360. case Intrinsic::bitreverse:
  5361. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5362. getValue(I.getArgOperand(0)).getValueType(),
  5363. getValue(I.getArgOperand(0))));
  5364. return nullptr;
  5365. case Intrinsic::bswap:
  5366. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5367. getValue(I.getArgOperand(0)).getValueType(),
  5368. getValue(I.getArgOperand(0))));
  5369. return nullptr;
  5370. case Intrinsic::cttz: {
  5371. SDValue Arg = getValue(I.getArgOperand(0));
  5372. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5373. EVT Ty = Arg.getValueType();
  5374. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5375. sdl, Ty, Arg));
  5376. return nullptr;
  5377. }
  5378. case Intrinsic::ctlz: {
  5379. SDValue Arg = getValue(I.getArgOperand(0));
  5380. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5381. EVT Ty = Arg.getValueType();
  5382. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5383. sdl, Ty, Arg));
  5384. return nullptr;
  5385. }
  5386. case Intrinsic::ctpop: {
  5387. SDValue Arg = getValue(I.getArgOperand(0));
  5388. EVT Ty = Arg.getValueType();
  5389. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5390. return nullptr;
  5391. }
  5392. case Intrinsic::fshl:
  5393. case Intrinsic::fshr: {
  5394. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5395. SDValue X = getValue(I.getArgOperand(0));
  5396. SDValue Y = getValue(I.getArgOperand(1));
  5397. SDValue Z = getValue(I.getArgOperand(2));
  5398. EVT VT = X.getValueType();
  5399. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5400. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5401. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5402. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5403. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5404. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5405. return nullptr;
  5406. }
  5407. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5408. // avoid the select that is necessary in the general case to filter out
  5409. // the 0-shift possibility that leads to UB.
  5410. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5411. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5412. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5413. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5414. return nullptr;
  5415. }
  5416. // Some targets only rotate one way. Try the opposite direction.
  5417. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5418. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5419. // Negate the shift amount because it is safe to ignore the high bits.
  5420. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5421. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5422. return nullptr;
  5423. }
  5424. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5425. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5426. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5427. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5428. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5429. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5430. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5431. return nullptr;
  5432. }
  5433. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5434. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5435. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5436. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5437. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5438. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5439. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5440. // and that is undefined. We must compare and select to avoid UB.
  5441. EVT CCVT = MVT::i1;
  5442. if (VT.isVector())
  5443. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5444. // For fshl, 0-shift returns the 1st arg (X).
  5445. // For fshr, 0-shift returns the 2nd arg (Y).
  5446. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5447. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5448. return nullptr;
  5449. }
  5450. case Intrinsic::sadd_sat: {
  5451. SDValue Op1 = getValue(I.getArgOperand(0));
  5452. SDValue Op2 = getValue(I.getArgOperand(1));
  5453. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5454. return nullptr;
  5455. }
  5456. case Intrinsic::uadd_sat: {
  5457. SDValue Op1 = getValue(I.getArgOperand(0));
  5458. SDValue Op2 = getValue(I.getArgOperand(1));
  5459. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5460. return nullptr;
  5461. }
  5462. case Intrinsic::ssub_sat: {
  5463. SDValue Op1 = getValue(I.getArgOperand(0));
  5464. SDValue Op2 = getValue(I.getArgOperand(1));
  5465. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5466. return nullptr;
  5467. }
  5468. case Intrinsic::usub_sat: {
  5469. SDValue Op1 = getValue(I.getArgOperand(0));
  5470. SDValue Op2 = getValue(I.getArgOperand(1));
  5471. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5472. return nullptr;
  5473. }
  5474. case Intrinsic::smul_fix:
  5475. case Intrinsic::umul_fix: {
  5476. SDValue Op1 = getValue(I.getArgOperand(0));
  5477. SDValue Op2 = getValue(I.getArgOperand(1));
  5478. SDValue Op3 = getValue(I.getArgOperand(2));
  5479. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5480. Op1.getValueType(), Op1, Op2, Op3));
  5481. return nullptr;
  5482. }
  5483. case Intrinsic::stacksave: {
  5484. SDValue Op = getRoot();
  5485. Res = DAG.getNode(
  5486. ISD::STACKSAVE, sdl,
  5487. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5488. setValue(&I, Res);
  5489. DAG.setRoot(Res.getValue(1));
  5490. return nullptr;
  5491. }
  5492. case Intrinsic::stackrestore:
  5493. Res = getValue(I.getArgOperand(0));
  5494. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5495. return nullptr;
  5496. case Intrinsic::get_dynamic_area_offset: {
  5497. SDValue Op = getRoot();
  5498. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5499. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5500. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5501. // target.
  5502. if (PtrTy != ResTy)
  5503. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5504. " intrinsic!");
  5505. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5506. Op);
  5507. DAG.setRoot(Op);
  5508. setValue(&I, Res);
  5509. return nullptr;
  5510. }
  5511. case Intrinsic::stackguard: {
  5512. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5513. MachineFunction &MF = DAG.getMachineFunction();
  5514. const Module &M = *MF.getFunction().getParent();
  5515. SDValue Chain = getRoot();
  5516. if (TLI.useLoadStackGuardNode()) {
  5517. Res = getLoadStackGuard(DAG, sdl, Chain);
  5518. } else {
  5519. const Value *Global = TLI.getSDagStackGuard(M);
  5520. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5521. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5522. MachinePointerInfo(Global, 0), Align,
  5523. MachineMemOperand::MOVolatile);
  5524. }
  5525. if (TLI.useStackGuardXorFP())
  5526. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5527. DAG.setRoot(Chain);
  5528. setValue(&I, Res);
  5529. return nullptr;
  5530. }
  5531. case Intrinsic::stackprotector: {
  5532. // Emit code into the DAG to store the stack guard onto the stack.
  5533. MachineFunction &MF = DAG.getMachineFunction();
  5534. MachineFrameInfo &MFI = MF.getFrameInfo();
  5535. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5536. SDValue Src, Chain = getRoot();
  5537. if (TLI.useLoadStackGuardNode())
  5538. Src = getLoadStackGuard(DAG, sdl, Chain);
  5539. else
  5540. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5541. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5542. int FI = FuncInfo.StaticAllocaMap[Slot];
  5543. MFI.setStackProtectorIndex(FI);
  5544. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5545. // Store the stack protector onto the stack.
  5546. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5547. DAG.getMachineFunction(), FI),
  5548. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5549. setValue(&I, Res);
  5550. DAG.setRoot(Res);
  5551. return nullptr;
  5552. }
  5553. case Intrinsic::objectsize: {
  5554. // If we don't know by now, we're never going to know.
  5555. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5556. assert(CI && "Non-constant type in __builtin_object_size?");
  5557. SDValue Arg = getValue(I.getCalledValue());
  5558. EVT Ty = Arg.getValueType();
  5559. if (CI->isZero())
  5560. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5561. else
  5562. Res = DAG.getConstant(0, sdl, Ty);
  5563. setValue(&I, Res);
  5564. return nullptr;
  5565. }
  5566. case Intrinsic::is_constant:
  5567. // If this wasn't constant-folded away by now, then it's not a
  5568. // constant.
  5569. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5570. return nullptr;
  5571. case Intrinsic::annotation:
  5572. case Intrinsic::ptr_annotation:
  5573. case Intrinsic::launder_invariant_group:
  5574. case Intrinsic::strip_invariant_group:
  5575. // Drop the intrinsic, but forward the value
  5576. setValue(&I, getValue(I.getOperand(0)));
  5577. return nullptr;
  5578. case Intrinsic::assume:
  5579. case Intrinsic::var_annotation:
  5580. case Intrinsic::sideeffect:
  5581. // Discard annotate attributes, assumptions, and artificial side-effects.
  5582. return nullptr;
  5583. case Intrinsic::codeview_annotation: {
  5584. // Emit a label associated with this metadata.
  5585. MachineFunction &MF = DAG.getMachineFunction();
  5586. MCSymbol *Label =
  5587. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5588. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5589. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5590. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5591. DAG.setRoot(Res);
  5592. return nullptr;
  5593. }
  5594. case Intrinsic::init_trampoline: {
  5595. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5596. SDValue Ops[6];
  5597. Ops[0] = getRoot();
  5598. Ops[1] = getValue(I.getArgOperand(0));
  5599. Ops[2] = getValue(I.getArgOperand(1));
  5600. Ops[3] = getValue(I.getArgOperand(2));
  5601. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5602. Ops[5] = DAG.getSrcValue(F);
  5603. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5604. DAG.setRoot(Res);
  5605. return nullptr;
  5606. }
  5607. case Intrinsic::adjust_trampoline:
  5608. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5609. TLI.getPointerTy(DAG.getDataLayout()),
  5610. getValue(I.getArgOperand(0))));
  5611. return nullptr;
  5612. case Intrinsic::gcroot: {
  5613. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5614. "only valid in functions with gc specified, enforced by Verifier");
  5615. assert(GFI && "implied by previous");
  5616. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5617. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5618. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5619. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5620. return nullptr;
  5621. }
  5622. case Intrinsic::gcread:
  5623. case Intrinsic::gcwrite:
  5624. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5625. case Intrinsic::flt_rounds:
  5626. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5627. return nullptr;
  5628. case Intrinsic::expect:
  5629. // Just replace __builtin_expect(exp, c) with EXP.
  5630. setValue(&I, getValue(I.getArgOperand(0)));
  5631. return nullptr;
  5632. case Intrinsic::debugtrap:
  5633. case Intrinsic::trap: {
  5634. StringRef TrapFuncName =
  5635. I.getAttributes()
  5636. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5637. .getValueAsString();
  5638. if (TrapFuncName.empty()) {
  5639. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5640. ISD::TRAP : ISD::DEBUGTRAP;
  5641. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5642. return nullptr;
  5643. }
  5644. TargetLowering::ArgListTy Args;
  5645. TargetLowering::CallLoweringInfo CLI(DAG);
  5646. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5647. CallingConv::C, I.getType(),
  5648. DAG.getExternalSymbol(TrapFuncName.data(),
  5649. TLI.getPointerTy(DAG.getDataLayout())),
  5650. std::move(Args));
  5651. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5652. DAG.setRoot(Result.second);
  5653. return nullptr;
  5654. }
  5655. case Intrinsic::uadd_with_overflow:
  5656. case Intrinsic::sadd_with_overflow:
  5657. case Intrinsic::usub_with_overflow:
  5658. case Intrinsic::ssub_with_overflow:
  5659. case Intrinsic::umul_with_overflow:
  5660. case Intrinsic::smul_with_overflow: {
  5661. ISD::NodeType Op;
  5662. switch (Intrinsic) {
  5663. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5664. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5665. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5666. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5667. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5668. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5669. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5670. }
  5671. SDValue Op1 = getValue(I.getArgOperand(0));
  5672. SDValue Op2 = getValue(I.getArgOperand(1));
  5673. EVT ResultVT = Op1.getValueType();
  5674. EVT OverflowVT = MVT::i1;
  5675. if (ResultVT.isVector())
  5676. OverflowVT = EVT::getVectorVT(
  5677. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5678. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5679. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5680. return nullptr;
  5681. }
  5682. case Intrinsic::prefetch: {
  5683. SDValue Ops[5];
  5684. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5685. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5686. Ops[0] = DAG.getRoot();
  5687. Ops[1] = getValue(I.getArgOperand(0));
  5688. Ops[2] = getValue(I.getArgOperand(1));
  5689. Ops[3] = getValue(I.getArgOperand(2));
  5690. Ops[4] = getValue(I.getArgOperand(3));
  5691. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5692. DAG.getVTList(MVT::Other), Ops,
  5693. EVT::getIntegerVT(*Context, 8),
  5694. MachinePointerInfo(I.getArgOperand(0)),
  5695. 0, /* align */
  5696. Flags);
  5697. // Chain the prefetch in parallell with any pending loads, to stay out of
  5698. // the way of later optimizations.
  5699. PendingLoads.push_back(Result);
  5700. Result = getRoot();
  5701. DAG.setRoot(Result);
  5702. return nullptr;
  5703. }
  5704. case Intrinsic::lifetime_start:
  5705. case Intrinsic::lifetime_end: {
  5706. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5707. // Stack coloring is not enabled in O0, discard region information.
  5708. if (TM.getOptLevel() == CodeGenOpt::None)
  5709. return nullptr;
  5710. const int64_t ObjectSize =
  5711. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5712. Value *const ObjectPtr = I.getArgOperand(1);
  5713. SmallVector<Value *, 4> Allocas;
  5714. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5715. for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
  5716. E = Allocas.end(); Object != E; ++Object) {
  5717. AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5718. // Could not find an Alloca.
  5719. if (!LifetimeObject)
  5720. continue;
  5721. // First check that the Alloca is static, otherwise it won't have a
  5722. // valid frame index.
  5723. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5724. if (SI == FuncInfo.StaticAllocaMap.end())
  5725. return nullptr;
  5726. const int FrameIndex = SI->second;
  5727. int64_t Offset;
  5728. if (GetPointerBaseWithConstantOffset(
  5729. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5730. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5731. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5732. Offset);
  5733. DAG.setRoot(Res);
  5734. }
  5735. return nullptr;
  5736. }
  5737. case Intrinsic::invariant_start:
  5738. // Discard region information.
  5739. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5740. return nullptr;
  5741. case Intrinsic::invariant_end:
  5742. // Discard region information.
  5743. return nullptr;
  5744. case Intrinsic::clear_cache:
  5745. return TLI.getClearCacheBuiltinName();
  5746. case Intrinsic::donothing:
  5747. // ignore
  5748. return nullptr;
  5749. case Intrinsic::experimental_stackmap:
  5750. visitStackmap(I);
  5751. return nullptr;
  5752. case Intrinsic::experimental_patchpoint_void:
  5753. case Intrinsic::experimental_patchpoint_i64:
  5754. visitPatchpoint(&I);
  5755. return nullptr;
  5756. case Intrinsic::experimental_gc_statepoint:
  5757. LowerStatepoint(ImmutableStatepoint(&I));
  5758. return nullptr;
  5759. case Intrinsic::experimental_gc_result:
  5760. visitGCResult(cast<GCResultInst>(I));
  5761. return nullptr;
  5762. case Intrinsic::experimental_gc_relocate:
  5763. visitGCRelocate(cast<GCRelocateInst>(I));
  5764. return nullptr;
  5765. case Intrinsic::instrprof_increment:
  5766. llvm_unreachable("instrprof failed to lower an increment");
  5767. case Intrinsic::instrprof_value_profile:
  5768. llvm_unreachable("instrprof failed to lower a value profiling call");
  5769. case Intrinsic::localescape: {
  5770. MachineFunction &MF = DAG.getMachineFunction();
  5771. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5772. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5773. // is the same on all targets.
  5774. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5775. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5776. if (isa<ConstantPointerNull>(Arg))
  5777. continue; // Skip null pointers. They represent a hole in index space.
  5778. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5779. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5780. "can only escape static allocas");
  5781. int FI = FuncInfo.StaticAllocaMap[Slot];
  5782. MCSymbol *FrameAllocSym =
  5783. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5784. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5785. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5786. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5787. .addSym(FrameAllocSym)
  5788. .addFrameIndex(FI);
  5789. }
  5790. return nullptr;
  5791. }
  5792. case Intrinsic::localrecover: {
  5793. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5794. MachineFunction &MF = DAG.getMachineFunction();
  5795. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5796. // Get the symbol that defines the frame offset.
  5797. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5798. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5799. unsigned IdxVal =
  5800. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5801. MCSymbol *FrameAllocSym =
  5802. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5803. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5804. // Create a MCSymbol for the label to avoid any target lowering
  5805. // that would make this PC relative.
  5806. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5807. SDValue OffsetVal =
  5808. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5809. // Add the offset to the FP.
  5810. Value *FP = I.getArgOperand(1);
  5811. SDValue FPVal = getValue(FP);
  5812. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5813. setValue(&I, Add);
  5814. return nullptr;
  5815. }
  5816. case Intrinsic::eh_exceptionpointer:
  5817. case Intrinsic::eh_exceptioncode: {
  5818. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5819. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5820. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5821. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5822. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5823. SDValue N =
  5824. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5825. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5826. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5827. setValue(&I, N);
  5828. return nullptr;
  5829. }
  5830. case Intrinsic::xray_customevent: {
  5831. // Here we want to make sure that the intrinsic behaves as if it has a
  5832. // specific calling convention, and only for x86_64.
  5833. // FIXME: Support other platforms later.
  5834. const auto &Triple = DAG.getTarget().getTargetTriple();
  5835. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5836. return nullptr;
  5837. SDLoc DL = getCurSDLoc();
  5838. SmallVector<SDValue, 8> Ops;
  5839. // We want to say that we always want the arguments in registers.
  5840. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5841. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5842. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5843. SDValue Chain = getRoot();
  5844. Ops.push_back(LogEntryVal);
  5845. Ops.push_back(StrSizeVal);
  5846. Ops.push_back(Chain);
  5847. // We need to enforce the calling convention for the callsite, so that
  5848. // argument ordering is enforced correctly, and that register allocation can
  5849. // see that some registers may be assumed clobbered and have to preserve
  5850. // them across calls to the intrinsic.
  5851. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5852. DL, NodeTys, Ops);
  5853. SDValue patchableNode = SDValue(MN, 0);
  5854. DAG.setRoot(patchableNode);
  5855. setValue(&I, patchableNode);
  5856. return nullptr;
  5857. }
  5858. case Intrinsic::xray_typedevent: {
  5859. // Here we want to make sure that the intrinsic behaves as if it has a
  5860. // specific calling convention, and only for x86_64.
  5861. // FIXME: Support other platforms later.
  5862. const auto &Triple = DAG.getTarget().getTargetTriple();
  5863. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5864. return nullptr;
  5865. SDLoc DL = getCurSDLoc();
  5866. SmallVector<SDValue, 8> Ops;
  5867. // We want to say that we always want the arguments in registers.
  5868. // It's unclear to me how manipulating the selection DAG here forces callers
  5869. // to provide arguments in registers instead of on the stack.
  5870. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5871. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5872. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5873. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5874. SDValue Chain = getRoot();
  5875. Ops.push_back(LogTypeId);
  5876. Ops.push_back(LogEntryVal);
  5877. Ops.push_back(StrSizeVal);
  5878. Ops.push_back(Chain);
  5879. // We need to enforce the calling convention for the callsite, so that
  5880. // argument ordering is enforced correctly, and that register allocation can
  5881. // see that some registers may be assumed clobbered and have to preserve
  5882. // them across calls to the intrinsic.
  5883. MachineSDNode *MN = DAG.getMachineNode(
  5884. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5885. SDValue patchableNode = SDValue(MN, 0);
  5886. DAG.setRoot(patchableNode);
  5887. setValue(&I, patchableNode);
  5888. return nullptr;
  5889. }
  5890. case Intrinsic::experimental_deoptimize:
  5891. LowerDeoptimizeCall(&I);
  5892. return nullptr;
  5893. case Intrinsic::experimental_vector_reduce_fadd:
  5894. case Intrinsic::experimental_vector_reduce_fmul:
  5895. case Intrinsic::experimental_vector_reduce_add:
  5896. case Intrinsic::experimental_vector_reduce_mul:
  5897. case Intrinsic::experimental_vector_reduce_and:
  5898. case Intrinsic::experimental_vector_reduce_or:
  5899. case Intrinsic::experimental_vector_reduce_xor:
  5900. case Intrinsic::experimental_vector_reduce_smax:
  5901. case Intrinsic::experimental_vector_reduce_smin:
  5902. case Intrinsic::experimental_vector_reduce_umax:
  5903. case Intrinsic::experimental_vector_reduce_umin:
  5904. case Intrinsic::experimental_vector_reduce_fmax:
  5905. case Intrinsic::experimental_vector_reduce_fmin:
  5906. visitVectorReduce(I, Intrinsic);
  5907. return nullptr;
  5908. case Intrinsic::icall_branch_funnel: {
  5909. SmallVector<SDValue, 16> Ops;
  5910. Ops.push_back(DAG.getRoot());
  5911. Ops.push_back(getValue(I.getArgOperand(0)));
  5912. int64_t Offset;
  5913. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5914. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  5915. if (!Base)
  5916. report_fatal_error(
  5917. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5918. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  5919. struct BranchFunnelTarget {
  5920. int64_t Offset;
  5921. SDValue Target;
  5922. };
  5923. SmallVector<BranchFunnelTarget, 8> Targets;
  5924. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  5925. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  5926. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  5927. if (ElemBase != Base)
  5928. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  5929. "to the same GlobalValue");
  5930. SDValue Val = getValue(I.getArgOperand(Op + 1));
  5931. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  5932. if (!GA)
  5933. report_fatal_error(
  5934. "llvm.icall.branch.funnel operand must be a GlobalValue");
  5935. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  5936. GA->getGlobal(), getCurSDLoc(),
  5937. Val.getValueType(), GA->getOffset())});
  5938. }
  5939. llvm::sort(Targets,
  5940. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  5941. return T1.Offset < T2.Offset;
  5942. });
  5943. for (auto &T : Targets) {
  5944. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  5945. Ops.push_back(T.Target);
  5946. }
  5947. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  5948. getCurSDLoc(), MVT::Other, Ops),
  5949. 0);
  5950. DAG.setRoot(N);
  5951. setValue(&I, N);
  5952. HasTailCall = true;
  5953. return nullptr;
  5954. }
  5955. case Intrinsic::wasm_landingpad_index:
  5956. // Information this intrinsic contained has been transferred to
  5957. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  5958. // delete it now.
  5959. return nullptr;
  5960. }
  5961. }
  5962. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  5963. const ConstrainedFPIntrinsic &FPI) {
  5964. SDLoc sdl = getCurSDLoc();
  5965. unsigned Opcode;
  5966. switch (FPI.getIntrinsicID()) {
  5967. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5968. case Intrinsic::experimental_constrained_fadd:
  5969. Opcode = ISD::STRICT_FADD;
  5970. break;
  5971. case Intrinsic::experimental_constrained_fsub:
  5972. Opcode = ISD::STRICT_FSUB;
  5973. break;
  5974. case Intrinsic::experimental_constrained_fmul:
  5975. Opcode = ISD::STRICT_FMUL;
  5976. break;
  5977. case Intrinsic::experimental_constrained_fdiv:
  5978. Opcode = ISD::STRICT_FDIV;
  5979. break;
  5980. case Intrinsic::experimental_constrained_frem:
  5981. Opcode = ISD::STRICT_FREM;
  5982. break;
  5983. case Intrinsic::experimental_constrained_fma:
  5984. Opcode = ISD::STRICT_FMA;
  5985. break;
  5986. case Intrinsic::experimental_constrained_sqrt:
  5987. Opcode = ISD::STRICT_FSQRT;
  5988. break;
  5989. case Intrinsic::experimental_constrained_pow:
  5990. Opcode = ISD::STRICT_FPOW;
  5991. break;
  5992. case Intrinsic::experimental_constrained_powi:
  5993. Opcode = ISD::STRICT_FPOWI;
  5994. break;
  5995. case Intrinsic::experimental_constrained_sin:
  5996. Opcode = ISD::STRICT_FSIN;
  5997. break;
  5998. case Intrinsic::experimental_constrained_cos:
  5999. Opcode = ISD::STRICT_FCOS;
  6000. break;
  6001. case Intrinsic::experimental_constrained_exp:
  6002. Opcode = ISD::STRICT_FEXP;
  6003. break;
  6004. case Intrinsic::experimental_constrained_exp2:
  6005. Opcode = ISD::STRICT_FEXP2;
  6006. break;
  6007. case Intrinsic::experimental_constrained_log:
  6008. Opcode = ISD::STRICT_FLOG;
  6009. break;
  6010. case Intrinsic::experimental_constrained_log10:
  6011. Opcode = ISD::STRICT_FLOG10;
  6012. break;
  6013. case Intrinsic::experimental_constrained_log2:
  6014. Opcode = ISD::STRICT_FLOG2;
  6015. break;
  6016. case Intrinsic::experimental_constrained_rint:
  6017. Opcode = ISD::STRICT_FRINT;
  6018. break;
  6019. case Intrinsic::experimental_constrained_nearbyint:
  6020. Opcode = ISD::STRICT_FNEARBYINT;
  6021. break;
  6022. case Intrinsic::experimental_constrained_maxnum:
  6023. Opcode = ISD::STRICT_FMAXNUM;
  6024. break;
  6025. case Intrinsic::experimental_constrained_minnum:
  6026. Opcode = ISD::STRICT_FMINNUM;
  6027. break;
  6028. case Intrinsic::experimental_constrained_ceil:
  6029. Opcode = ISD::STRICT_FCEIL;
  6030. break;
  6031. case Intrinsic::experimental_constrained_floor:
  6032. Opcode = ISD::STRICT_FFLOOR;
  6033. break;
  6034. case Intrinsic::experimental_constrained_round:
  6035. Opcode = ISD::STRICT_FROUND;
  6036. break;
  6037. case Intrinsic::experimental_constrained_trunc:
  6038. Opcode = ISD::STRICT_FTRUNC;
  6039. break;
  6040. }
  6041. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6042. SDValue Chain = getRoot();
  6043. SmallVector<EVT, 4> ValueVTs;
  6044. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6045. ValueVTs.push_back(MVT::Other); // Out chain
  6046. SDVTList VTs = DAG.getVTList(ValueVTs);
  6047. SDValue Result;
  6048. if (FPI.isUnaryOp())
  6049. Result = DAG.getNode(Opcode, sdl, VTs,
  6050. { Chain, getValue(FPI.getArgOperand(0)) });
  6051. else if (FPI.isTernaryOp())
  6052. Result = DAG.getNode(Opcode, sdl, VTs,
  6053. { Chain, getValue(FPI.getArgOperand(0)),
  6054. getValue(FPI.getArgOperand(1)),
  6055. getValue(FPI.getArgOperand(2)) });
  6056. else
  6057. Result = DAG.getNode(Opcode, sdl, VTs,
  6058. { Chain, getValue(FPI.getArgOperand(0)),
  6059. getValue(FPI.getArgOperand(1)) });
  6060. assert(Result.getNode()->getNumValues() == 2);
  6061. SDValue OutChain = Result.getValue(1);
  6062. DAG.setRoot(OutChain);
  6063. SDValue FPResult = Result.getValue(0);
  6064. setValue(&FPI, FPResult);
  6065. }
  6066. std::pair<SDValue, SDValue>
  6067. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6068. const BasicBlock *EHPadBB) {
  6069. MachineFunction &MF = DAG.getMachineFunction();
  6070. MachineModuleInfo &MMI = MF.getMMI();
  6071. MCSymbol *BeginLabel = nullptr;
  6072. if (EHPadBB) {
  6073. // Insert a label before the invoke call to mark the try range. This can be
  6074. // used to detect deletion of the invoke via the MachineModuleInfo.
  6075. BeginLabel = MMI.getContext().createTempSymbol();
  6076. // For SjLj, keep track of which landing pads go with which invokes
  6077. // so as to maintain the ordering of pads in the LSDA.
  6078. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6079. if (CallSiteIndex) {
  6080. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6081. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6082. // Now that the call site is handled, stop tracking it.
  6083. MMI.setCurrentCallSite(0);
  6084. }
  6085. // Both PendingLoads and PendingExports must be flushed here;
  6086. // this call might not return.
  6087. (void)getRoot();
  6088. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6089. CLI.setChain(getRoot());
  6090. }
  6091. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6092. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6093. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6094. "Non-null chain expected with non-tail call!");
  6095. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6096. "Null value expected with tail call!");
  6097. if (!Result.second.getNode()) {
  6098. // As a special case, a null chain means that a tail call has been emitted
  6099. // and the DAG root is already updated.
  6100. HasTailCall = true;
  6101. // Since there's no actual continuation from this block, nothing can be
  6102. // relying on us setting vregs for them.
  6103. PendingExports.clear();
  6104. } else {
  6105. DAG.setRoot(Result.second);
  6106. }
  6107. if (EHPadBB) {
  6108. // Insert a label at the end of the invoke call to mark the try range. This
  6109. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6110. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6111. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6112. // Inform MachineModuleInfo of range.
  6113. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6114. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6115. // actually use outlined funclets and their LSDA info style.
  6116. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6117. assert(CLI.CS);
  6118. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6119. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6120. BeginLabel, EndLabel);
  6121. } else if (!isScopedEHPersonality(Pers)) {
  6122. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6123. }
  6124. }
  6125. return Result;
  6126. }
  6127. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6128. bool isTailCall,
  6129. const BasicBlock *EHPadBB) {
  6130. auto &DL = DAG.getDataLayout();
  6131. FunctionType *FTy = CS.getFunctionType();
  6132. Type *RetTy = CS.getType();
  6133. TargetLowering::ArgListTy Args;
  6134. Args.reserve(CS.arg_size());
  6135. const Value *SwiftErrorVal = nullptr;
  6136. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6137. // We can't tail call inside a function with a swifterror argument. Lowering
  6138. // does not support this yet. It would have to move into the swifterror
  6139. // register before the call.
  6140. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6141. if (TLI.supportSwiftError() &&
  6142. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6143. isTailCall = false;
  6144. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6145. i != e; ++i) {
  6146. TargetLowering::ArgListEntry Entry;
  6147. const Value *V = *i;
  6148. // Skip empty types
  6149. if (V->getType()->isEmptyTy())
  6150. continue;
  6151. SDValue ArgNode = getValue(V);
  6152. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6153. Entry.setAttributes(&CS, i - CS.arg_begin());
  6154. // Use swifterror virtual register as input to the call.
  6155. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6156. SwiftErrorVal = V;
  6157. // We find the virtual register for the actual swifterror argument.
  6158. // Instead of using the Value, we use the virtual register instead.
  6159. Entry.Node = DAG.getRegister(FuncInfo
  6160. .getOrCreateSwiftErrorVRegUseAt(
  6161. CS.getInstruction(), FuncInfo.MBB, V)
  6162. .first,
  6163. EVT(TLI.getPointerTy(DL)));
  6164. }
  6165. Args.push_back(Entry);
  6166. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6167. // might point to function-local memory), we can't meaningfully tail-call.
  6168. if (Entry.IsSRet && isa<Instruction>(V))
  6169. isTailCall = false;
  6170. }
  6171. // Check if target-independent constraints permit a tail call here.
  6172. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6173. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6174. isTailCall = false;
  6175. // Disable tail calls if there is an swifterror argument. Targets have not
  6176. // been updated to support tail calls.
  6177. if (TLI.supportSwiftError() && SwiftErrorVal)
  6178. isTailCall = false;
  6179. TargetLowering::CallLoweringInfo CLI(DAG);
  6180. CLI.setDebugLoc(getCurSDLoc())
  6181. .setChain(getRoot())
  6182. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6183. .setTailCall(isTailCall)
  6184. .setConvergent(CS.isConvergent());
  6185. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6186. if (Result.first.getNode()) {
  6187. const Instruction *Inst = CS.getInstruction();
  6188. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6189. setValue(Inst, Result.first);
  6190. }
  6191. // The last element of CLI.InVals has the SDValue for swifterror return.
  6192. // Here we copy it to a virtual register and update SwiftErrorMap for
  6193. // book-keeping.
  6194. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6195. // Get the last element of InVals.
  6196. SDValue Src = CLI.InVals.back();
  6197. unsigned VReg; bool CreatedVReg;
  6198. std::tie(VReg, CreatedVReg) =
  6199. FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
  6200. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6201. // We update the virtual register for the actual swifterror argument.
  6202. if (CreatedVReg)
  6203. FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
  6204. DAG.setRoot(CopyNode);
  6205. }
  6206. }
  6207. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6208. SelectionDAGBuilder &Builder) {
  6209. // Check to see if this load can be trivially constant folded, e.g. if the
  6210. // input is from a string literal.
  6211. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6212. // Cast pointer to the type we really want to load.
  6213. Type *LoadTy =
  6214. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6215. if (LoadVT.isVector())
  6216. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6217. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6218. PointerType::getUnqual(LoadTy));
  6219. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6220. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6221. return Builder.getValue(LoadCst);
  6222. }
  6223. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6224. // still constant memory, the input chain can be the entry node.
  6225. SDValue Root;
  6226. bool ConstantMemory = false;
  6227. // Do not serialize (non-volatile) loads of constant memory with anything.
  6228. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6229. Root = Builder.DAG.getEntryNode();
  6230. ConstantMemory = true;
  6231. } else {
  6232. // Do not serialize non-volatile loads against each other.
  6233. Root = Builder.DAG.getRoot();
  6234. }
  6235. SDValue Ptr = Builder.getValue(PtrVal);
  6236. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6237. Ptr, MachinePointerInfo(PtrVal),
  6238. /* Alignment = */ 1);
  6239. if (!ConstantMemory)
  6240. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6241. return LoadVal;
  6242. }
  6243. /// Record the value for an instruction that produces an integer result,
  6244. /// converting the type where necessary.
  6245. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6246. SDValue Value,
  6247. bool IsSigned) {
  6248. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6249. I.getType(), true);
  6250. if (IsSigned)
  6251. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6252. else
  6253. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6254. setValue(&I, Value);
  6255. }
  6256. /// See if we can lower a memcmp call into an optimized form. If so, return
  6257. /// true and lower it. Otherwise return false, and it will be lowered like a
  6258. /// normal call.
  6259. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6260. /// correct prototype.
  6261. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6262. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6263. const Value *Size = I.getArgOperand(2);
  6264. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6265. if (CSize && CSize->getZExtValue() == 0) {
  6266. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6267. I.getType(), true);
  6268. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6269. return true;
  6270. }
  6271. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6272. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6273. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6274. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6275. if (Res.first.getNode()) {
  6276. processIntegerCallValue(I, Res.first, true);
  6277. PendingLoads.push_back(Res.second);
  6278. return true;
  6279. }
  6280. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6281. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6282. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6283. return false;
  6284. // If the target has a fast compare for the given size, it will return a
  6285. // preferred load type for that size. Require that the load VT is legal and
  6286. // that the target supports unaligned loads of that type. Otherwise, return
  6287. // INVALID.
  6288. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6289. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6290. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6291. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6292. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6293. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6294. // TODO: Check alignment of src and dest ptrs.
  6295. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6296. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6297. if (!TLI.isTypeLegal(LVT) ||
  6298. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6299. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6300. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6301. }
  6302. return LVT;
  6303. };
  6304. // This turns into unaligned loads. We only do this if the target natively
  6305. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6306. // we'll only produce a small number of byte loads.
  6307. MVT LoadVT;
  6308. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6309. switch (NumBitsToCompare) {
  6310. default:
  6311. return false;
  6312. case 16:
  6313. LoadVT = MVT::i16;
  6314. break;
  6315. case 32:
  6316. LoadVT = MVT::i32;
  6317. break;
  6318. case 64:
  6319. case 128:
  6320. case 256:
  6321. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6322. break;
  6323. }
  6324. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6325. return false;
  6326. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6327. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6328. // Bitcast to a wide integer type if the loads are vectors.
  6329. if (LoadVT.isVector()) {
  6330. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6331. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6332. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6333. }
  6334. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6335. processIntegerCallValue(I, Cmp, false);
  6336. return true;
  6337. }
  6338. /// See if we can lower a memchr call into an optimized form. If so, return
  6339. /// true and lower it. Otherwise return false, and it will be lowered like a
  6340. /// normal call.
  6341. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6342. /// correct prototype.
  6343. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6344. const Value *Src = I.getArgOperand(0);
  6345. const Value *Char = I.getArgOperand(1);
  6346. const Value *Length = I.getArgOperand(2);
  6347. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6348. std::pair<SDValue, SDValue> Res =
  6349. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6350. getValue(Src), getValue(Char), getValue(Length),
  6351. MachinePointerInfo(Src));
  6352. if (Res.first.getNode()) {
  6353. setValue(&I, Res.first);
  6354. PendingLoads.push_back(Res.second);
  6355. return true;
  6356. }
  6357. return false;
  6358. }
  6359. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6360. /// true and lower it. Otherwise return false, and it will be lowered like a
  6361. /// normal call.
  6362. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6363. /// correct prototype.
  6364. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6365. SDValue Dst = getValue(I.getArgOperand(0));
  6366. SDValue Src = getValue(I.getArgOperand(1));
  6367. SDValue Size = getValue(I.getArgOperand(2));
  6368. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6369. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6370. unsigned Align = std::min(DstAlign, SrcAlign);
  6371. if (Align == 0) // Alignment of one or both could not be inferred.
  6372. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6373. bool isVol = false;
  6374. SDLoc sdl = getCurSDLoc();
  6375. // In the mempcpy context we need to pass in a false value for isTailCall
  6376. // because the return pointer needs to be adjusted by the size of
  6377. // the copied memory.
  6378. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6379. false, /*isTailCall=*/false,
  6380. MachinePointerInfo(I.getArgOperand(0)),
  6381. MachinePointerInfo(I.getArgOperand(1)));
  6382. assert(MC.getNode() != nullptr &&
  6383. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6384. DAG.setRoot(MC);
  6385. // Check if Size needs to be truncated or extended.
  6386. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6387. // Adjust return pointer to point just past the last dst byte.
  6388. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6389. Dst, Size);
  6390. setValue(&I, DstPlusSize);
  6391. return true;
  6392. }
  6393. /// See if we can lower a strcpy call into an optimized form. If so, return
  6394. /// true and lower it, otherwise return false and it will be lowered like a
  6395. /// normal call.
  6396. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6397. /// correct prototype.
  6398. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6399. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6400. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6401. std::pair<SDValue, SDValue> Res =
  6402. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6403. getValue(Arg0), getValue(Arg1),
  6404. MachinePointerInfo(Arg0),
  6405. MachinePointerInfo(Arg1), isStpcpy);
  6406. if (Res.first.getNode()) {
  6407. setValue(&I, Res.first);
  6408. DAG.setRoot(Res.second);
  6409. return true;
  6410. }
  6411. return false;
  6412. }
  6413. /// See if we can lower a strcmp call into an optimized form. If so, return
  6414. /// true and lower it, otherwise return false and it will be lowered like a
  6415. /// normal call.
  6416. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6417. /// correct prototype.
  6418. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6419. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6420. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6421. std::pair<SDValue, SDValue> Res =
  6422. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6423. getValue(Arg0), getValue(Arg1),
  6424. MachinePointerInfo(Arg0),
  6425. MachinePointerInfo(Arg1));
  6426. if (Res.first.getNode()) {
  6427. processIntegerCallValue(I, Res.first, true);
  6428. PendingLoads.push_back(Res.second);
  6429. return true;
  6430. }
  6431. return false;
  6432. }
  6433. /// See if we can lower a strlen call into an optimized form. If so, return
  6434. /// true and lower it, otherwise return false and it will be lowered like a
  6435. /// normal call.
  6436. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6437. /// correct prototype.
  6438. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6439. const Value *Arg0 = I.getArgOperand(0);
  6440. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6441. std::pair<SDValue, SDValue> Res =
  6442. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6443. getValue(Arg0), MachinePointerInfo(Arg0));
  6444. if (Res.first.getNode()) {
  6445. processIntegerCallValue(I, Res.first, false);
  6446. PendingLoads.push_back(Res.second);
  6447. return true;
  6448. }
  6449. return false;
  6450. }
  6451. /// See if we can lower a strnlen call into an optimized form. If so, return
  6452. /// true and lower it, otherwise return false and it will be lowered like a
  6453. /// normal call.
  6454. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6455. /// correct prototype.
  6456. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6457. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6458. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6459. std::pair<SDValue, SDValue> Res =
  6460. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6461. getValue(Arg0), getValue(Arg1),
  6462. MachinePointerInfo(Arg0));
  6463. if (Res.first.getNode()) {
  6464. processIntegerCallValue(I, Res.first, false);
  6465. PendingLoads.push_back(Res.second);
  6466. return true;
  6467. }
  6468. return false;
  6469. }
  6470. /// See if we can lower a unary floating-point operation into an SDNode with
  6471. /// the specified Opcode. If so, return true and lower it, otherwise return
  6472. /// false and it will be lowered like a normal call.
  6473. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6474. /// correct prototype.
  6475. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6476. unsigned Opcode) {
  6477. // We already checked this call's prototype; verify it doesn't modify errno.
  6478. if (!I.onlyReadsMemory())
  6479. return false;
  6480. SDValue Tmp = getValue(I.getArgOperand(0));
  6481. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6482. return true;
  6483. }
  6484. /// See if we can lower a binary floating-point operation into an SDNode with
  6485. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6486. /// false, and it will be lowered like a normal call.
  6487. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6488. /// correct prototype.
  6489. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6490. unsigned Opcode) {
  6491. // We already checked this call's prototype; verify it doesn't modify errno.
  6492. if (!I.onlyReadsMemory())
  6493. return false;
  6494. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6495. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6496. EVT VT = Tmp0.getValueType();
  6497. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6498. return true;
  6499. }
  6500. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6501. // Handle inline assembly differently.
  6502. if (isa<InlineAsm>(I.getCalledValue())) {
  6503. visitInlineAsm(&I);
  6504. return;
  6505. }
  6506. const char *RenameFn = nullptr;
  6507. if (Function *F = I.getCalledFunction()) {
  6508. if (F->isDeclaration()) {
  6509. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6510. unsigned IID = F->getIntrinsicID();
  6511. if (!IID)
  6512. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6513. IID = II->getIntrinsicID(F);
  6514. if (IID) {
  6515. RenameFn = visitIntrinsicCall(I, IID);
  6516. if (!RenameFn)
  6517. return;
  6518. }
  6519. }
  6520. // Check for well-known libc/libm calls. If the function is internal, it
  6521. // can't be a library call. Don't do the check if marked as nobuiltin for
  6522. // some reason or the call site requires strict floating point semantics.
  6523. LibFunc Func;
  6524. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6525. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6526. LibInfo->hasOptimizedCodeGen(Func)) {
  6527. switch (Func) {
  6528. default: break;
  6529. case LibFunc_copysign:
  6530. case LibFunc_copysignf:
  6531. case LibFunc_copysignl:
  6532. // We already checked this call's prototype; verify it doesn't modify
  6533. // errno.
  6534. if (I.onlyReadsMemory()) {
  6535. SDValue LHS = getValue(I.getArgOperand(0));
  6536. SDValue RHS = getValue(I.getArgOperand(1));
  6537. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6538. LHS.getValueType(), LHS, RHS));
  6539. return;
  6540. }
  6541. break;
  6542. case LibFunc_fabs:
  6543. case LibFunc_fabsf:
  6544. case LibFunc_fabsl:
  6545. if (visitUnaryFloatCall(I, ISD::FABS))
  6546. return;
  6547. break;
  6548. case LibFunc_fmin:
  6549. case LibFunc_fminf:
  6550. case LibFunc_fminl:
  6551. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6552. return;
  6553. break;
  6554. case LibFunc_fmax:
  6555. case LibFunc_fmaxf:
  6556. case LibFunc_fmaxl:
  6557. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6558. return;
  6559. break;
  6560. case LibFunc_sin:
  6561. case LibFunc_sinf:
  6562. case LibFunc_sinl:
  6563. if (visitUnaryFloatCall(I, ISD::FSIN))
  6564. return;
  6565. break;
  6566. case LibFunc_cos:
  6567. case LibFunc_cosf:
  6568. case LibFunc_cosl:
  6569. if (visitUnaryFloatCall(I, ISD::FCOS))
  6570. return;
  6571. break;
  6572. case LibFunc_sqrt:
  6573. case LibFunc_sqrtf:
  6574. case LibFunc_sqrtl:
  6575. case LibFunc_sqrt_finite:
  6576. case LibFunc_sqrtf_finite:
  6577. case LibFunc_sqrtl_finite:
  6578. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6579. return;
  6580. break;
  6581. case LibFunc_floor:
  6582. case LibFunc_floorf:
  6583. case LibFunc_floorl:
  6584. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6585. return;
  6586. break;
  6587. case LibFunc_nearbyint:
  6588. case LibFunc_nearbyintf:
  6589. case LibFunc_nearbyintl:
  6590. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6591. return;
  6592. break;
  6593. case LibFunc_ceil:
  6594. case LibFunc_ceilf:
  6595. case LibFunc_ceill:
  6596. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6597. return;
  6598. break;
  6599. case LibFunc_rint:
  6600. case LibFunc_rintf:
  6601. case LibFunc_rintl:
  6602. if (visitUnaryFloatCall(I, ISD::FRINT))
  6603. return;
  6604. break;
  6605. case LibFunc_round:
  6606. case LibFunc_roundf:
  6607. case LibFunc_roundl:
  6608. if (visitUnaryFloatCall(I, ISD::FROUND))
  6609. return;
  6610. break;
  6611. case LibFunc_trunc:
  6612. case LibFunc_truncf:
  6613. case LibFunc_truncl:
  6614. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6615. return;
  6616. break;
  6617. case LibFunc_log2:
  6618. case LibFunc_log2f:
  6619. case LibFunc_log2l:
  6620. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6621. return;
  6622. break;
  6623. case LibFunc_exp2:
  6624. case LibFunc_exp2f:
  6625. case LibFunc_exp2l:
  6626. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6627. return;
  6628. break;
  6629. case LibFunc_memcmp:
  6630. if (visitMemCmpCall(I))
  6631. return;
  6632. break;
  6633. case LibFunc_mempcpy:
  6634. if (visitMemPCpyCall(I))
  6635. return;
  6636. break;
  6637. case LibFunc_memchr:
  6638. if (visitMemChrCall(I))
  6639. return;
  6640. break;
  6641. case LibFunc_strcpy:
  6642. if (visitStrCpyCall(I, false))
  6643. return;
  6644. break;
  6645. case LibFunc_stpcpy:
  6646. if (visitStrCpyCall(I, true))
  6647. return;
  6648. break;
  6649. case LibFunc_strcmp:
  6650. if (visitStrCmpCall(I))
  6651. return;
  6652. break;
  6653. case LibFunc_strlen:
  6654. if (visitStrLenCall(I))
  6655. return;
  6656. break;
  6657. case LibFunc_strnlen:
  6658. if (visitStrNLenCall(I))
  6659. return;
  6660. break;
  6661. }
  6662. }
  6663. }
  6664. SDValue Callee;
  6665. if (!RenameFn)
  6666. Callee = getValue(I.getCalledValue());
  6667. else
  6668. Callee = DAG.getExternalSymbol(
  6669. RenameFn,
  6670. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6671. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6672. // have to do anything here to lower funclet bundles.
  6673. assert(!I.hasOperandBundlesOtherThan(
  6674. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6675. "Cannot lower calls with arbitrary operand bundles!");
  6676. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6677. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6678. else
  6679. // Check if we can potentially perform a tail call. More detailed checking
  6680. // is be done within LowerCallTo, after more information about the call is
  6681. // known.
  6682. LowerCallTo(&I, Callee, I.isTailCall());
  6683. }
  6684. namespace {
  6685. /// AsmOperandInfo - This contains information for each constraint that we are
  6686. /// lowering.
  6687. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6688. public:
  6689. /// CallOperand - If this is the result output operand or a clobber
  6690. /// this is null, otherwise it is the incoming operand to the CallInst.
  6691. /// This gets modified as the asm is processed.
  6692. SDValue CallOperand;
  6693. /// AssignedRegs - If this is a register or register class operand, this
  6694. /// contains the set of register corresponding to the operand.
  6695. RegsForValue AssignedRegs;
  6696. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6697. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6698. }
  6699. /// Whether or not this operand accesses memory
  6700. bool hasMemory(const TargetLowering &TLI) const {
  6701. // Indirect operand accesses access memory.
  6702. if (isIndirect)
  6703. return true;
  6704. for (const auto &Code : Codes)
  6705. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6706. return true;
  6707. return false;
  6708. }
  6709. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6710. /// corresponds to. If there is no Value* for this operand, it returns
  6711. /// MVT::Other.
  6712. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6713. const DataLayout &DL) const {
  6714. if (!CallOperandVal) return MVT::Other;
  6715. if (isa<BasicBlock>(CallOperandVal))
  6716. return TLI.getPointerTy(DL);
  6717. llvm::Type *OpTy = CallOperandVal->getType();
  6718. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6719. // If this is an indirect operand, the operand is a pointer to the
  6720. // accessed type.
  6721. if (isIndirect) {
  6722. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6723. if (!PtrTy)
  6724. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6725. OpTy = PtrTy->getElementType();
  6726. }
  6727. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6728. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6729. if (STy->getNumElements() == 1)
  6730. OpTy = STy->getElementType(0);
  6731. // If OpTy is not a single value, it may be a struct/union that we
  6732. // can tile with integers.
  6733. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6734. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6735. switch (BitSize) {
  6736. default: break;
  6737. case 1:
  6738. case 8:
  6739. case 16:
  6740. case 32:
  6741. case 64:
  6742. case 128:
  6743. OpTy = IntegerType::get(Context, BitSize);
  6744. break;
  6745. }
  6746. }
  6747. return TLI.getValueType(DL, OpTy, true);
  6748. }
  6749. };
  6750. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6751. } // end anonymous namespace
  6752. /// Make sure that the output operand \p OpInfo and its corresponding input
  6753. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6754. /// out).
  6755. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6756. SDISelAsmOperandInfo &MatchingOpInfo,
  6757. SelectionDAG &DAG) {
  6758. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6759. return;
  6760. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6761. const auto &TLI = DAG.getTargetLoweringInfo();
  6762. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6763. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6764. OpInfo.ConstraintVT);
  6765. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6766. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6767. MatchingOpInfo.ConstraintVT);
  6768. if ((OpInfo.ConstraintVT.isInteger() !=
  6769. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6770. (MatchRC.second != InputRC.second)) {
  6771. // FIXME: error out in a more elegant fashion
  6772. report_fatal_error("Unsupported asm: input constraint"
  6773. " with a matching output constraint of"
  6774. " incompatible type!");
  6775. }
  6776. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6777. }
  6778. /// Get a direct memory input to behave well as an indirect operand.
  6779. /// This may introduce stores, hence the need for a \p Chain.
  6780. /// \return The (possibly updated) chain.
  6781. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6782. SDISelAsmOperandInfo &OpInfo,
  6783. SelectionDAG &DAG) {
  6784. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6785. // If we don't have an indirect input, put it in the constpool if we can,
  6786. // otherwise spill it to a stack slot.
  6787. // TODO: This isn't quite right. We need to handle these according to
  6788. // the addressing mode that the constraint wants. Also, this may take
  6789. // an additional register for the computation and we don't want that
  6790. // either.
  6791. // If the operand is a float, integer, or vector constant, spill to a
  6792. // constant pool entry to get its address.
  6793. const Value *OpVal = OpInfo.CallOperandVal;
  6794. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6795. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6796. OpInfo.CallOperand = DAG.getConstantPool(
  6797. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6798. return Chain;
  6799. }
  6800. // Otherwise, create a stack slot and emit a store to it before the asm.
  6801. Type *Ty = OpVal->getType();
  6802. auto &DL = DAG.getDataLayout();
  6803. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6804. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6805. MachineFunction &MF = DAG.getMachineFunction();
  6806. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6807. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6808. Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6809. MachinePointerInfo::getFixedStack(MF, SSFI));
  6810. OpInfo.CallOperand = StackSlot;
  6811. return Chain;
  6812. }
  6813. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6814. /// specified operand. We prefer to assign virtual registers, to allow the
  6815. /// register allocator to handle the assignment process. However, if the asm
  6816. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6817. /// allocation. This produces generally horrible, but correct, code.
  6818. ///
  6819. /// OpInfo describes the operand
  6820. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6821. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6822. SDISelAsmOperandInfo &OpInfo,
  6823. SDISelAsmOperandInfo &RefOpInfo) {
  6824. LLVMContext &Context = *DAG.getContext();
  6825. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6826. MachineFunction &MF = DAG.getMachineFunction();
  6827. SmallVector<unsigned, 4> Regs;
  6828. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6829. // No work to do for memory operations.
  6830. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6831. return;
  6832. // If this is a constraint for a single physreg, or a constraint for a
  6833. // register class, find it.
  6834. unsigned AssignedReg;
  6835. const TargetRegisterClass *RC;
  6836. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6837. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6838. // RC is unset only on failure. Return immediately.
  6839. if (!RC)
  6840. return;
  6841. // Get the actual register value type. This is important, because the user
  6842. // may have asked for (e.g.) the AX register in i32 type. We need to
  6843. // remember that AX is actually i16 to get the right extension.
  6844. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6845. if (OpInfo.ConstraintVT != MVT::Other) {
  6846. // If this is an FP operand in an integer register (or visa versa), or more
  6847. // generally if the operand value disagrees with the register class we plan
  6848. // to stick it in, fix the operand type.
  6849. //
  6850. // If this is an input value, the bitcast to the new type is done now.
  6851. // Bitcast for output value is done at the end of visitInlineAsm().
  6852. if ((OpInfo.Type == InlineAsm::isOutput ||
  6853. OpInfo.Type == InlineAsm::isInput) &&
  6854. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  6855. // Try to convert to the first EVT that the reg class contains. If the
  6856. // types are identical size, use a bitcast to convert (e.g. two differing
  6857. // vector types). Note: output bitcast is done at the end of
  6858. // visitInlineAsm().
  6859. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  6860. // Exclude indirect inputs while they are unsupported because the code
  6861. // to perform the load is missing and thus OpInfo.CallOperand still
  6862. // refers to the input address rather than the pointed-to value.
  6863. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  6864. OpInfo.CallOperand =
  6865. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6866. OpInfo.ConstraintVT = RegVT;
  6867. // If the operand is an FP value and we want it in integer registers,
  6868. // use the corresponding integer type. This turns an f64 value into
  6869. // i64, which can be passed with two i32 values on a 32-bit machine.
  6870. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6871. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6872. if (OpInfo.Type == InlineAsm::isInput)
  6873. OpInfo.CallOperand =
  6874. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  6875. OpInfo.ConstraintVT = VT;
  6876. }
  6877. }
  6878. }
  6879. // No need to allocate a matching input constraint since the constraint it's
  6880. // matching to has already been allocated.
  6881. if (OpInfo.isMatchingInputConstraint())
  6882. return;
  6883. EVT ValueVT = OpInfo.ConstraintVT;
  6884. if (OpInfo.ConstraintVT == MVT::Other)
  6885. ValueVT = RegVT;
  6886. // Initialize NumRegs.
  6887. unsigned NumRegs = 1;
  6888. if (OpInfo.ConstraintVT != MVT::Other)
  6889. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6890. // If this is a constraint for a specific physical register, like {r17},
  6891. // assign it now.
  6892. // If this associated to a specific register, initialize iterator to correct
  6893. // place. If virtual, make sure we have enough registers
  6894. // Initialize iterator if necessary
  6895. TargetRegisterClass::iterator I = RC->begin();
  6896. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6897. // Do not check for single registers.
  6898. if (AssignedReg) {
  6899. for (; *I != AssignedReg; ++I)
  6900. assert(I != RC->end() && "AssignedReg should be member of RC");
  6901. }
  6902. for (; NumRegs; --NumRegs, ++I) {
  6903. assert(I != RC->end() && "Ran out of registers to allocate!");
  6904. auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
  6905. Regs.push_back(R);
  6906. }
  6907. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  6908. }
  6909. static unsigned
  6910. findMatchingInlineAsmOperand(unsigned OperandNo,
  6911. const std::vector<SDValue> &AsmNodeOperands) {
  6912. // Scan until we find the definition we already emitted of this operand.
  6913. unsigned CurOp = InlineAsm::Op_FirstOperand;
  6914. for (; OperandNo; --OperandNo) {
  6915. // Advance to the next operand.
  6916. unsigned OpFlag =
  6917. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  6918. assert((InlineAsm::isRegDefKind(OpFlag) ||
  6919. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  6920. InlineAsm::isMemKind(OpFlag)) &&
  6921. "Skipped past definitions?");
  6922. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  6923. }
  6924. return CurOp;
  6925. }
  6926. namespace {
  6927. class ExtraFlags {
  6928. unsigned Flags = 0;
  6929. public:
  6930. explicit ExtraFlags(ImmutableCallSite CS) {
  6931. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6932. if (IA->hasSideEffects())
  6933. Flags |= InlineAsm::Extra_HasSideEffects;
  6934. if (IA->isAlignStack())
  6935. Flags |= InlineAsm::Extra_IsAlignStack;
  6936. if (CS.isConvergent())
  6937. Flags |= InlineAsm::Extra_IsConvergent;
  6938. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  6939. }
  6940. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  6941. // Ideally, we would only check against memory constraints. However, the
  6942. // meaning of an Other constraint can be target-specific and we can't easily
  6943. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  6944. // for Other constraints as well.
  6945. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  6946. OpInfo.ConstraintType == TargetLowering::C_Other) {
  6947. if (OpInfo.Type == InlineAsm::isInput)
  6948. Flags |= InlineAsm::Extra_MayLoad;
  6949. else if (OpInfo.Type == InlineAsm::isOutput)
  6950. Flags |= InlineAsm::Extra_MayStore;
  6951. else if (OpInfo.Type == InlineAsm::isClobber)
  6952. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  6953. }
  6954. }
  6955. unsigned get() const { return Flags; }
  6956. };
  6957. } // end anonymous namespace
  6958. /// visitInlineAsm - Handle a call to an InlineAsm object.
  6959. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  6960. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  6961. /// ConstraintOperands - Information about all of the constraints.
  6962. SDISelAsmOperandInfoVector ConstraintOperands;
  6963. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6964. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  6965. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  6966. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  6967. // AsmDialect, MayLoad, MayStore).
  6968. bool HasSideEffect = IA->hasSideEffects();
  6969. ExtraFlags ExtraInfo(CS);
  6970. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  6971. unsigned ResNo = 0; // ResNo - The result number of the next output.
  6972. for (auto &T : TargetConstraints) {
  6973. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  6974. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  6975. // Compute the value type for each operand.
  6976. if (OpInfo.Type == InlineAsm::isInput ||
  6977. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  6978. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  6979. // Process the call argument. BasicBlocks are labels, currently appearing
  6980. // only in asm's.
  6981. const Instruction *I = CS.getInstruction();
  6982. if (isa<CallBrInst>(I) &&
  6983. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  6984. cast<CallBrInst>(I)->getNumIndirectDests())) {
  6985. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  6986. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  6987. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  6988. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  6989. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  6990. } else {
  6991. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  6992. }
  6993. OpInfo.ConstraintVT =
  6994. OpInfo
  6995. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  6996. .getSimpleVT();
  6997. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  6998. // The return value of the call is this value. As such, there is no
  6999. // corresponding argument.
  7000. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7001. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7002. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7003. DAG.getDataLayout(), STy->getElementType(ResNo));
  7004. } else {
  7005. assert(ResNo == 0 && "Asm only has one result!");
  7006. OpInfo.ConstraintVT =
  7007. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7008. }
  7009. ++ResNo;
  7010. } else {
  7011. OpInfo.ConstraintVT = MVT::Other;
  7012. }
  7013. if (!HasSideEffect)
  7014. HasSideEffect = OpInfo.hasMemory(TLI);
  7015. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7016. // FIXME: Could we compute this on OpInfo rather than T?
  7017. // Compute the constraint code and ConstraintType to use.
  7018. TLI.ComputeConstraintToUse(T, SDValue());
  7019. ExtraInfo.update(T);
  7020. }
  7021. // We won't need to flush pending loads if this asm doesn't touch
  7022. // memory and is nonvolatile.
  7023. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7024. // Second pass over the constraints: compute which constraint option to use.
  7025. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7026. // If this is an output operand with a matching input operand, look up the
  7027. // matching input. If their types mismatch, e.g. one is an integer, the
  7028. // other is floating point, or their sizes are different, flag it as an
  7029. // error.
  7030. if (OpInfo.hasMatchingInput()) {
  7031. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7032. patchMatchingInput(OpInfo, Input, DAG);
  7033. }
  7034. // Compute the constraint code and ConstraintType to use.
  7035. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7036. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7037. OpInfo.Type == InlineAsm::isClobber)
  7038. continue;
  7039. // If this is a memory input, and if the operand is not indirect, do what we
  7040. // need to provide an address for the memory input.
  7041. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7042. !OpInfo.isIndirect) {
  7043. assert((OpInfo.isMultipleAlternative ||
  7044. (OpInfo.Type == InlineAsm::isInput)) &&
  7045. "Can only indirectify direct input operands!");
  7046. // Memory operands really want the address of the value.
  7047. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7048. // There is no longer a Value* corresponding to this operand.
  7049. OpInfo.CallOperandVal = nullptr;
  7050. // It is now an indirect operand.
  7051. OpInfo.isIndirect = true;
  7052. }
  7053. }
  7054. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7055. std::vector<SDValue> AsmNodeOperands;
  7056. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7057. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7058. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7059. // If we have a !srcloc metadata node associated with it, we want to attach
  7060. // this to the ultimately generated inline asm machineinstr. To do this, we
  7061. // pass in the third operand as this (potentially null) inline asm MDNode.
  7062. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7063. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7064. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7065. // bits as operand 3.
  7066. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7067. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7068. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7069. // this, assign virtual and physical registers for inputs and otput.
  7070. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7071. // Assign Registers.
  7072. SDISelAsmOperandInfo &RefOpInfo =
  7073. OpInfo.isMatchingInputConstraint()
  7074. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7075. : OpInfo;
  7076. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7077. switch (OpInfo.Type) {
  7078. case InlineAsm::isOutput:
  7079. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7080. (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7081. OpInfo.isIndirect)) {
  7082. unsigned ConstraintID =
  7083. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7084. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7085. "Failed to convert memory constraint code to constraint id.");
  7086. // Add information to the INLINEASM node to know about this output.
  7087. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7088. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7089. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7090. MVT::i32));
  7091. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7092. break;
  7093. } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
  7094. !OpInfo.isIndirect) ||
  7095. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7096. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7097. // Otherwise, this outputs to a register (directly for C_Register /
  7098. // C_RegisterClass, and a target-defined fashion for C_Other). Find a
  7099. // register that we can use.
  7100. if (OpInfo.AssignedRegs.Regs.empty()) {
  7101. emitInlineAsmError(
  7102. CS, "couldn't allocate output register for constraint '" +
  7103. Twine(OpInfo.ConstraintCode) + "'");
  7104. return;
  7105. }
  7106. // Add information to the INLINEASM node to know that this register is
  7107. // set.
  7108. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7109. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7110. : InlineAsm::Kind_RegDef,
  7111. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7112. }
  7113. break;
  7114. case InlineAsm::isInput: {
  7115. SDValue InOperandVal = OpInfo.CallOperand;
  7116. if (OpInfo.isMatchingInputConstraint()) {
  7117. // If this is required to match an output register we have already set,
  7118. // just use its register.
  7119. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7120. AsmNodeOperands);
  7121. unsigned OpFlag =
  7122. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7123. if (InlineAsm::isRegDefKind(OpFlag) ||
  7124. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7125. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7126. if (OpInfo.isIndirect) {
  7127. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7128. emitInlineAsmError(CS, "inline asm not supported yet:"
  7129. " don't know how to handle tied "
  7130. "indirect register inputs");
  7131. return;
  7132. }
  7133. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7134. SmallVector<unsigned, 4> Regs;
  7135. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7136. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7137. MachineRegisterInfo &RegInfo =
  7138. DAG.getMachineFunction().getRegInfo();
  7139. for (unsigned i = 0; i != NumRegs; ++i)
  7140. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7141. } else {
  7142. emitInlineAsmError(CS, "inline asm error: This value type register "
  7143. "class is not natively supported!");
  7144. return;
  7145. }
  7146. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7147. SDLoc dl = getCurSDLoc();
  7148. // Use the produced MatchedRegs object to
  7149. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7150. CS.getInstruction());
  7151. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7152. true, OpInfo.getMatchedOperand(), dl,
  7153. DAG, AsmNodeOperands);
  7154. break;
  7155. }
  7156. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7157. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7158. "Unexpected number of operands");
  7159. // Add information to the INLINEASM node to know about this input.
  7160. // See InlineAsm.h isUseOperandTiedToDef.
  7161. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7162. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7163. OpInfo.getMatchedOperand());
  7164. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7165. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7166. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7167. break;
  7168. }
  7169. // Treat indirect 'X' constraint as memory.
  7170. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7171. OpInfo.isIndirect)
  7172. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7173. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  7174. std::vector<SDValue> Ops;
  7175. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7176. Ops, DAG);
  7177. if (Ops.empty()) {
  7178. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7179. Twine(OpInfo.ConstraintCode) + "'");
  7180. return;
  7181. }
  7182. // Add information to the INLINEASM node to know about this input.
  7183. unsigned ResOpType =
  7184. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7185. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7186. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7187. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7188. break;
  7189. }
  7190. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7191. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7192. assert(InOperandVal.getValueType() ==
  7193. TLI.getPointerTy(DAG.getDataLayout()) &&
  7194. "Memory operands expect pointer values");
  7195. unsigned ConstraintID =
  7196. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7197. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7198. "Failed to convert memory constraint code to constraint id.");
  7199. // Add information to the INLINEASM node to know about this input.
  7200. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7201. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7202. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7203. getCurSDLoc(),
  7204. MVT::i32));
  7205. AsmNodeOperands.push_back(InOperandVal);
  7206. break;
  7207. }
  7208. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7209. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  7210. "Unknown constraint type!");
  7211. // TODO: Support this.
  7212. if (OpInfo.isIndirect) {
  7213. emitInlineAsmError(
  7214. CS, "Don't know how to handle indirect register inputs yet "
  7215. "for constraint '" +
  7216. Twine(OpInfo.ConstraintCode) + "'");
  7217. return;
  7218. }
  7219. // Copy the input into the appropriate registers.
  7220. if (OpInfo.AssignedRegs.Regs.empty()) {
  7221. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7222. Twine(OpInfo.ConstraintCode) + "'");
  7223. return;
  7224. }
  7225. SDLoc dl = getCurSDLoc();
  7226. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7227. Chain, &Flag, CS.getInstruction());
  7228. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7229. dl, DAG, AsmNodeOperands);
  7230. break;
  7231. }
  7232. case InlineAsm::isClobber:
  7233. // Add the clobbered value to the operand list, so that the register
  7234. // allocator is aware that the physreg got clobbered.
  7235. if (!OpInfo.AssignedRegs.Regs.empty())
  7236. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7237. false, 0, getCurSDLoc(), DAG,
  7238. AsmNodeOperands);
  7239. break;
  7240. }
  7241. }
  7242. // Finish up input operands. Set the input chain and add the flag last.
  7243. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7244. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7245. unsigned ISDOpc = isa<CallBrInst>(CS.getInstruction()) ? ISD::INLINEASM_BR
  7246. : ISD::INLINEASM;
  7247. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7248. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7249. Flag = Chain.getValue(1);
  7250. // Do additional work to generate outputs.
  7251. SmallVector<EVT, 1> ResultVTs;
  7252. SmallVector<SDValue, 1> ResultValues;
  7253. SmallVector<SDValue, 8> OutChains;
  7254. llvm::Type *CSResultType = CS.getType();
  7255. ArrayRef<Type *> ResultTypes;
  7256. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7257. ResultTypes = StructResult->elements();
  7258. else if (!CSResultType->isVoidTy())
  7259. ResultTypes = makeArrayRef(CSResultType);
  7260. auto CurResultType = ResultTypes.begin();
  7261. auto handleRegAssign = [&](SDValue V) {
  7262. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7263. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7264. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7265. ++CurResultType;
  7266. // If the type of the inline asm call site return value is different but has
  7267. // same size as the type of the asm output bitcast it. One example of this
  7268. // is for vectors with different width / number of elements. This can
  7269. // happen for register classes that can contain multiple different value
  7270. // types. The preg or vreg allocated may not have the same VT as was
  7271. // expected.
  7272. //
  7273. // This can also happen for a return value that disagrees with the register
  7274. // class it is put in, eg. a double in a general-purpose register on a
  7275. // 32-bit machine.
  7276. if (ResultVT != V.getValueType() &&
  7277. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7278. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7279. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7280. V.getValueType().isInteger()) {
  7281. // If a result value was tied to an input value, the computed result
  7282. // may have a wider width than the expected result. Extract the
  7283. // relevant portion.
  7284. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7285. }
  7286. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7287. ResultVTs.push_back(ResultVT);
  7288. ResultValues.push_back(V);
  7289. };
  7290. // Deal with output operands.
  7291. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7292. if (OpInfo.Type == InlineAsm::isOutput) {
  7293. SDValue Val;
  7294. // Skip trivial output operands.
  7295. if (OpInfo.AssignedRegs.Regs.empty())
  7296. continue;
  7297. switch (OpInfo.ConstraintType) {
  7298. case TargetLowering::C_Register:
  7299. case TargetLowering::C_RegisterClass:
  7300. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7301. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7302. break;
  7303. case TargetLowering::C_Other:
  7304. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7305. OpInfo, DAG);
  7306. break;
  7307. case TargetLowering::C_Memory:
  7308. break; // Already handled.
  7309. case TargetLowering::C_Unknown:
  7310. assert(false && "Unexpected unknown constraint");
  7311. }
  7312. // Indirect output manifest as stores. Record output chains.
  7313. if (OpInfo.isIndirect) {
  7314. const Value *Ptr = OpInfo.CallOperandVal;
  7315. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7316. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7317. MachinePointerInfo(Ptr));
  7318. OutChains.push_back(Store);
  7319. } else {
  7320. // generate CopyFromRegs to associated registers.
  7321. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7322. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7323. for (const SDValue &V : Val->op_values())
  7324. handleRegAssign(V);
  7325. } else
  7326. handleRegAssign(Val);
  7327. }
  7328. }
  7329. }
  7330. // Set results.
  7331. if (!ResultValues.empty()) {
  7332. assert(CurResultType == ResultTypes.end() &&
  7333. "Mismatch in number of ResultTypes");
  7334. assert(ResultValues.size() == ResultTypes.size() &&
  7335. "Mismatch in number of output operands in asm result");
  7336. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7337. DAG.getVTList(ResultVTs), ResultValues);
  7338. setValue(CS.getInstruction(), V);
  7339. }
  7340. // Collect store chains.
  7341. if (!OutChains.empty())
  7342. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7343. // Only Update Root if inline assembly has a memory effect.
  7344. if (ResultValues.empty() || HasSideEffect || !OutChains.empty())
  7345. DAG.setRoot(Chain);
  7346. }
  7347. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7348. const Twine &Message) {
  7349. LLVMContext &Ctx = *DAG.getContext();
  7350. Ctx.emitError(CS.getInstruction(), Message);
  7351. // Make sure we leave the DAG in a valid state
  7352. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7353. SmallVector<EVT, 1> ValueVTs;
  7354. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7355. if (ValueVTs.empty())
  7356. return;
  7357. SmallVector<SDValue, 1> Ops;
  7358. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7359. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7360. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7361. }
  7362. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7363. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7364. MVT::Other, getRoot(),
  7365. getValue(I.getArgOperand(0)),
  7366. DAG.getSrcValue(I.getArgOperand(0))));
  7367. }
  7368. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7369. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7370. const DataLayout &DL = DAG.getDataLayout();
  7371. SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
  7372. getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
  7373. DAG.getSrcValue(I.getOperand(0)),
  7374. DL.getABITypeAlignment(I.getType()));
  7375. setValue(&I, V);
  7376. DAG.setRoot(V.getValue(1));
  7377. }
  7378. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7379. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7380. MVT::Other, getRoot(),
  7381. getValue(I.getArgOperand(0)),
  7382. DAG.getSrcValue(I.getArgOperand(0))));
  7383. }
  7384. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7385. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7386. MVT::Other, getRoot(),
  7387. getValue(I.getArgOperand(0)),
  7388. getValue(I.getArgOperand(1)),
  7389. DAG.getSrcValue(I.getArgOperand(0)),
  7390. DAG.getSrcValue(I.getArgOperand(1))));
  7391. }
  7392. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7393. const Instruction &I,
  7394. SDValue Op) {
  7395. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7396. if (!Range)
  7397. return Op;
  7398. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7399. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7400. return Op;
  7401. APInt Lo = CR.getUnsignedMin();
  7402. if (!Lo.isMinValue())
  7403. return Op;
  7404. APInt Hi = CR.getUnsignedMax();
  7405. unsigned Bits = std::max(Hi.getActiveBits(),
  7406. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7407. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7408. SDLoc SL = getCurSDLoc();
  7409. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7410. DAG.getValueType(SmallVT));
  7411. unsigned NumVals = Op.getNode()->getNumValues();
  7412. if (NumVals == 1)
  7413. return ZExt;
  7414. SmallVector<SDValue, 4> Ops;
  7415. Ops.push_back(ZExt);
  7416. for (unsigned I = 1; I != NumVals; ++I)
  7417. Ops.push_back(Op.getValue(I));
  7418. return DAG.getMergeValues(Ops, SL);
  7419. }
  7420. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7421. /// the call being lowered.
  7422. ///
  7423. /// This is a helper for lowering intrinsics that follow a target calling
  7424. /// convention or require stack pointer adjustment. Only a subset of the
  7425. /// intrinsic's operands need to participate in the calling convention.
  7426. void SelectionDAGBuilder::populateCallLoweringInfo(
  7427. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7428. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7429. bool IsPatchPoint) {
  7430. TargetLowering::ArgListTy Args;
  7431. Args.reserve(NumArgs);
  7432. // Populate the argument list.
  7433. // Attributes for args start at offset 1, after the return attribute.
  7434. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7435. ArgI != ArgE; ++ArgI) {
  7436. const Value *V = Call->getOperand(ArgI);
  7437. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7438. TargetLowering::ArgListEntry Entry;
  7439. Entry.Node = getValue(V);
  7440. Entry.Ty = V->getType();
  7441. Entry.setAttributes(Call, ArgI);
  7442. Args.push_back(Entry);
  7443. }
  7444. CLI.setDebugLoc(getCurSDLoc())
  7445. .setChain(getRoot())
  7446. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7447. .setDiscardResult(Call->use_empty())
  7448. .setIsPatchPoint(IsPatchPoint);
  7449. }
  7450. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7451. /// or patchpoint target node's operand list.
  7452. ///
  7453. /// Constants are converted to TargetConstants purely as an optimization to
  7454. /// avoid constant materialization and register allocation.
  7455. ///
  7456. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7457. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  7458. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7459. /// address materialization and register allocation, but may also be required
  7460. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7461. /// alloca in the entry block, then the runtime may assume that the alloca's
  7462. /// StackMap location can be read immediately after compilation and that the
  7463. /// location is valid at any point during execution (this is similar to the
  7464. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7465. /// only available in a register, then the runtime would need to trap when
  7466. /// execution reaches the StackMap in order to read the alloca's location.
  7467. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7468. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7469. SelectionDAGBuilder &Builder) {
  7470. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7471. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7472. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7473. Ops.push_back(
  7474. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7475. Ops.push_back(
  7476. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7477. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7478. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7479. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7480. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7481. } else
  7482. Ops.push_back(OpVal);
  7483. }
  7484. }
  7485. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7486. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7487. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7488. // [live variables...])
  7489. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7490. SDValue Chain, InFlag, Callee, NullPtr;
  7491. SmallVector<SDValue, 32> Ops;
  7492. SDLoc DL = getCurSDLoc();
  7493. Callee = getValue(CI.getCalledValue());
  7494. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7495. // The stackmap intrinsic only records the live variables (the arguemnts
  7496. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7497. // intrinsic, this won't be lowered to a function call. This means we don't
  7498. // have to worry about calling conventions and target specific lowering code.
  7499. // Instead we perform the call lowering right here.
  7500. //
  7501. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7502. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7503. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7504. //
  7505. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7506. InFlag = Chain.getValue(1);
  7507. // Add the <id> and <numBytes> constants.
  7508. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7509. Ops.push_back(DAG.getTargetConstant(
  7510. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7511. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7512. Ops.push_back(DAG.getTargetConstant(
  7513. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7514. MVT::i32));
  7515. // Push live variables for the stack map.
  7516. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7517. // We are not pushing any register mask info here on the operands list,
  7518. // because the stackmap doesn't clobber anything.
  7519. // Push the chain and the glue flag.
  7520. Ops.push_back(Chain);
  7521. Ops.push_back(InFlag);
  7522. // Create the STACKMAP node.
  7523. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7524. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7525. Chain = SDValue(SM, 0);
  7526. InFlag = Chain.getValue(1);
  7527. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7528. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7529. // Set the root to the target-lowered call chain.
  7530. DAG.setRoot(Chain);
  7531. // Inform the Frame Information that we have a stackmap in this function.
  7532. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7533. }
  7534. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7535. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7536. const BasicBlock *EHPadBB) {
  7537. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7538. // i32 <numBytes>,
  7539. // i8* <target>,
  7540. // i32 <numArgs>,
  7541. // [Args...],
  7542. // [live variables...])
  7543. CallingConv::ID CC = CS.getCallingConv();
  7544. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7545. bool HasDef = !CS->getType()->isVoidTy();
  7546. SDLoc dl = getCurSDLoc();
  7547. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7548. // Handle immediate and symbolic callees.
  7549. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7550. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7551. /*isTarget=*/true);
  7552. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7553. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7554. SDLoc(SymbolicCallee),
  7555. SymbolicCallee->getValueType(0));
  7556. // Get the real number of arguments participating in the call <numArgs>
  7557. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7558. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7559. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7560. // Intrinsics include all meta-operands up to but not including CC.
  7561. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7562. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7563. "Not enough arguments provided to the patchpoint intrinsic");
  7564. // For AnyRegCC the arguments are lowered later on manually.
  7565. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7566. Type *ReturnTy =
  7567. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7568. TargetLowering::CallLoweringInfo CLI(DAG);
  7569. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7570. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7571. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7572. SDNode *CallEnd = Result.second.getNode();
  7573. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7574. CallEnd = CallEnd->getOperand(0).getNode();
  7575. /// Get a call instruction from the call sequence chain.
  7576. /// Tail calls are not allowed.
  7577. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7578. "Expected a callseq node.");
  7579. SDNode *Call = CallEnd->getOperand(0).getNode();
  7580. bool HasGlue = Call->getGluedNode();
  7581. // Replace the target specific call node with the patchable intrinsic.
  7582. SmallVector<SDValue, 8> Ops;
  7583. // Add the <id> and <numBytes> constants.
  7584. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7585. Ops.push_back(DAG.getTargetConstant(
  7586. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7587. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7588. Ops.push_back(DAG.getTargetConstant(
  7589. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7590. MVT::i32));
  7591. // Add the callee.
  7592. Ops.push_back(Callee);
  7593. // Adjust <numArgs> to account for any arguments that have been passed on the
  7594. // stack instead.
  7595. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7596. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7597. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7598. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7599. // Add the calling convention
  7600. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7601. // Add the arguments we omitted previously. The register allocator should
  7602. // place these in any free register.
  7603. if (IsAnyRegCC)
  7604. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7605. Ops.push_back(getValue(CS.getArgument(i)));
  7606. // Push the arguments from the call instruction up to the register mask.
  7607. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7608. Ops.append(Call->op_begin() + 2, e);
  7609. // Push live variables for the stack map.
  7610. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7611. // Push the register mask info.
  7612. if (HasGlue)
  7613. Ops.push_back(*(Call->op_end()-2));
  7614. else
  7615. Ops.push_back(*(Call->op_end()-1));
  7616. // Push the chain (this is originally the first operand of the call, but
  7617. // becomes now the last or second to last operand).
  7618. Ops.push_back(*(Call->op_begin()));
  7619. // Push the glue flag (last operand).
  7620. if (HasGlue)
  7621. Ops.push_back(*(Call->op_end()-1));
  7622. SDVTList NodeTys;
  7623. if (IsAnyRegCC && HasDef) {
  7624. // Create the return types based on the intrinsic definition
  7625. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7626. SmallVector<EVT, 3> ValueVTs;
  7627. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7628. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7629. // There is always a chain and a glue type at the end
  7630. ValueVTs.push_back(MVT::Other);
  7631. ValueVTs.push_back(MVT::Glue);
  7632. NodeTys = DAG.getVTList(ValueVTs);
  7633. } else
  7634. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7635. // Replace the target specific call node with a PATCHPOINT node.
  7636. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7637. dl, NodeTys, Ops);
  7638. // Update the NodeMap.
  7639. if (HasDef) {
  7640. if (IsAnyRegCC)
  7641. setValue(CS.getInstruction(), SDValue(MN, 0));
  7642. else
  7643. setValue(CS.getInstruction(), Result.first);
  7644. }
  7645. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7646. // call sequence. Furthermore the location of the chain and glue can change
  7647. // when the AnyReg calling convention is used and the intrinsic returns a
  7648. // value.
  7649. if (IsAnyRegCC && HasDef) {
  7650. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7651. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7652. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7653. } else
  7654. DAG.ReplaceAllUsesWith(Call, MN);
  7655. DAG.DeleteNode(Call);
  7656. // Inform the Frame Information that we have a patchpoint in this function.
  7657. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7658. }
  7659. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7660. unsigned Intrinsic) {
  7661. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7662. SDValue Op1 = getValue(I.getArgOperand(0));
  7663. SDValue Op2;
  7664. if (I.getNumArgOperands() > 1)
  7665. Op2 = getValue(I.getArgOperand(1));
  7666. SDLoc dl = getCurSDLoc();
  7667. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7668. SDValue Res;
  7669. FastMathFlags FMF;
  7670. if (isa<FPMathOperator>(I))
  7671. FMF = I.getFastMathFlags();
  7672. switch (Intrinsic) {
  7673. case Intrinsic::experimental_vector_reduce_fadd:
  7674. if (FMF.isFast())
  7675. Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
  7676. else
  7677. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7678. break;
  7679. case Intrinsic::experimental_vector_reduce_fmul:
  7680. if (FMF.isFast())
  7681. Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
  7682. else
  7683. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7684. break;
  7685. case Intrinsic::experimental_vector_reduce_add:
  7686. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7687. break;
  7688. case Intrinsic::experimental_vector_reduce_mul:
  7689. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7690. break;
  7691. case Intrinsic::experimental_vector_reduce_and:
  7692. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7693. break;
  7694. case Intrinsic::experimental_vector_reduce_or:
  7695. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7696. break;
  7697. case Intrinsic::experimental_vector_reduce_xor:
  7698. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7699. break;
  7700. case Intrinsic::experimental_vector_reduce_smax:
  7701. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7702. break;
  7703. case Intrinsic::experimental_vector_reduce_smin:
  7704. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7705. break;
  7706. case Intrinsic::experimental_vector_reduce_umax:
  7707. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7708. break;
  7709. case Intrinsic::experimental_vector_reduce_umin:
  7710. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7711. break;
  7712. case Intrinsic::experimental_vector_reduce_fmax:
  7713. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7714. break;
  7715. case Intrinsic::experimental_vector_reduce_fmin:
  7716. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7717. break;
  7718. default:
  7719. llvm_unreachable("Unhandled vector reduce intrinsic");
  7720. }
  7721. setValue(&I, Res);
  7722. }
  7723. /// Returns an AttributeList representing the attributes applied to the return
  7724. /// value of the given call.
  7725. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7726. SmallVector<Attribute::AttrKind, 2> Attrs;
  7727. if (CLI.RetSExt)
  7728. Attrs.push_back(Attribute::SExt);
  7729. if (CLI.RetZExt)
  7730. Attrs.push_back(Attribute::ZExt);
  7731. if (CLI.IsInReg)
  7732. Attrs.push_back(Attribute::InReg);
  7733. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7734. Attrs);
  7735. }
  7736. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7737. /// implementation, which just calls LowerCall.
  7738. /// FIXME: When all targets are
  7739. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7740. std::pair<SDValue, SDValue>
  7741. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7742. // Handle the incoming return values from the call.
  7743. CLI.Ins.clear();
  7744. Type *OrigRetTy = CLI.RetTy;
  7745. SmallVector<EVT, 4> RetTys;
  7746. SmallVector<uint64_t, 4> Offsets;
  7747. auto &DL = CLI.DAG.getDataLayout();
  7748. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7749. if (CLI.IsPostTypeLegalization) {
  7750. // If we are lowering a libcall after legalization, split the return type.
  7751. SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
  7752. SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
  7753. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7754. EVT RetVT = OldRetTys[i];
  7755. uint64_t Offset = OldOffsets[i];
  7756. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7757. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7758. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7759. RetTys.append(NumRegs, RegisterVT);
  7760. for (unsigned j = 0; j != NumRegs; ++j)
  7761. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7762. }
  7763. }
  7764. SmallVector<ISD::OutputArg, 4> Outs;
  7765. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7766. bool CanLowerReturn =
  7767. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7768. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7769. SDValue DemoteStackSlot;
  7770. int DemoteStackIdx = -100;
  7771. if (!CanLowerReturn) {
  7772. // FIXME: equivalent assert?
  7773. // assert(!CS.hasInAllocaArgument() &&
  7774. // "sret demotion is incompatible with inalloca");
  7775. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7776. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7777. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7778. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7779. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7780. DL.getAllocaAddrSpace());
  7781. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7782. ArgListEntry Entry;
  7783. Entry.Node = DemoteStackSlot;
  7784. Entry.Ty = StackSlotPtrType;
  7785. Entry.IsSExt = false;
  7786. Entry.IsZExt = false;
  7787. Entry.IsInReg = false;
  7788. Entry.IsSRet = true;
  7789. Entry.IsNest = false;
  7790. Entry.IsByVal = false;
  7791. Entry.IsReturned = false;
  7792. Entry.IsSwiftSelf = false;
  7793. Entry.IsSwiftError = false;
  7794. Entry.Alignment = Align;
  7795. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7796. CLI.NumFixedArgs += 1;
  7797. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7798. // sret demotion isn't compatible with tail-calls, since the sret argument
  7799. // points into the callers stack frame.
  7800. CLI.IsTailCall = false;
  7801. } else {
  7802. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7803. EVT VT = RetTys[I];
  7804. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7805. CLI.CallConv, VT);
  7806. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7807. CLI.CallConv, VT);
  7808. for (unsigned i = 0; i != NumRegs; ++i) {
  7809. ISD::InputArg MyFlags;
  7810. MyFlags.VT = RegisterVT;
  7811. MyFlags.ArgVT = VT;
  7812. MyFlags.Used = CLI.IsReturnValueUsed;
  7813. if (CLI.RetSExt)
  7814. MyFlags.Flags.setSExt();
  7815. if (CLI.RetZExt)
  7816. MyFlags.Flags.setZExt();
  7817. if (CLI.IsInReg)
  7818. MyFlags.Flags.setInReg();
  7819. CLI.Ins.push_back(MyFlags);
  7820. }
  7821. }
  7822. }
  7823. // We push in swifterror return as the last element of CLI.Ins.
  7824. ArgListTy &Args = CLI.getArgs();
  7825. if (supportSwiftError()) {
  7826. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7827. if (Args[i].IsSwiftError) {
  7828. ISD::InputArg MyFlags;
  7829. MyFlags.VT = getPointerTy(DL);
  7830. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7831. MyFlags.Flags.setSwiftError();
  7832. CLI.Ins.push_back(MyFlags);
  7833. }
  7834. }
  7835. }
  7836. // Handle all of the outgoing arguments.
  7837. CLI.Outs.clear();
  7838. CLI.OutVals.clear();
  7839. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7840. SmallVector<EVT, 4> ValueVTs;
  7841. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7842. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7843. Type *FinalType = Args[i].Ty;
  7844. if (Args[i].IsByVal)
  7845. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7846. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7847. FinalType, CLI.CallConv, CLI.IsVarArg);
  7848. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7849. ++Value) {
  7850. EVT VT = ValueVTs[Value];
  7851. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7852. SDValue Op = SDValue(Args[i].Node.getNode(),
  7853. Args[i].Node.getResNo() + Value);
  7854. ISD::ArgFlagsTy Flags;
  7855. // Certain targets (such as MIPS), may have a different ABI alignment
  7856. // for a type depending on the context. Give the target a chance to
  7857. // specify the alignment it wants.
  7858. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7859. if (Args[i].IsZExt)
  7860. Flags.setZExt();
  7861. if (Args[i].IsSExt)
  7862. Flags.setSExt();
  7863. if (Args[i].IsInReg) {
  7864. // If we are using vectorcall calling convention, a structure that is
  7865. // passed InReg - is surely an HVA
  7866. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7867. isa<StructType>(FinalType)) {
  7868. // The first value of a structure is marked
  7869. if (0 == Value)
  7870. Flags.setHvaStart();
  7871. Flags.setHva();
  7872. }
  7873. // Set InReg Flag
  7874. Flags.setInReg();
  7875. }
  7876. if (Args[i].IsSRet)
  7877. Flags.setSRet();
  7878. if (Args[i].IsSwiftSelf)
  7879. Flags.setSwiftSelf();
  7880. if (Args[i].IsSwiftError)
  7881. Flags.setSwiftError();
  7882. if (Args[i].IsByVal)
  7883. Flags.setByVal();
  7884. if (Args[i].IsInAlloca) {
  7885. Flags.setInAlloca();
  7886. // Set the byval flag for CCAssignFn callbacks that don't know about
  7887. // inalloca. This way we can know how many bytes we should've allocated
  7888. // and how many bytes a callee cleanup function will pop. If we port
  7889. // inalloca to more targets, we'll have to add custom inalloca handling
  7890. // in the various CC lowering callbacks.
  7891. Flags.setByVal();
  7892. }
  7893. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  7894. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  7895. Type *ElementTy = Ty->getElementType();
  7896. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  7897. // For ByVal, alignment should come from FE. BE will guess if this
  7898. // info is not there but there are cases it cannot get right.
  7899. unsigned FrameAlign;
  7900. if (Args[i].Alignment)
  7901. FrameAlign = Args[i].Alignment;
  7902. else
  7903. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  7904. Flags.setByValAlign(FrameAlign);
  7905. }
  7906. if (Args[i].IsNest)
  7907. Flags.setNest();
  7908. if (NeedsRegBlock)
  7909. Flags.setInConsecutiveRegs();
  7910. Flags.setOrigAlign(OriginalAlignment);
  7911. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7912. CLI.CallConv, VT);
  7913. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7914. CLI.CallConv, VT);
  7915. SmallVector<SDValue, 4> Parts(NumParts);
  7916. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  7917. if (Args[i].IsSExt)
  7918. ExtendKind = ISD::SIGN_EXTEND;
  7919. else if (Args[i].IsZExt)
  7920. ExtendKind = ISD::ZERO_EXTEND;
  7921. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  7922. // for now.
  7923. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  7924. CanLowerReturn) {
  7925. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  7926. "unexpected use of 'returned'");
  7927. // Before passing 'returned' to the target lowering code, ensure that
  7928. // either the register MVT and the actual EVT are the same size or that
  7929. // the return value and argument are extended in the same way; in these
  7930. // cases it's safe to pass the argument register value unchanged as the
  7931. // return register value (although it's at the target's option whether
  7932. // to do so)
  7933. // TODO: allow code generation to take advantage of partially preserved
  7934. // registers rather than clobbering the entire register when the
  7935. // parameter extension method is not compatible with the return
  7936. // extension method
  7937. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  7938. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  7939. CLI.RetZExt == Args[i].IsZExt))
  7940. Flags.setReturned();
  7941. }
  7942. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  7943. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  7944. for (unsigned j = 0; j != NumParts; ++j) {
  7945. // if it isn't first piece, alignment must be 1
  7946. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  7947. i < CLI.NumFixedArgs,
  7948. i, j*Parts[j].getValueType().getStoreSize());
  7949. if (NumParts > 1 && j == 0)
  7950. MyFlags.Flags.setSplit();
  7951. else if (j != 0) {
  7952. MyFlags.Flags.setOrigAlign(1);
  7953. if (j == NumParts - 1)
  7954. MyFlags.Flags.setSplitEnd();
  7955. }
  7956. CLI.Outs.push_back(MyFlags);
  7957. CLI.OutVals.push_back(Parts[j]);
  7958. }
  7959. if (NeedsRegBlock && Value == NumValues - 1)
  7960. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  7961. }
  7962. }
  7963. SmallVector<SDValue, 4> InVals;
  7964. CLI.Chain = LowerCall(CLI, InVals);
  7965. // Update CLI.InVals to use outside of this function.
  7966. CLI.InVals = InVals;
  7967. // Verify that the target's LowerCall behaved as expected.
  7968. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  7969. "LowerCall didn't return a valid chain!");
  7970. assert((!CLI.IsTailCall || InVals.empty()) &&
  7971. "LowerCall emitted a return value for a tail call!");
  7972. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  7973. "LowerCall didn't emit the correct number of values!");
  7974. // For a tail call, the return value is merely live-out and there aren't
  7975. // any nodes in the DAG representing it. Return a special value to
  7976. // indicate that a tail call has been emitted and no more Instructions
  7977. // should be processed in the current block.
  7978. if (CLI.IsTailCall) {
  7979. CLI.DAG.setRoot(CLI.Chain);
  7980. return std::make_pair(SDValue(), SDValue());
  7981. }
  7982. #ifndef NDEBUG
  7983. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  7984. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  7985. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  7986. "LowerCall emitted a value with the wrong type!");
  7987. }
  7988. #endif
  7989. SmallVector<SDValue, 4> ReturnValues;
  7990. if (!CanLowerReturn) {
  7991. // The instruction result is the result of loading from the
  7992. // hidden sret parameter.
  7993. SmallVector<EVT, 1> PVTs;
  7994. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  7995. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  7996. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  7997. EVT PtrVT = PVTs[0];
  7998. unsigned NumValues = RetTys.size();
  7999. ReturnValues.resize(NumValues);
  8000. SmallVector<SDValue, 4> Chains(NumValues);
  8001. // An aggregate return value cannot wrap around the address space, so
  8002. // offsets to its parts don't wrap either.
  8003. SDNodeFlags Flags;
  8004. Flags.setNoUnsignedWrap(true);
  8005. for (unsigned i = 0; i < NumValues; ++i) {
  8006. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8007. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8008. PtrVT), Flags);
  8009. SDValue L = CLI.DAG.getLoad(
  8010. RetTys[i], CLI.DL, CLI.Chain, Add,
  8011. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8012. DemoteStackIdx, Offsets[i]),
  8013. /* Alignment = */ 1);
  8014. ReturnValues[i] = L;
  8015. Chains[i] = L.getValue(1);
  8016. }
  8017. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8018. } else {
  8019. // Collect the legal value parts into potentially illegal values
  8020. // that correspond to the original function's return values.
  8021. Optional<ISD::NodeType> AssertOp;
  8022. if (CLI.RetSExt)
  8023. AssertOp = ISD::AssertSext;
  8024. else if (CLI.RetZExt)
  8025. AssertOp = ISD::AssertZext;
  8026. unsigned CurReg = 0;
  8027. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8028. EVT VT = RetTys[I];
  8029. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8030. CLI.CallConv, VT);
  8031. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8032. CLI.CallConv, VT);
  8033. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8034. NumRegs, RegisterVT, VT, nullptr,
  8035. CLI.CallConv, AssertOp));
  8036. CurReg += NumRegs;
  8037. }
  8038. // For a function returning void, there is no return value. We can't create
  8039. // such a node, so we just return a null return value in that case. In
  8040. // that case, nothing will actually look at the value.
  8041. if (ReturnValues.empty())
  8042. return std::make_pair(SDValue(), CLI.Chain);
  8043. }
  8044. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8045. CLI.DAG.getVTList(RetTys), ReturnValues);
  8046. return std::make_pair(Res, CLI.Chain);
  8047. }
  8048. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8049. SmallVectorImpl<SDValue> &Results,
  8050. SelectionDAG &DAG) const {
  8051. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8052. Results.push_back(Res);
  8053. }
  8054. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8055. llvm_unreachable("LowerOperation not implemented for this target!");
  8056. }
  8057. void
  8058. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8059. SDValue Op = getNonRegisterValue(V);
  8060. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8061. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8062. "Copy from a reg to the same reg!");
  8063. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  8064. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8065. // If this is an InlineAsm we have to match the registers required, not the
  8066. // notional registers required by the type.
  8067. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8068. None); // This is not an ABI copy.
  8069. SDValue Chain = DAG.getEntryNode();
  8070. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8071. FuncInfo.PreferredExtendType.end())
  8072. ? ISD::ANY_EXTEND
  8073. : FuncInfo.PreferredExtendType[V];
  8074. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8075. PendingExports.push_back(Chain);
  8076. }
  8077. #include "llvm/CodeGen/SelectionDAGISel.h"
  8078. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8079. /// entry block, return true. This includes arguments used by switches, since
  8080. /// the switch may expand into multiple basic blocks.
  8081. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8082. // With FastISel active, we may be splitting blocks, so force creation
  8083. // of virtual registers for all non-dead arguments.
  8084. if (FastISel)
  8085. return A->use_empty();
  8086. const BasicBlock &Entry = A->getParent()->front();
  8087. for (const User *U : A->users())
  8088. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8089. return false; // Use not in entry block.
  8090. return true;
  8091. }
  8092. using ArgCopyElisionMapTy =
  8093. DenseMap<const Argument *,
  8094. std::pair<const AllocaInst *, const StoreInst *>>;
  8095. /// Scan the entry block of the function in FuncInfo for arguments that look
  8096. /// like copies into a local alloca. Record any copied arguments in
  8097. /// ArgCopyElisionCandidates.
  8098. static void
  8099. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8100. FunctionLoweringInfo *FuncInfo,
  8101. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8102. // Record the state of every static alloca used in the entry block. Argument
  8103. // allocas are all used in the entry block, so we need approximately as many
  8104. // entries as we have arguments.
  8105. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8106. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8107. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8108. StaticAllocas.reserve(NumArgs * 2);
  8109. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8110. if (!V)
  8111. return nullptr;
  8112. V = V->stripPointerCasts();
  8113. const auto *AI = dyn_cast<AllocaInst>(V);
  8114. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8115. return nullptr;
  8116. auto Iter = StaticAllocas.insert({AI, Unknown});
  8117. return &Iter.first->second;
  8118. };
  8119. // Look for stores of arguments to static allocas. Look through bitcasts and
  8120. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8121. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8122. // unanalyzed store might write it.
  8123. // FIXME: Handle structs initialized with multiple stores.
  8124. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8125. // Look for stores, and handle non-store uses conservatively.
  8126. const auto *SI = dyn_cast<StoreInst>(&I);
  8127. if (!SI) {
  8128. // We will look through cast uses, so ignore them completely.
  8129. if (I.isCast())
  8130. continue;
  8131. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8132. if (isa<DbgInfoIntrinsic>(I))
  8133. continue;
  8134. // This is an unknown instruction. Assume it escapes or writes to all
  8135. // static alloca operands.
  8136. for (const Use &U : I.operands()) {
  8137. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8138. *Info = StaticAllocaInfo::Clobbered;
  8139. }
  8140. continue;
  8141. }
  8142. // If the stored value is a static alloca, mark it as escaped.
  8143. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8144. *Info = StaticAllocaInfo::Clobbered;
  8145. // Check if the destination is a static alloca.
  8146. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8147. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8148. if (!Info)
  8149. continue;
  8150. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8151. // Skip allocas that have been initialized or clobbered.
  8152. if (*Info != StaticAllocaInfo::Unknown)
  8153. continue;
  8154. // Check if the stored value is an argument, and that this store fully
  8155. // initializes the alloca. Don't elide copies from the same argument twice.
  8156. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8157. const auto *Arg = dyn_cast<Argument>(Val);
  8158. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8159. Arg->getType()->isEmptyTy() ||
  8160. DL.getTypeStoreSize(Arg->getType()) !=
  8161. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8162. ArgCopyElisionCandidates.count(Arg)) {
  8163. *Info = StaticAllocaInfo::Clobbered;
  8164. continue;
  8165. }
  8166. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8167. << '\n');
  8168. // Mark this alloca and store for argument copy elision.
  8169. *Info = StaticAllocaInfo::Elidable;
  8170. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8171. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8172. // builds, which is useful, because -O0 builds have large entry blocks and
  8173. // many allocas.
  8174. if (ArgCopyElisionCandidates.size() == NumArgs)
  8175. break;
  8176. }
  8177. }
  8178. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8179. /// ArgVal is a load from a suitable fixed stack object.
  8180. static void tryToElideArgumentCopy(
  8181. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8182. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8183. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8184. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8185. SDValue ArgVal, bool &ArgHasUses) {
  8186. // Check if this is a load from a fixed stack object.
  8187. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8188. if (!LNode)
  8189. return;
  8190. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8191. if (!FINode)
  8192. return;
  8193. // Check that the fixed stack object is the right size and alignment.
  8194. // Look at the alignment that the user wrote on the alloca instead of looking
  8195. // at the stack object.
  8196. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8197. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8198. const AllocaInst *AI = ArgCopyIter->second.first;
  8199. int FixedIndex = FINode->getIndex();
  8200. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8201. int OldIndex = AllocaIndex;
  8202. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8203. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8204. LLVM_DEBUG(
  8205. dbgs() << " argument copy elision failed due to bad fixed stack "
  8206. "object size\n");
  8207. return;
  8208. }
  8209. unsigned RequiredAlignment = AI->getAlignment();
  8210. if (!RequiredAlignment) {
  8211. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8212. AI->getAllocatedType());
  8213. }
  8214. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8215. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8216. "greater than stack argument alignment ("
  8217. << RequiredAlignment << " vs "
  8218. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8219. return;
  8220. }
  8221. // Perform the elision. Delete the old stack object and replace its only use
  8222. // in the variable info map. Mark the stack object as mutable.
  8223. LLVM_DEBUG({
  8224. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8225. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8226. << '\n';
  8227. });
  8228. MFI.RemoveStackObject(OldIndex);
  8229. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8230. AllocaIndex = FixedIndex;
  8231. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8232. Chains.push_back(ArgVal.getValue(1));
  8233. // Avoid emitting code for the store implementing the copy.
  8234. const StoreInst *SI = ArgCopyIter->second.second;
  8235. ElidedArgCopyInstrs.insert(SI);
  8236. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8237. // if it is't used by anything other than the store.
  8238. for (const Value *U : Arg.users()) {
  8239. if (U != SI) {
  8240. ArgHasUses = true;
  8241. break;
  8242. }
  8243. }
  8244. }
  8245. void SelectionDAGISel::LowerArguments(const Function &F) {
  8246. SelectionDAG &DAG = SDB->DAG;
  8247. SDLoc dl = SDB->getCurSDLoc();
  8248. const DataLayout &DL = DAG.getDataLayout();
  8249. SmallVector<ISD::InputArg, 16> Ins;
  8250. if (!FuncInfo->CanLowerReturn) {
  8251. // Put in an sret pointer parameter before all the other parameters.
  8252. SmallVector<EVT, 1> ValueVTs;
  8253. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8254. F.getReturnType()->getPointerTo(
  8255. DAG.getDataLayout().getAllocaAddrSpace()),
  8256. ValueVTs);
  8257. // NOTE: Assuming that a pointer will never break down to more than one VT
  8258. // or one register.
  8259. ISD::ArgFlagsTy Flags;
  8260. Flags.setSRet();
  8261. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8262. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8263. ISD::InputArg::NoArgIndex, 0);
  8264. Ins.push_back(RetArg);
  8265. }
  8266. // Look for stores of arguments to static allocas. Mark such arguments with a
  8267. // flag to ask the target to give us the memory location of that argument if
  8268. // available.
  8269. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8270. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8271. // Set up the incoming argument description vector.
  8272. for (const Argument &Arg : F.args()) {
  8273. unsigned ArgNo = Arg.getArgNo();
  8274. SmallVector<EVT, 4> ValueVTs;
  8275. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8276. bool isArgValueUsed = !Arg.use_empty();
  8277. unsigned PartBase = 0;
  8278. Type *FinalType = Arg.getType();
  8279. if (Arg.hasAttribute(Attribute::ByVal))
  8280. FinalType = cast<PointerType>(FinalType)->getElementType();
  8281. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8282. FinalType, F.getCallingConv(), F.isVarArg());
  8283. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8284. Value != NumValues; ++Value) {
  8285. EVT VT = ValueVTs[Value];
  8286. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8287. ISD::ArgFlagsTy Flags;
  8288. // Certain targets (such as MIPS), may have a different ABI alignment
  8289. // for a type depending on the context. Give the target a chance to
  8290. // specify the alignment it wants.
  8291. unsigned OriginalAlignment =
  8292. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8293. if (Arg.hasAttribute(Attribute::ZExt))
  8294. Flags.setZExt();
  8295. if (Arg.hasAttribute(Attribute::SExt))
  8296. Flags.setSExt();
  8297. if (Arg.hasAttribute(Attribute::InReg)) {
  8298. // If we are using vectorcall calling convention, a structure that is
  8299. // passed InReg - is surely an HVA
  8300. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8301. isa<StructType>(Arg.getType())) {
  8302. // The first value of a structure is marked
  8303. if (0 == Value)
  8304. Flags.setHvaStart();
  8305. Flags.setHva();
  8306. }
  8307. // Set InReg Flag
  8308. Flags.setInReg();
  8309. }
  8310. if (Arg.hasAttribute(Attribute::StructRet))
  8311. Flags.setSRet();
  8312. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8313. Flags.setSwiftSelf();
  8314. if (Arg.hasAttribute(Attribute::SwiftError))
  8315. Flags.setSwiftError();
  8316. if (Arg.hasAttribute(Attribute::ByVal))
  8317. Flags.setByVal();
  8318. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8319. Flags.setInAlloca();
  8320. // Set the byval flag for CCAssignFn callbacks that don't know about
  8321. // inalloca. This way we can know how many bytes we should've allocated
  8322. // and how many bytes a callee cleanup function will pop. If we port
  8323. // inalloca to more targets, we'll have to add custom inalloca handling
  8324. // in the various CC lowering callbacks.
  8325. Flags.setByVal();
  8326. }
  8327. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8328. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8329. if (ArgNo == 0)
  8330. Flags.setByVal();
  8331. }
  8332. if (Flags.isByVal() || Flags.isInAlloca()) {
  8333. PointerType *Ty = cast<PointerType>(Arg.getType());
  8334. Type *ElementTy = Ty->getElementType();
  8335. Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
  8336. // For ByVal, alignment should be passed from FE. BE will guess if
  8337. // this info is not there but there are cases it cannot get right.
  8338. unsigned FrameAlign;
  8339. if (Arg.getParamAlignment())
  8340. FrameAlign = Arg.getParamAlignment();
  8341. else
  8342. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8343. Flags.setByValAlign(FrameAlign);
  8344. }
  8345. if (Arg.hasAttribute(Attribute::Nest))
  8346. Flags.setNest();
  8347. if (NeedsRegBlock)
  8348. Flags.setInConsecutiveRegs();
  8349. Flags.setOrigAlign(OriginalAlignment);
  8350. if (ArgCopyElisionCandidates.count(&Arg))
  8351. Flags.setCopyElisionCandidate();
  8352. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8353. *CurDAG->getContext(), F.getCallingConv(), VT);
  8354. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8355. *CurDAG->getContext(), F.getCallingConv(), VT);
  8356. for (unsigned i = 0; i != NumRegs; ++i) {
  8357. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8358. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8359. if (NumRegs > 1 && i == 0)
  8360. MyFlags.Flags.setSplit();
  8361. // if it isn't first piece, alignment must be 1
  8362. else if (i > 0) {
  8363. MyFlags.Flags.setOrigAlign(1);
  8364. if (i == NumRegs - 1)
  8365. MyFlags.Flags.setSplitEnd();
  8366. }
  8367. Ins.push_back(MyFlags);
  8368. }
  8369. if (NeedsRegBlock && Value == NumValues - 1)
  8370. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8371. PartBase += VT.getStoreSize();
  8372. }
  8373. }
  8374. // Call the target to set up the argument values.
  8375. SmallVector<SDValue, 8> InVals;
  8376. SDValue NewRoot = TLI->LowerFormalArguments(
  8377. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8378. // Verify that the target's LowerFormalArguments behaved as expected.
  8379. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8380. "LowerFormalArguments didn't return a valid chain!");
  8381. assert(InVals.size() == Ins.size() &&
  8382. "LowerFormalArguments didn't emit the correct number of values!");
  8383. LLVM_DEBUG({
  8384. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8385. assert(InVals[i].getNode() &&
  8386. "LowerFormalArguments emitted a null value!");
  8387. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8388. "LowerFormalArguments emitted a value with the wrong type!");
  8389. }
  8390. });
  8391. // Update the DAG with the new chain value resulting from argument lowering.
  8392. DAG.setRoot(NewRoot);
  8393. // Set up the argument values.
  8394. unsigned i = 0;
  8395. if (!FuncInfo->CanLowerReturn) {
  8396. // Create a virtual register for the sret pointer, and put in a copy
  8397. // from the sret argument into it.
  8398. SmallVector<EVT, 1> ValueVTs;
  8399. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8400. F.getReturnType()->getPointerTo(
  8401. DAG.getDataLayout().getAllocaAddrSpace()),
  8402. ValueVTs);
  8403. MVT VT = ValueVTs[0].getSimpleVT();
  8404. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8405. Optional<ISD::NodeType> AssertOp = None;
  8406. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8407. nullptr, F.getCallingConv(), AssertOp);
  8408. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8409. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8410. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8411. FuncInfo->DemoteRegister = SRetReg;
  8412. NewRoot =
  8413. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8414. DAG.setRoot(NewRoot);
  8415. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8416. ++i;
  8417. }
  8418. SmallVector<SDValue, 4> Chains;
  8419. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8420. for (const Argument &Arg : F.args()) {
  8421. SmallVector<SDValue, 4> ArgValues;
  8422. SmallVector<EVT, 4> ValueVTs;
  8423. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8424. unsigned NumValues = ValueVTs.size();
  8425. if (NumValues == 0)
  8426. continue;
  8427. bool ArgHasUses = !Arg.use_empty();
  8428. // Elide the copying store if the target loaded this argument from a
  8429. // suitable fixed stack object.
  8430. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8431. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8432. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8433. InVals[i], ArgHasUses);
  8434. }
  8435. // If this argument is unused then remember its value. It is used to generate
  8436. // debugging information.
  8437. bool isSwiftErrorArg =
  8438. TLI->supportSwiftError() &&
  8439. Arg.hasAttribute(Attribute::SwiftError);
  8440. if (!ArgHasUses && !isSwiftErrorArg) {
  8441. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8442. // Also remember any frame index for use in FastISel.
  8443. if (FrameIndexSDNode *FI =
  8444. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8445. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8446. }
  8447. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8448. EVT VT = ValueVTs[Val];
  8449. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8450. F.getCallingConv(), VT);
  8451. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8452. *CurDAG->getContext(), F.getCallingConv(), VT);
  8453. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8454. // we do generate a copy for it that can be used on return from the
  8455. // function.
  8456. if (ArgHasUses || isSwiftErrorArg) {
  8457. Optional<ISD::NodeType> AssertOp;
  8458. if (Arg.hasAttribute(Attribute::SExt))
  8459. AssertOp = ISD::AssertSext;
  8460. else if (Arg.hasAttribute(Attribute::ZExt))
  8461. AssertOp = ISD::AssertZext;
  8462. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8463. PartVT, VT, nullptr,
  8464. F.getCallingConv(), AssertOp));
  8465. }
  8466. i += NumParts;
  8467. }
  8468. // We don't need to do anything else for unused arguments.
  8469. if (ArgValues.empty())
  8470. continue;
  8471. // Note down frame index.
  8472. if (FrameIndexSDNode *FI =
  8473. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8474. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8475. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8476. SDB->getCurSDLoc());
  8477. SDB->setValue(&Arg, Res);
  8478. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8479. // We want to associate the argument with the frame index, among
  8480. // involved operands, that correspond to the lowest address. The
  8481. // getCopyFromParts function, called earlier, is swapping the order of
  8482. // the operands to BUILD_PAIR depending on endianness. The result of
  8483. // that swapping is that the least significant bits of the argument will
  8484. // be in the first operand of the BUILD_PAIR node, and the most
  8485. // significant bits will be in the second operand.
  8486. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8487. if (LoadSDNode *LNode =
  8488. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8489. if (FrameIndexSDNode *FI =
  8490. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8491. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8492. }
  8493. // Update the SwiftErrorVRegDefMap.
  8494. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8495. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8496. if (TargetRegisterInfo::isVirtualRegister(Reg))
  8497. FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
  8498. FuncInfo->SwiftErrorArg, Reg);
  8499. }
  8500. // If this argument is live outside of the entry block, insert a copy from
  8501. // wherever we got it to the vreg that other BB's will reference it as.
  8502. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  8503. // If we can, though, try to skip creating an unnecessary vreg.
  8504. // FIXME: This isn't very clean... it would be nice to make this more
  8505. // general. It's also subtly incompatible with the hacks FastISel
  8506. // uses with vregs.
  8507. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8508. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  8509. FuncInfo->ValueMap[&Arg] = Reg;
  8510. continue;
  8511. }
  8512. }
  8513. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8514. FuncInfo->InitializeRegForValue(&Arg);
  8515. SDB->CopyToExportRegsIfNeeded(&Arg);
  8516. }
  8517. }
  8518. if (!Chains.empty()) {
  8519. Chains.push_back(NewRoot);
  8520. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8521. }
  8522. DAG.setRoot(NewRoot);
  8523. assert(i == InVals.size() && "Argument register count mismatch!");
  8524. // If any argument copy elisions occurred and we have debug info, update the
  8525. // stale frame indices used in the dbg.declare variable info table.
  8526. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8527. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8528. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8529. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8530. if (I != ArgCopyElisionFrameIndexMap.end())
  8531. VI.Slot = I->second;
  8532. }
  8533. }
  8534. // Finally, if the target has anything special to do, allow it to do so.
  8535. EmitFunctionEntryCode();
  8536. }
  8537. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8538. /// ensure constants are generated when needed. Remember the virtual registers
  8539. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8540. /// directly add them, because expansion might result in multiple MBB's for one
  8541. /// BB. As such, the start of the BB might correspond to a different MBB than
  8542. /// the end.
  8543. void
  8544. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8545. const Instruction *TI = LLVMBB->getTerminator();
  8546. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8547. // Check PHI nodes in successors that expect a value to be available from this
  8548. // block.
  8549. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8550. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8551. if (!isa<PHINode>(SuccBB->begin())) continue;
  8552. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8553. // If this terminator has multiple identical successors (common for
  8554. // switches), only handle each succ once.
  8555. if (!SuccsHandled.insert(SuccMBB).second)
  8556. continue;
  8557. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8558. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8559. // nodes and Machine PHI nodes, but the incoming operands have not been
  8560. // emitted yet.
  8561. for (const PHINode &PN : SuccBB->phis()) {
  8562. // Ignore dead phi's.
  8563. if (PN.use_empty())
  8564. continue;
  8565. // Skip empty types
  8566. if (PN.getType()->isEmptyTy())
  8567. continue;
  8568. unsigned Reg;
  8569. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8570. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8571. unsigned &RegOut = ConstantsOut[C];
  8572. if (RegOut == 0) {
  8573. RegOut = FuncInfo.CreateRegs(C->getType());
  8574. CopyValueToVirtualRegister(C, RegOut);
  8575. }
  8576. Reg = RegOut;
  8577. } else {
  8578. DenseMap<const Value *, unsigned>::iterator I =
  8579. FuncInfo.ValueMap.find(PHIOp);
  8580. if (I != FuncInfo.ValueMap.end())
  8581. Reg = I->second;
  8582. else {
  8583. assert(isa<AllocaInst>(PHIOp) &&
  8584. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8585. "Didn't codegen value into a register!??");
  8586. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  8587. CopyValueToVirtualRegister(PHIOp, Reg);
  8588. }
  8589. }
  8590. // Remember that this register needs to added to the machine PHI node as
  8591. // the input for this MBB.
  8592. SmallVector<EVT, 4> ValueVTs;
  8593. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8594. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8595. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8596. EVT VT = ValueVTs[vti];
  8597. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8598. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8599. FuncInfo.PHINodesToUpdate.push_back(
  8600. std::make_pair(&*MBBI++, Reg + i));
  8601. Reg += NumRegisters;
  8602. }
  8603. }
  8604. }
  8605. ConstantsOut.clear();
  8606. }
  8607. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8608. /// is 0.
  8609. MachineBasicBlock *
  8610. SelectionDAGBuilder::StackProtectorDescriptor::
  8611. AddSuccessorMBB(const BasicBlock *BB,
  8612. MachineBasicBlock *ParentMBB,
  8613. bool IsLikely,
  8614. MachineBasicBlock *SuccMBB) {
  8615. // If SuccBB has not been created yet, create it.
  8616. if (!SuccMBB) {
  8617. MachineFunction *MF = ParentMBB->getParent();
  8618. MachineFunction::iterator BBI(ParentMBB);
  8619. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8620. MF->insert(++BBI, SuccMBB);
  8621. }
  8622. // Add it as a successor of ParentMBB.
  8623. ParentMBB->addSuccessor(
  8624. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8625. return SuccMBB;
  8626. }
  8627. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8628. MachineFunction::iterator I(MBB);
  8629. if (++I == FuncInfo.MF->end())
  8630. return nullptr;
  8631. return &*I;
  8632. }
  8633. /// During lowering new call nodes can be created (such as memset, etc.).
  8634. /// Those will become new roots of the current DAG, but complications arise
  8635. /// when they are tail calls. In such cases, the call lowering will update
  8636. /// the root, but the builder still needs to know that a tail call has been
  8637. /// lowered in order to avoid generating an additional return.
  8638. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8639. // If the node is null, we do have a tail call.
  8640. if (MaybeTC.getNode() != nullptr)
  8641. DAG.setRoot(MaybeTC);
  8642. else
  8643. HasTailCall = true;
  8644. }
  8645. uint64_t
  8646. SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
  8647. unsigned First, unsigned Last) const {
  8648. assert(Last >= First);
  8649. const APInt &LowCase = Clusters[First].Low->getValue();
  8650. const APInt &HighCase = Clusters[Last].High->getValue();
  8651. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  8652. // FIXME: A range of consecutive cases has 100% density, but only requires one
  8653. // comparison to lower. We should discriminate against such consecutive ranges
  8654. // in jump tables.
  8655. return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
  8656. }
  8657. uint64_t SelectionDAGBuilder::getJumpTableNumCases(
  8658. const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
  8659. unsigned Last) const {
  8660. assert(Last >= First);
  8661. assert(TotalCases[Last] >= TotalCases[First]);
  8662. uint64_t NumCases =
  8663. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  8664. return NumCases;
  8665. }
  8666. bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
  8667. unsigned First, unsigned Last,
  8668. const SwitchInst *SI,
  8669. MachineBasicBlock *DefaultMBB,
  8670. CaseCluster &JTCluster) {
  8671. assert(First <= Last);
  8672. auto Prob = BranchProbability::getZero();
  8673. unsigned NumCmps = 0;
  8674. std::vector<MachineBasicBlock*> Table;
  8675. DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
  8676. // Initialize probabilities in JTProbs.
  8677. for (unsigned I = First; I <= Last; ++I)
  8678. JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
  8679. for (unsigned I = First; I <= Last; ++I) {
  8680. assert(Clusters[I].Kind == CC_Range);
  8681. Prob += Clusters[I].Prob;
  8682. const APInt &Low = Clusters[I].Low->getValue();
  8683. const APInt &High = Clusters[I].High->getValue();
  8684. NumCmps += (Low == High) ? 1 : 2;
  8685. if (I != First) {
  8686. // Fill the gap between this and the previous cluster.
  8687. const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
  8688. assert(PreviousHigh.slt(Low));
  8689. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  8690. for (uint64_t J = 0; J < Gap; J++)
  8691. Table.push_back(DefaultMBB);
  8692. }
  8693. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  8694. for (uint64_t J = 0; J < ClusterSize; ++J)
  8695. Table.push_back(Clusters[I].MBB);
  8696. JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
  8697. }
  8698. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8699. unsigned NumDests = JTProbs.size();
  8700. if (TLI.isSuitableForBitTests(
  8701. NumDests, NumCmps, Clusters[First].Low->getValue(),
  8702. Clusters[Last].High->getValue(), DAG.getDataLayout())) {
  8703. // Clusters[First..Last] should be lowered as bit tests instead.
  8704. return false;
  8705. }
  8706. // Create the MBB that will load from and jump through the table.
  8707. // Note: We create it here, but it's not inserted into the function yet.
  8708. MachineFunction *CurMF = FuncInfo.MF;
  8709. MachineBasicBlock *JumpTableMBB =
  8710. CurMF->CreateMachineBasicBlock(SI->getParent());
  8711. // Add successors. Note: use table order for determinism.
  8712. SmallPtrSet<MachineBasicBlock *, 8> Done;
  8713. for (MachineBasicBlock *Succ : Table) {
  8714. if (Done.count(Succ))
  8715. continue;
  8716. addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
  8717. Done.insert(Succ);
  8718. }
  8719. JumpTableMBB->normalizeSuccProbs();
  8720. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  8721. ->createJumpTableIndex(Table);
  8722. // Set up the jump table info.
  8723. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  8724. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  8725. Clusters[Last].High->getValue(), SI->getCondition(),
  8726. nullptr, false);
  8727. JTCases.emplace_back(std::move(JTH), std::move(JT));
  8728. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  8729. JTCases.size() - 1, Prob);
  8730. return true;
  8731. }
  8732. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  8733. const SwitchInst *SI,
  8734. MachineBasicBlock *DefaultMBB) {
  8735. #ifndef NDEBUG
  8736. // Clusters must be non-empty, sorted, and only contain Range clusters.
  8737. assert(!Clusters.empty());
  8738. for (CaseCluster &C : Clusters)
  8739. assert(C.Kind == CC_Range);
  8740. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  8741. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  8742. #endif
  8743. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8744. if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
  8745. return;
  8746. const int64_t N = Clusters.size();
  8747. const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
  8748. const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
  8749. if (N < 2 || N < MinJumpTableEntries)
  8750. return;
  8751. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  8752. SmallVector<unsigned, 8> TotalCases(N);
  8753. for (unsigned i = 0; i < N; ++i) {
  8754. const APInt &Hi = Clusters[i].High->getValue();
  8755. const APInt &Lo = Clusters[i].Low->getValue();
  8756. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  8757. if (i != 0)
  8758. TotalCases[i] += TotalCases[i - 1];
  8759. }
  8760. // Cheap case: the whole range may be suitable for jump table.
  8761. uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
  8762. uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
  8763. assert(NumCases < UINT64_MAX / 100);
  8764. assert(Range >= NumCases);
  8765. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8766. CaseCluster JTCluster;
  8767. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  8768. Clusters[0] = JTCluster;
  8769. Clusters.resize(1);
  8770. return;
  8771. }
  8772. }
  8773. // The algorithm below is not suitable for -O0.
  8774. if (TM.getOptLevel() == CodeGenOpt::None)
  8775. return;
  8776. // Split Clusters into minimum number of dense partitions. The algorithm uses
  8777. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  8778. // for the Case Statement'" (1994), but builds the MinPartitions array in
  8779. // reverse order to make it easier to reconstruct the partitions in ascending
  8780. // order. In the choice between two optimal partitionings, it picks the one
  8781. // which yields more jump tables.
  8782. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8783. SmallVector<unsigned, 8> MinPartitions(N);
  8784. // LastElement[i] is the last element of the partition starting at i.
  8785. SmallVector<unsigned, 8> LastElement(N);
  8786. // PartitionsScore[i] is used to break ties when choosing between two
  8787. // partitionings resulting in the same number of partitions.
  8788. SmallVector<unsigned, 8> PartitionsScore(N);
  8789. // For PartitionsScore, a small number of comparisons is considered as good as
  8790. // a jump table and a single comparison is considered better than a jump
  8791. // table.
  8792. enum PartitionScores : unsigned {
  8793. NoTable = 0,
  8794. Table = 1,
  8795. FewCases = 1,
  8796. SingleCase = 2
  8797. };
  8798. // Base case: There is only one way to partition Clusters[N-1].
  8799. MinPartitions[N - 1] = 1;
  8800. LastElement[N - 1] = N - 1;
  8801. PartitionsScore[N - 1] = PartitionScores::SingleCase;
  8802. // Note: loop indexes are signed to avoid underflow.
  8803. for (int64_t i = N - 2; i >= 0; i--) {
  8804. // Find optimal partitioning of Clusters[i..N-1].
  8805. // Baseline: Put Clusters[i] into a partition on its own.
  8806. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8807. LastElement[i] = i;
  8808. PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
  8809. // Search for a solution that results in fewer partitions.
  8810. for (int64_t j = N - 1; j > i; j--) {
  8811. // Try building a partition from Clusters[i..j].
  8812. uint64_t Range = getJumpTableRange(Clusters, i, j);
  8813. uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
  8814. assert(NumCases < UINT64_MAX / 100);
  8815. assert(Range >= NumCases);
  8816. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8817. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8818. unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
  8819. int64_t NumEntries = j - i + 1;
  8820. if (NumEntries == 1)
  8821. Score += PartitionScores::SingleCase;
  8822. else if (NumEntries <= SmallNumberOfEntries)
  8823. Score += PartitionScores::FewCases;
  8824. else if (NumEntries >= MinJumpTableEntries)
  8825. Score += PartitionScores::Table;
  8826. // If this leads to fewer partitions, or to the same number of
  8827. // partitions with better score, it is a better partitioning.
  8828. if (NumPartitions < MinPartitions[i] ||
  8829. (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
  8830. MinPartitions[i] = NumPartitions;
  8831. LastElement[i] = j;
  8832. PartitionsScore[i] = Score;
  8833. }
  8834. }
  8835. }
  8836. }
  8837. // Iterate over the partitions, replacing some with jump tables in-place.
  8838. unsigned DstIndex = 0;
  8839. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8840. Last = LastElement[First];
  8841. assert(Last >= First);
  8842. assert(DstIndex <= First);
  8843. unsigned NumClusters = Last - First + 1;
  8844. CaseCluster JTCluster;
  8845. if (NumClusters >= MinJumpTableEntries &&
  8846. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  8847. Clusters[DstIndex++] = JTCluster;
  8848. } else {
  8849. for (unsigned I = First; I <= Last; ++I)
  8850. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  8851. }
  8852. }
  8853. Clusters.resize(DstIndex);
  8854. }
  8855. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  8856. unsigned First, unsigned Last,
  8857. const SwitchInst *SI,
  8858. CaseCluster &BTCluster) {
  8859. assert(First <= Last);
  8860. if (First == Last)
  8861. return false;
  8862. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8863. unsigned NumCmps = 0;
  8864. for (int64_t I = First; I <= Last; ++I) {
  8865. assert(Clusters[I].Kind == CC_Range);
  8866. Dests.set(Clusters[I].MBB->getNumber());
  8867. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  8868. }
  8869. unsigned NumDests = Dests.count();
  8870. APInt Low = Clusters[First].Low->getValue();
  8871. APInt High = Clusters[Last].High->getValue();
  8872. assert(Low.slt(High));
  8873. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8874. const DataLayout &DL = DAG.getDataLayout();
  8875. if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
  8876. return false;
  8877. APInt LowBound;
  8878. APInt CmpRange;
  8879. const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
  8880. assert(TLI.rangeFitsInWord(Low, High, DL) &&
  8881. "Case range must fit in bit mask!");
  8882. // Check if the clusters cover a contiguous range such that no value in the
  8883. // range will jump to the default statement.
  8884. bool ContiguousRange = true;
  8885. for (int64_t I = First + 1; I <= Last; ++I) {
  8886. if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
  8887. ContiguousRange = false;
  8888. break;
  8889. }
  8890. }
  8891. if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
  8892. // Optimize the case where all the case values fit in a word without having
  8893. // to subtract minValue. In this case, we can optimize away the subtraction.
  8894. LowBound = APInt::getNullValue(Low.getBitWidth());
  8895. CmpRange = High;
  8896. ContiguousRange = false;
  8897. } else {
  8898. LowBound = Low;
  8899. CmpRange = High - Low;
  8900. }
  8901. CaseBitsVector CBV;
  8902. auto TotalProb = BranchProbability::getZero();
  8903. for (unsigned i = First; i <= Last; ++i) {
  8904. // Find the CaseBits for this destination.
  8905. unsigned j;
  8906. for (j = 0; j < CBV.size(); ++j)
  8907. if (CBV[j].BB == Clusters[i].MBB)
  8908. break;
  8909. if (j == CBV.size())
  8910. CBV.push_back(
  8911. CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
  8912. CaseBits *CB = &CBV[j];
  8913. // Update Mask, Bits and ExtraProb.
  8914. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  8915. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  8916. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  8917. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  8918. CB->Bits += Hi - Lo + 1;
  8919. CB->ExtraProb += Clusters[i].Prob;
  8920. TotalProb += Clusters[i].Prob;
  8921. }
  8922. BitTestInfo BTI;
  8923. llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
  8924. // Sort by probability first, number of bits second, bit mask third.
  8925. if (a.ExtraProb != b.ExtraProb)
  8926. return a.ExtraProb > b.ExtraProb;
  8927. if (a.Bits != b.Bits)
  8928. return a.Bits > b.Bits;
  8929. return a.Mask < b.Mask;
  8930. });
  8931. for (auto &CB : CBV) {
  8932. MachineBasicBlock *BitTestBB =
  8933. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  8934. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
  8935. }
  8936. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  8937. SI->getCondition(), -1U, MVT::Other, false,
  8938. ContiguousRange, nullptr, nullptr, std::move(BTI),
  8939. TotalProb);
  8940. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  8941. BitTestCases.size() - 1, TotalProb);
  8942. return true;
  8943. }
  8944. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  8945. const SwitchInst *SI) {
  8946. // Partition Clusters into as few subsets as possible, where each subset has a
  8947. // range that fits in a machine word and has <= 3 unique destinations.
  8948. #ifndef NDEBUG
  8949. // Clusters must be sorted and contain Range or JumpTable clusters.
  8950. assert(!Clusters.empty());
  8951. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  8952. for (const CaseCluster &C : Clusters)
  8953. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  8954. for (unsigned i = 1; i < Clusters.size(); ++i)
  8955. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  8956. #endif
  8957. // The algorithm below is not suitable for -O0.
  8958. if (TM.getOptLevel() == CodeGenOpt::None)
  8959. return;
  8960. // If target does not have legal shift left, do not emit bit tests at all.
  8961. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8962. const DataLayout &DL = DAG.getDataLayout();
  8963. EVT PTy = TLI.getPointerTy(DL);
  8964. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  8965. return;
  8966. int BitWidth = PTy.getSizeInBits();
  8967. const int64_t N = Clusters.size();
  8968. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8969. SmallVector<unsigned, 8> MinPartitions(N);
  8970. // LastElement[i] is the last element of the partition starting at i.
  8971. SmallVector<unsigned, 8> LastElement(N);
  8972. // FIXME: This might not be the best algorithm for finding bit test clusters.
  8973. // Base case: There is only one way to partition Clusters[N-1].
  8974. MinPartitions[N - 1] = 1;
  8975. LastElement[N - 1] = N - 1;
  8976. // Note: loop indexes are signed to avoid underflow.
  8977. for (int64_t i = N - 2; i >= 0; --i) {
  8978. // Find optimal partitioning of Clusters[i..N-1].
  8979. // Baseline: Put Clusters[i] into a partition on its own.
  8980. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8981. LastElement[i] = i;
  8982. // Search for a solution that results in fewer partitions.
  8983. // Note: the search is limited by BitWidth, reducing time complexity.
  8984. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  8985. // Try building a partition from Clusters[i..j].
  8986. // Check the range.
  8987. if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
  8988. Clusters[j].High->getValue(), DL))
  8989. continue;
  8990. // Check nbr of destinations and cluster types.
  8991. // FIXME: This works, but doesn't seem very efficient.
  8992. bool RangesOnly = true;
  8993. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  8994. for (int64_t k = i; k <= j; k++) {
  8995. if (Clusters[k].Kind != CC_Range) {
  8996. RangesOnly = false;
  8997. break;
  8998. }
  8999. Dests.set(Clusters[k].MBB->getNumber());
  9000. }
  9001. if (!RangesOnly || Dests.count() > 3)
  9002. break;
  9003. // Check if it's a better partition.
  9004. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  9005. if (NumPartitions < MinPartitions[i]) {
  9006. // Found a better partition.
  9007. MinPartitions[i] = NumPartitions;
  9008. LastElement[i] = j;
  9009. }
  9010. }
  9011. }
  9012. // Iterate over the partitions, replacing with bit-test clusters in-place.
  9013. unsigned DstIndex = 0;
  9014. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  9015. Last = LastElement[First];
  9016. assert(First <= Last);
  9017. assert(DstIndex <= First);
  9018. CaseCluster BitTestCluster;
  9019. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  9020. Clusters[DstIndex++] = BitTestCluster;
  9021. } else {
  9022. size_t NumClusters = Last - First + 1;
  9023. std::memmove(&Clusters[DstIndex], &Clusters[First],
  9024. sizeof(Clusters[0]) * NumClusters);
  9025. DstIndex += NumClusters;
  9026. }
  9027. }
  9028. Clusters.resize(DstIndex);
  9029. }
  9030. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  9031. MachineBasicBlock *SwitchMBB,
  9032. MachineBasicBlock *DefaultMBB) {
  9033. MachineFunction *CurMF = FuncInfo.MF;
  9034. MachineBasicBlock *NextMBB = nullptr;
  9035. MachineFunction::iterator BBI(W.MBB);
  9036. if (++BBI != FuncInfo.MF->end())
  9037. NextMBB = &*BBI;
  9038. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  9039. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9040. if (Size == 2 && W.MBB == SwitchMBB) {
  9041. // If any two of the cases has the same destination, and if one value
  9042. // is the same as the other, but has one bit unset that the other has set,
  9043. // use bit manipulation to do two compares at once. For example:
  9044. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  9045. // TODO: This could be extended to merge any 2 cases in switches with 3
  9046. // cases.
  9047. // TODO: Handle cases where W.CaseBB != SwitchBB.
  9048. CaseCluster &Small = *W.FirstCluster;
  9049. CaseCluster &Big = *W.LastCluster;
  9050. if (Small.Low == Small.High && Big.Low == Big.High &&
  9051. Small.MBB == Big.MBB) {
  9052. const APInt &SmallValue = Small.Low->getValue();
  9053. const APInt &BigValue = Big.Low->getValue();
  9054. // Check that there is only one bit different.
  9055. APInt CommonBit = BigValue ^ SmallValue;
  9056. if (CommonBit.isPowerOf2()) {
  9057. SDValue CondLHS = getValue(Cond);
  9058. EVT VT = CondLHS.getValueType();
  9059. SDLoc DL = getCurSDLoc();
  9060. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  9061. DAG.getConstant(CommonBit, DL, VT));
  9062. SDValue Cond = DAG.getSetCC(
  9063. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  9064. ISD::SETEQ);
  9065. // Update successor info.
  9066. // Both Small and Big will jump to Small.BB, so we sum up the
  9067. // probabilities.
  9068. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  9069. if (BPI)
  9070. addSuccessorWithProb(
  9071. SwitchMBB, DefaultMBB,
  9072. // The default destination is the first successor in IR.
  9073. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  9074. else
  9075. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  9076. // Insert the true branch.
  9077. SDValue BrCond =
  9078. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  9079. DAG.getBasicBlock(Small.MBB));
  9080. // Insert the false branch.
  9081. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  9082. DAG.getBasicBlock(DefaultMBB));
  9083. DAG.setRoot(BrCond);
  9084. return;
  9085. }
  9086. }
  9087. }
  9088. if (TM.getOptLevel() != CodeGenOpt::None) {
  9089. // Here, we order cases by probability so the most likely case will be
  9090. // checked first. However, two clusters can have the same probability in
  9091. // which case their relative ordering is non-deterministic. So we use Low
  9092. // as a tie-breaker as clusters are guaranteed to never overlap.
  9093. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  9094. [](const CaseCluster &a, const CaseCluster &b) {
  9095. return a.Prob != b.Prob ?
  9096. a.Prob > b.Prob :
  9097. a.Low->getValue().slt(b.Low->getValue());
  9098. });
  9099. // Rearrange the case blocks so that the last one falls through if possible
  9100. // without changing the order of probabilities.
  9101. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  9102. --I;
  9103. if (I->Prob > W.LastCluster->Prob)
  9104. break;
  9105. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  9106. std::swap(*I, *W.LastCluster);
  9107. break;
  9108. }
  9109. }
  9110. }
  9111. // Compute total probability.
  9112. BranchProbability DefaultProb = W.DefaultProb;
  9113. BranchProbability UnhandledProbs = DefaultProb;
  9114. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  9115. UnhandledProbs += I->Prob;
  9116. MachineBasicBlock *CurMBB = W.MBB;
  9117. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  9118. bool FallthroughUnreachable = false;
  9119. MachineBasicBlock *Fallthrough;
  9120. if (I == W.LastCluster) {
  9121. // For the last cluster, fall through to the default destination.
  9122. Fallthrough = DefaultMBB;
  9123. FallthroughUnreachable = isa<UnreachableInst>(
  9124. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  9125. } else {
  9126. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  9127. CurMF->insert(BBI, Fallthrough);
  9128. // Put Cond in a virtual register to make it available from the new blocks.
  9129. ExportFromCurrentBlock(Cond);
  9130. }
  9131. UnhandledProbs -= I->Prob;
  9132. switch (I->Kind) {
  9133. case CC_JumpTable: {
  9134. // FIXME: Optimize away range check based on pivot comparisons.
  9135. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  9136. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  9137. // The jump block hasn't been inserted yet; insert it here.
  9138. MachineBasicBlock *JumpMBB = JT->MBB;
  9139. CurMF->insert(BBI, JumpMBB);
  9140. auto JumpProb = I->Prob;
  9141. auto FallthroughProb = UnhandledProbs;
  9142. // If the default statement is a target of the jump table, we evenly
  9143. // distribute the default probability to successors of CurMBB. Also
  9144. // update the probability on the edge from JumpMBB to Fallthrough.
  9145. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  9146. SE = JumpMBB->succ_end();
  9147. SI != SE; ++SI) {
  9148. if (*SI == DefaultMBB) {
  9149. JumpProb += DefaultProb / 2;
  9150. FallthroughProb -= DefaultProb / 2;
  9151. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  9152. JumpMBB->normalizeSuccProbs();
  9153. break;
  9154. }
  9155. }
  9156. if (FallthroughUnreachable) {
  9157. // Skip the range check if the fallthrough block is unreachable.
  9158. JTH->OmitRangeCheck = true;
  9159. }
  9160. if (!JTH->OmitRangeCheck)
  9161. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  9162. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  9163. CurMBB->normalizeSuccProbs();
  9164. // The jump table header will be inserted in our current block, do the
  9165. // range check, and fall through to our fallthrough block.
  9166. JTH->HeaderBB = CurMBB;
  9167. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  9168. // If we're in the right place, emit the jump table header right now.
  9169. if (CurMBB == SwitchMBB) {
  9170. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  9171. JTH->Emitted = true;
  9172. }
  9173. break;
  9174. }
  9175. case CC_BitTests: {
  9176. // FIXME: If Fallthrough is unreachable, skip the range check.
  9177. // FIXME: Optimize away range check based on pivot comparisons.
  9178. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  9179. // The bit test blocks haven't been inserted yet; insert them here.
  9180. for (BitTestCase &BTC : BTB->Cases)
  9181. CurMF->insert(BBI, BTC.ThisBB);
  9182. // Fill in fields of the BitTestBlock.
  9183. BTB->Parent = CurMBB;
  9184. BTB->Default = Fallthrough;
  9185. BTB->DefaultProb = UnhandledProbs;
  9186. // If the cases in bit test don't form a contiguous range, we evenly
  9187. // distribute the probability on the edge to Fallthrough to two
  9188. // successors of CurMBB.
  9189. if (!BTB->ContiguousRange) {
  9190. BTB->Prob += DefaultProb / 2;
  9191. BTB->DefaultProb -= DefaultProb / 2;
  9192. }
  9193. // If we're in the right place, emit the bit test header right now.
  9194. if (CurMBB == SwitchMBB) {
  9195. visitBitTestHeader(*BTB, SwitchMBB);
  9196. BTB->Emitted = true;
  9197. }
  9198. break;
  9199. }
  9200. case CC_Range: {
  9201. const Value *RHS, *LHS, *MHS;
  9202. ISD::CondCode CC;
  9203. if (I->Low == I->High) {
  9204. // Check Cond == I->Low.
  9205. CC = ISD::SETEQ;
  9206. LHS = Cond;
  9207. RHS=I->Low;
  9208. MHS = nullptr;
  9209. } else {
  9210. // Check I->Low <= Cond <= I->High.
  9211. CC = ISD::SETLE;
  9212. LHS = I->Low;
  9213. MHS = Cond;
  9214. RHS = I->High;
  9215. }
  9216. // If Fallthrough is unreachable, fold away the comparison.
  9217. if (FallthroughUnreachable)
  9218. CC = ISD::SETTRUE;
  9219. // The false probability is the sum of all unhandled cases.
  9220. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9221. getCurSDLoc(), I->Prob, UnhandledProbs);
  9222. if (CurMBB == SwitchMBB)
  9223. visitSwitchCase(CB, SwitchMBB);
  9224. else
  9225. SwitchCases.push_back(CB);
  9226. break;
  9227. }
  9228. }
  9229. CurMBB = Fallthrough;
  9230. }
  9231. }
  9232. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9233. CaseClusterIt First,
  9234. CaseClusterIt Last) {
  9235. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9236. if (X.Prob != CC.Prob)
  9237. return X.Prob > CC.Prob;
  9238. // Ties are broken by comparing the case value.
  9239. return X.Low->getValue().slt(CC.Low->getValue());
  9240. });
  9241. }
  9242. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9243. const SwitchWorkListItem &W,
  9244. Value *Cond,
  9245. MachineBasicBlock *SwitchMBB) {
  9246. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9247. "Clusters not sorted?");
  9248. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9249. // Balance the tree based on branch probabilities to create a near-optimal (in
  9250. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9251. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9252. CaseClusterIt LastLeft = W.FirstCluster;
  9253. CaseClusterIt FirstRight = W.LastCluster;
  9254. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9255. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9256. // Move LastLeft and FirstRight towards each other from opposite directions to
  9257. // find a partitioning of the clusters which balances the probability on both
  9258. // sides. If LeftProb and RightProb are equal, alternate which side is
  9259. // taken to ensure 0-probability nodes are distributed evenly.
  9260. unsigned I = 0;
  9261. while (LastLeft + 1 < FirstRight) {
  9262. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9263. LeftProb += (++LastLeft)->Prob;
  9264. else
  9265. RightProb += (--FirstRight)->Prob;
  9266. I++;
  9267. }
  9268. while (true) {
  9269. // Our binary search tree differs from a typical BST in that ours can have up
  9270. // to three values in each leaf. The pivot selection above doesn't take that
  9271. // into account, which means the tree might require more nodes and be less
  9272. // efficient. We compensate for this here.
  9273. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9274. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9275. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9276. // If one side has less than 3 clusters, and the other has more than 3,
  9277. // consider taking a cluster from the other side.
  9278. if (NumLeft < NumRight) {
  9279. // Consider moving the first cluster on the right to the left side.
  9280. CaseCluster &CC = *FirstRight;
  9281. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9282. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9283. if (LeftSideRank <= RightSideRank) {
  9284. // Moving the cluster to the left does not demote it.
  9285. ++LastLeft;
  9286. ++FirstRight;
  9287. continue;
  9288. }
  9289. } else {
  9290. assert(NumRight < NumLeft);
  9291. // Consider moving the last element on the left to the right side.
  9292. CaseCluster &CC = *LastLeft;
  9293. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9294. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9295. if (RightSideRank <= LeftSideRank) {
  9296. // Moving the cluster to the right does not demot it.
  9297. --LastLeft;
  9298. --FirstRight;
  9299. continue;
  9300. }
  9301. }
  9302. }
  9303. break;
  9304. }
  9305. assert(LastLeft + 1 == FirstRight);
  9306. assert(LastLeft >= W.FirstCluster);
  9307. assert(FirstRight <= W.LastCluster);
  9308. // Use the first element on the right as pivot since we will make less-than
  9309. // comparisons against it.
  9310. CaseClusterIt PivotCluster = FirstRight;
  9311. assert(PivotCluster > W.FirstCluster);
  9312. assert(PivotCluster <= W.LastCluster);
  9313. CaseClusterIt FirstLeft = W.FirstCluster;
  9314. CaseClusterIt LastRight = W.LastCluster;
  9315. const ConstantInt *Pivot = PivotCluster->Low;
  9316. // New blocks will be inserted immediately after the current one.
  9317. MachineFunction::iterator BBI(W.MBB);
  9318. ++BBI;
  9319. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9320. // we can branch to its destination directly if it's squeezed exactly in
  9321. // between the known lower bound and Pivot - 1.
  9322. MachineBasicBlock *LeftMBB;
  9323. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9324. FirstLeft->Low == W.GE &&
  9325. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9326. LeftMBB = FirstLeft->MBB;
  9327. } else {
  9328. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9329. FuncInfo.MF->insert(BBI, LeftMBB);
  9330. WorkList.push_back(
  9331. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9332. // Put Cond in a virtual register to make it available from the new blocks.
  9333. ExportFromCurrentBlock(Cond);
  9334. }
  9335. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9336. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9337. // directly if RHS.High equals the current upper bound.
  9338. MachineBasicBlock *RightMBB;
  9339. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9340. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9341. RightMBB = FirstRight->MBB;
  9342. } else {
  9343. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9344. FuncInfo.MF->insert(BBI, RightMBB);
  9345. WorkList.push_back(
  9346. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9347. // Put Cond in a virtual register to make it available from the new blocks.
  9348. ExportFromCurrentBlock(Cond);
  9349. }
  9350. // Create the CaseBlock record that will be used to lower the branch.
  9351. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9352. getCurSDLoc(), LeftProb, RightProb);
  9353. if (W.MBB == SwitchMBB)
  9354. visitSwitchCase(CB, SwitchMBB);
  9355. else
  9356. SwitchCases.push_back(CB);
  9357. }
  9358. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9359. // from the swith statement.
  9360. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9361. BranchProbability PeeledCaseProb) {
  9362. if (PeeledCaseProb == BranchProbability::getOne())
  9363. return BranchProbability::getZero();
  9364. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9365. uint32_t Numerator = CaseProb.getNumerator();
  9366. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9367. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9368. }
  9369. // Try to peel the top probability case if it exceeds the threshold.
  9370. // Return current MachineBasicBlock for the switch statement if the peeling
  9371. // does not occur.
  9372. // If the peeling is performed, return the newly created MachineBasicBlock
  9373. // for the peeled switch statement. Also update Clusters to remove the peeled
  9374. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9375. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9376. const SwitchInst &SI, CaseClusterVector &Clusters,
  9377. BranchProbability &PeeledCaseProb) {
  9378. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9379. // Don't perform if there is only one cluster or optimizing for size.
  9380. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9381. TM.getOptLevel() == CodeGenOpt::None ||
  9382. SwitchMBB->getParent()->getFunction().hasMinSize())
  9383. return SwitchMBB;
  9384. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9385. unsigned PeeledCaseIndex = 0;
  9386. bool SwitchPeeled = false;
  9387. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9388. CaseCluster &CC = Clusters[Index];
  9389. if (CC.Prob < TopCaseProb)
  9390. continue;
  9391. TopCaseProb = CC.Prob;
  9392. PeeledCaseIndex = Index;
  9393. SwitchPeeled = true;
  9394. }
  9395. if (!SwitchPeeled)
  9396. return SwitchMBB;
  9397. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9398. << TopCaseProb << "\n");
  9399. // Record the MBB for the peeled switch statement.
  9400. MachineFunction::iterator BBI(SwitchMBB);
  9401. ++BBI;
  9402. MachineBasicBlock *PeeledSwitchMBB =
  9403. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9404. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9405. ExportFromCurrentBlock(SI.getCondition());
  9406. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9407. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9408. nullptr, nullptr, TopCaseProb.getCompl()};
  9409. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9410. Clusters.erase(PeeledCaseIt);
  9411. for (CaseCluster &CC : Clusters) {
  9412. LLVM_DEBUG(
  9413. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9414. << CC.Prob << "\n");
  9415. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9416. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9417. }
  9418. PeeledCaseProb = TopCaseProb;
  9419. return PeeledSwitchMBB;
  9420. }
  9421. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9422. // Extract cases from the switch.
  9423. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9424. CaseClusterVector Clusters;
  9425. Clusters.reserve(SI.getNumCases());
  9426. for (auto I : SI.cases()) {
  9427. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9428. const ConstantInt *CaseVal = I.getCaseValue();
  9429. BranchProbability Prob =
  9430. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9431. : BranchProbability(1, SI.getNumCases() + 1);
  9432. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9433. }
  9434. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9435. // Cluster adjacent cases with the same destination. We do this at all
  9436. // optimization levels because it's cheap to do and will make codegen faster
  9437. // if there are many clusters.
  9438. sortAndRangeify(Clusters);
  9439. // The branch probablity of the peeled case.
  9440. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9441. MachineBasicBlock *PeeledSwitchMBB =
  9442. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9443. // If there is only the default destination, jump there directly.
  9444. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9445. if (Clusters.empty()) {
  9446. assert(PeeledSwitchMBB == SwitchMBB);
  9447. SwitchMBB->addSuccessor(DefaultMBB);
  9448. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9449. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9450. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9451. }
  9452. return;
  9453. }
  9454. findJumpTables(Clusters, &SI, DefaultMBB);
  9455. findBitTestClusters(Clusters, &SI);
  9456. LLVM_DEBUG({
  9457. dbgs() << "Case clusters: ";
  9458. for (const CaseCluster &C : Clusters) {
  9459. if (C.Kind == CC_JumpTable)
  9460. dbgs() << "JT:";
  9461. if (C.Kind == CC_BitTests)
  9462. dbgs() << "BT:";
  9463. C.Low->getValue().print(dbgs(), true);
  9464. if (C.Low != C.High) {
  9465. dbgs() << '-';
  9466. C.High->getValue().print(dbgs(), true);
  9467. }
  9468. dbgs() << ' ';
  9469. }
  9470. dbgs() << '\n';
  9471. });
  9472. assert(!Clusters.empty());
  9473. SwitchWorkList WorkList;
  9474. CaseClusterIt First = Clusters.begin();
  9475. CaseClusterIt Last = Clusters.end() - 1;
  9476. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9477. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9478. // DefaultMBB is not replaced.
  9479. if (PeeledCaseProb != BranchProbability::getZero() &&
  9480. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9481. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9482. WorkList.push_back(
  9483. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9484. while (!WorkList.empty()) {
  9485. SwitchWorkListItem W = WorkList.back();
  9486. WorkList.pop_back();
  9487. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9488. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9489. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9490. // For optimized builds, lower large range as a balanced binary tree.
  9491. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9492. continue;
  9493. }
  9494. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9495. }
  9496. }