SelectionDAGBuilder.cpp 423 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916
  1. //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "SelectionDAGBuilder.h"
  13. #include "SDNodeDbgValue.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Analysis/AliasAnalysis.h"
  29. #include "llvm/Analysis/BranchProbabilityInfo.h"
  30. #include "llvm/Analysis/ConstantFolding.h"
  31. #include "llvm/Analysis/EHPersonalities.h"
  32. #include "llvm/Analysis/Loads.h"
  33. #include "llvm/Analysis/MemoryLocation.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/ValueTracking.h"
  36. #include "llvm/Analysis/VectorUtils.h"
  37. #include "llvm/CodeGen/Analysis.h"
  38. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  39. #include "llvm/CodeGen/GCMetadata.h"
  40. #include "llvm/CodeGen/ISDOpcodes.h"
  41. #include "llvm/CodeGen/MachineBasicBlock.h"
  42. #include "llvm/CodeGen/MachineFrameInfo.h"
  43. #include "llvm/CodeGen/MachineFunction.h"
  44. #include "llvm/CodeGen/MachineInstr.h"
  45. #include "llvm/CodeGen/MachineInstrBuilder.h"
  46. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  47. #include "llvm/CodeGen/MachineMemOperand.h"
  48. #include "llvm/CodeGen/MachineModuleInfo.h"
  49. #include "llvm/CodeGen/MachineOperand.h"
  50. #include "llvm/CodeGen/MachineRegisterInfo.h"
  51. #include "llvm/CodeGen/RuntimeLibcalls.h"
  52. #include "llvm/CodeGen/SelectionDAG.h"
  53. #include "llvm/CodeGen/SelectionDAGNodes.h"
  54. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  55. #include "llvm/CodeGen/StackMaps.h"
  56. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  57. #include "llvm/CodeGen/TargetFrameLowering.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetLowering.h"
  60. #include "llvm/CodeGen/TargetOpcodes.h"
  61. #include "llvm/CodeGen/TargetRegisterInfo.h"
  62. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  63. #include "llvm/CodeGen/ValueTypes.h"
  64. #include "llvm/CodeGen/WinEHFuncInfo.h"
  65. #include "llvm/IR/Argument.h"
  66. #include "llvm/IR/Attributes.h"
  67. #include "llvm/IR/BasicBlock.h"
  68. #include "llvm/IR/CFG.h"
  69. #include "llvm/IR/CallSite.h"
  70. #include "llvm/IR/CallingConv.h"
  71. #include "llvm/IR/Constant.h"
  72. #include "llvm/IR/ConstantRange.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfoMetadata.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/InlineAsm.h"
  81. #include "llvm/IR/InstrTypes.h"
  82. #include "llvm/IR/Instruction.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/Intrinsics.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Metadata.h"
  88. #include "llvm/IR/Module.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/PatternMatch.h"
  91. #include "llvm/IR/Statepoint.h"
  92. #include "llvm/IR/Type.h"
  93. #include "llvm/IR/User.h"
  94. #include "llvm/IR/Value.h"
  95. #include "llvm/MC/MCContext.h"
  96. #include "llvm/MC/MCSymbol.h"
  97. #include "llvm/Support/AtomicOrdering.h"
  98. #include "llvm/Support/BranchProbability.h"
  99. #include "llvm/Support/Casting.h"
  100. #include "llvm/Support/CodeGen.h"
  101. #include "llvm/Support/CommandLine.h"
  102. #include "llvm/Support/Compiler.h"
  103. #include "llvm/Support/Debug.h"
  104. #include "llvm/Support/ErrorHandling.h"
  105. #include "llvm/Support/MachineValueType.h"
  106. #include "llvm/Support/MathExtras.h"
  107. #include "llvm/Support/raw_ostream.h"
  108. #include "llvm/Target/TargetIntrinsicInfo.h"
  109. #include "llvm/Target/TargetMachine.h"
  110. #include "llvm/Target/TargetOptions.h"
  111. #include "llvm/Transforms/Utils/Local.h"
  112. #include <algorithm>
  113. #include <cassert>
  114. #include <cstddef>
  115. #include <cstdint>
  116. #include <cstring>
  117. #include <iterator>
  118. #include <limits>
  119. #include <numeric>
  120. #include <tuple>
  121. #include <utility>
  122. #include <vector>
  123. using namespace llvm;
  124. using namespace PatternMatch;
  125. #define DEBUG_TYPE "isel"
  126. /// LimitFloatPrecision - Generate low-precision inline sequences for
  127. /// some float libcalls (6, 8 or 12 bits).
  128. static unsigned LimitFloatPrecision;
  129. static cl::opt<unsigned, true>
  130. LimitFPPrecision("limit-float-precision",
  131. cl::desc("Generate low-precision inline sequences "
  132. "for some float libcalls"),
  133. cl::location(LimitFloatPrecision), cl::Hidden,
  134. cl::init(0));
  135. static cl::opt<unsigned> SwitchPeelThreshold(
  136. "switch-peel-threshold", cl::Hidden, cl::init(66),
  137. cl::desc("Set the case probability threshold for peeling the case from a "
  138. "switch statement. A value greater than 100 will void this "
  139. "optimization"));
  140. // Limit the width of DAG chains. This is important in general to prevent
  141. // DAG-based analysis from blowing up. For example, alias analysis and
  142. // load clustering may not complete in reasonable time. It is difficult to
  143. // recognize and avoid this situation within each individual analysis, and
  144. // future analyses are likely to have the same behavior. Limiting DAG width is
  145. // the safe approach and will be especially important with global DAGs.
  146. //
  147. // MaxParallelChains default is arbitrarily high to avoid affecting
  148. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  149. // sequence over this should have been converted to llvm.memcpy by the
  150. // frontend. It is easy to induce this behavior with .ll code such as:
  151. // %buffer = alloca [4096 x i8]
  152. // %data = load [4096 x i8]* %argPtr
  153. // store [4096 x i8] %data, [4096 x i8]* %buffer
  154. static const unsigned MaxParallelChains = 64;
  155. // Return the calling convention if the Value passed requires ABI mangling as it
  156. // is a parameter to a function or a return value from a function which is not
  157. // an intrinsic.
  158. static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
  159. if (auto *R = dyn_cast<ReturnInst>(V))
  160. return R->getParent()->getParent()->getCallingConv();
  161. if (auto *CI = dyn_cast<CallInst>(V)) {
  162. const bool IsInlineAsm = CI->isInlineAsm();
  163. const bool IsIndirectFunctionCall =
  164. !IsInlineAsm && !CI->getCalledFunction();
  165. // It is possible that the call instruction is an inline asm statement or an
  166. // indirect function call in which case the return value of
  167. // getCalledFunction() would be nullptr.
  168. const bool IsInstrinsicCall =
  169. !IsInlineAsm && !IsIndirectFunctionCall &&
  170. CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
  171. if (!IsInlineAsm && !IsInstrinsicCall)
  172. return CI->getCallingConv();
  173. }
  174. return None;
  175. }
  176. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  177. const SDValue *Parts, unsigned NumParts,
  178. MVT PartVT, EVT ValueVT, const Value *V,
  179. Optional<CallingConv::ID> CC);
  180. /// getCopyFromParts - Create a value that contains the specified legal parts
  181. /// combined into the value they represent. If the parts combine to a type
  182. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  183. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  184. /// (ISD::AssertSext).
  185. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  186. const SDValue *Parts, unsigned NumParts,
  187. MVT PartVT, EVT ValueVT, const Value *V,
  188. Optional<CallingConv::ID> CC = None,
  189. Optional<ISD::NodeType> AssertOp = None) {
  190. if (ValueVT.isVector())
  191. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  192. CC);
  193. assert(NumParts > 0 && "No parts to assemble!");
  194. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  195. SDValue Val = Parts[0];
  196. if (NumParts > 1) {
  197. // Assemble the value from multiple parts.
  198. if (ValueVT.isInteger()) {
  199. unsigned PartBits = PartVT.getSizeInBits();
  200. unsigned ValueBits = ValueVT.getSizeInBits();
  201. // Assemble the power of 2 part.
  202. unsigned RoundParts =
  203. (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
  204. unsigned RoundBits = PartBits * RoundParts;
  205. EVT RoundVT = RoundBits == ValueBits ?
  206. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  207. SDValue Lo, Hi;
  208. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  209. if (RoundParts > 2) {
  210. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  211. PartVT, HalfVT, V);
  212. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  213. RoundParts / 2, PartVT, HalfVT, V);
  214. } else {
  215. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  216. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  217. }
  218. if (DAG.getDataLayout().isBigEndian())
  219. std::swap(Lo, Hi);
  220. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  221. if (RoundParts < NumParts) {
  222. // Assemble the trailing non-power-of-2 part.
  223. unsigned OddParts = NumParts - RoundParts;
  224. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  225. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  226. OddVT, V, CC);
  227. // Combine the round and odd parts.
  228. Lo = Val;
  229. if (DAG.getDataLayout().isBigEndian())
  230. std::swap(Lo, Hi);
  231. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  232. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  233. Hi =
  234. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  235. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  236. TLI.getPointerTy(DAG.getDataLayout())));
  237. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  238. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  239. }
  240. } else if (PartVT.isFloatingPoint()) {
  241. // FP split into multiple FP parts (for ppcf128)
  242. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  243. "Unexpected split");
  244. SDValue Lo, Hi;
  245. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  246. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  247. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  248. std::swap(Lo, Hi);
  249. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  250. } else {
  251. // FP split into integer parts (soft fp)
  252. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  253. !PartVT.isVector() && "Unexpected split");
  254. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  255. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  256. }
  257. }
  258. // There is now one part, held in Val. Correct it to match ValueVT.
  259. // PartEVT is the type of the register class that holds the value.
  260. // ValueVT is the type of the inline asm operation.
  261. EVT PartEVT = Val.getValueType();
  262. if (PartEVT == ValueVT)
  263. return Val;
  264. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  265. ValueVT.bitsLT(PartEVT)) {
  266. // For an FP value in an integer part, we need to truncate to the right
  267. // width first.
  268. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  269. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  270. }
  271. // Handle types that have the same size.
  272. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  273. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  274. // Handle types with different sizes.
  275. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  276. if (ValueVT.bitsLT(PartEVT)) {
  277. // For a truncate, see if we have any information to
  278. // indicate whether the truncated bits will always be
  279. // zero or sign-extension.
  280. if (AssertOp.hasValue())
  281. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  282. DAG.getValueType(ValueVT));
  283. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  284. }
  285. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  286. }
  287. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  288. // FP_ROUND's are always exact here.
  289. if (ValueVT.bitsLT(Val.getValueType()))
  290. return DAG.getNode(
  291. ISD::FP_ROUND, DL, ValueVT, Val,
  292. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  293. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  294. }
  295. // Handle MMX to a narrower integer type by bitcasting MMX to integer and
  296. // then truncating.
  297. if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
  298. ValueVT.bitsLT(PartEVT)) {
  299. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
  300. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  301. }
  302. report_fatal_error("Unknown mismatch in getCopyFromParts!");
  303. }
  304. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  305. const Twine &ErrMsg) {
  306. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  307. if (!V)
  308. return Ctx.emitError(ErrMsg);
  309. const char *AsmError = ", possible invalid constraint for vector type";
  310. if (const CallInst *CI = dyn_cast<CallInst>(I))
  311. if (isa<InlineAsm>(CI->getCalledValue()))
  312. return Ctx.emitError(I, ErrMsg + AsmError);
  313. return Ctx.emitError(I, ErrMsg);
  314. }
  315. /// getCopyFromPartsVector - Create a value that contains the specified legal
  316. /// parts combined into the value they represent. If the parts combine to a
  317. /// type larger than ValueVT then AssertOp can be used to specify whether the
  318. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  319. /// ValueVT (ISD::AssertSext).
  320. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  321. const SDValue *Parts, unsigned NumParts,
  322. MVT PartVT, EVT ValueVT, const Value *V,
  323. Optional<CallingConv::ID> CallConv) {
  324. assert(ValueVT.isVector() && "Not a vector value");
  325. assert(NumParts > 0 && "No parts to assemble!");
  326. const bool IsABIRegCopy = CallConv.hasValue();
  327. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  328. SDValue Val = Parts[0];
  329. // Handle a multi-element vector.
  330. if (NumParts > 1) {
  331. EVT IntermediateVT;
  332. MVT RegisterVT;
  333. unsigned NumIntermediates;
  334. unsigned NumRegs;
  335. if (IsABIRegCopy) {
  336. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  337. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  338. NumIntermediates, RegisterVT);
  339. } else {
  340. NumRegs =
  341. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  342. NumIntermediates, RegisterVT);
  343. }
  344. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  345. NumParts = NumRegs; // Silence a compiler warning.
  346. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  347. assert(RegisterVT.getSizeInBits() ==
  348. Parts[0].getSimpleValueType().getSizeInBits() &&
  349. "Part type sizes don't match!");
  350. // Assemble the parts into intermediate operands.
  351. SmallVector<SDValue, 8> Ops(NumIntermediates);
  352. if (NumIntermediates == NumParts) {
  353. // If the register was not expanded, truncate or copy the value,
  354. // as appropriate.
  355. for (unsigned i = 0; i != NumParts; ++i)
  356. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  357. PartVT, IntermediateVT, V);
  358. } else if (NumParts > 0) {
  359. // If the intermediate type was expanded, build the intermediate
  360. // operands from the parts.
  361. assert(NumParts % NumIntermediates == 0 &&
  362. "Must expand into a divisible number of parts!");
  363. unsigned Factor = NumParts / NumIntermediates;
  364. for (unsigned i = 0; i != NumIntermediates; ++i)
  365. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  366. PartVT, IntermediateVT, V);
  367. }
  368. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  369. // intermediate operands.
  370. EVT BuiltVectorTy =
  371. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  372. (IntermediateVT.isVector()
  373. ? IntermediateVT.getVectorNumElements() * NumParts
  374. : NumIntermediates));
  375. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  376. : ISD::BUILD_VECTOR,
  377. DL, BuiltVectorTy, Ops);
  378. }
  379. // There is now one part, held in Val. Correct it to match ValueVT.
  380. EVT PartEVT = Val.getValueType();
  381. if (PartEVT == ValueVT)
  382. return Val;
  383. if (PartEVT.isVector()) {
  384. // If the element type of the source/dest vectors are the same, but the
  385. // parts vector has more elements than the value vector, then we have a
  386. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  387. // elements we want.
  388. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  389. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  390. "Cannot narrow, it would be a lossy transformation");
  391. return DAG.getNode(
  392. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  393. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  394. }
  395. // Vector/Vector bitcast.
  396. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  397. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  398. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  399. "Cannot handle this kind of promotion");
  400. // Promoted vector extract
  401. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  402. }
  403. // Trivial bitcast if the types are the same size and the destination
  404. // vector type is legal.
  405. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  406. TLI.isTypeLegal(ValueVT))
  407. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  408. if (ValueVT.getVectorNumElements() != 1) {
  409. // Certain ABIs require that vectors are passed as integers. For vectors
  410. // are the same size, this is an obvious bitcast.
  411. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  412. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  413. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  414. // Bitcast Val back the original type and extract the corresponding
  415. // vector we want.
  416. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  417. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  418. ValueVT.getVectorElementType(), Elts);
  419. Val = DAG.getBitcast(WiderVecType, Val);
  420. return DAG.getNode(
  421. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  422. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  423. }
  424. diagnosePossiblyInvalidConstraint(
  425. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  426. return DAG.getUNDEF(ValueVT);
  427. }
  428. // Handle cases such as i8 -> <1 x i1>
  429. EVT ValueSVT = ValueVT.getVectorElementType();
  430. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  431. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  432. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  433. return DAG.getBuildVector(ValueVT, DL, Val);
  434. }
  435. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  436. SDValue Val, SDValue *Parts, unsigned NumParts,
  437. MVT PartVT, const Value *V,
  438. Optional<CallingConv::ID> CallConv);
  439. /// getCopyToParts - Create a series of nodes that contain the specified value
  440. /// split into legal parts. If the parts contain more bits than Val, then, for
  441. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  442. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  443. SDValue *Parts, unsigned NumParts, MVT PartVT,
  444. const Value *V,
  445. Optional<CallingConv::ID> CallConv = None,
  446. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  447. EVT ValueVT = Val.getValueType();
  448. // Handle the vector case separately.
  449. if (ValueVT.isVector())
  450. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  451. CallConv);
  452. unsigned PartBits = PartVT.getSizeInBits();
  453. unsigned OrigNumParts = NumParts;
  454. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  455. "Copying to an illegal type!");
  456. if (NumParts == 0)
  457. return;
  458. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  459. EVT PartEVT = PartVT;
  460. if (PartEVT == ValueVT) {
  461. assert(NumParts == 1 && "No-op copy with multiple parts!");
  462. Parts[0] = Val;
  463. return;
  464. }
  465. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  466. // If the parts cover more bits than the value has, promote the value.
  467. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  468. assert(NumParts == 1 && "Do not know what to promote to!");
  469. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  470. } else {
  471. if (ValueVT.isFloatingPoint()) {
  472. // FP values need to be bitcast, then extended if they are being put
  473. // into a larger container.
  474. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  475. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  476. }
  477. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  478. ValueVT.isInteger() &&
  479. "Unknown mismatch!");
  480. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  481. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  482. if (PartVT == MVT::x86mmx)
  483. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  484. }
  485. } else if (PartBits == ValueVT.getSizeInBits()) {
  486. // Different types of the same size.
  487. assert(NumParts == 1 && PartEVT != ValueVT);
  488. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  489. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  490. // If the parts cover less bits than value has, truncate the value.
  491. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  492. ValueVT.isInteger() &&
  493. "Unknown mismatch!");
  494. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  495. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  496. if (PartVT == MVT::x86mmx)
  497. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  498. }
  499. // The value may have changed - recompute ValueVT.
  500. ValueVT = Val.getValueType();
  501. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  502. "Failed to tile the value with PartVT!");
  503. if (NumParts == 1) {
  504. if (PartEVT != ValueVT) {
  505. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  506. "scalar-to-vector conversion failed");
  507. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  508. }
  509. Parts[0] = Val;
  510. return;
  511. }
  512. // Expand the value into multiple parts.
  513. if (NumParts & (NumParts - 1)) {
  514. // The number of parts is not a power of 2. Split off and copy the tail.
  515. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  516. "Do not know what to expand to!");
  517. unsigned RoundParts = 1 << Log2_32(NumParts);
  518. unsigned RoundBits = RoundParts * PartBits;
  519. unsigned OddParts = NumParts - RoundParts;
  520. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  521. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  522. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  523. CallConv);
  524. if (DAG.getDataLayout().isBigEndian())
  525. // The odd parts were reversed by getCopyToParts - unreverse them.
  526. std::reverse(Parts + RoundParts, Parts + NumParts);
  527. NumParts = RoundParts;
  528. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  529. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  530. }
  531. // The number of parts is a power of 2. Repeatedly bisect the value using
  532. // EXTRACT_ELEMENT.
  533. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  534. EVT::getIntegerVT(*DAG.getContext(),
  535. ValueVT.getSizeInBits()),
  536. Val);
  537. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  538. for (unsigned i = 0; i < NumParts; i += StepSize) {
  539. unsigned ThisBits = StepSize * PartBits / 2;
  540. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  541. SDValue &Part0 = Parts[i];
  542. SDValue &Part1 = Parts[i+StepSize/2];
  543. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  544. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  545. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  546. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  547. if (ThisBits == PartBits && ThisVT != PartVT) {
  548. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  549. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  550. }
  551. }
  552. }
  553. if (DAG.getDataLayout().isBigEndian())
  554. std::reverse(Parts, Parts + OrigNumParts);
  555. }
  556. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  557. SDValue Val, const SDLoc &DL, EVT PartVT) {
  558. if (!PartVT.isVector())
  559. return SDValue();
  560. EVT ValueVT = Val.getValueType();
  561. unsigned PartNumElts = PartVT.getVectorNumElements();
  562. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  563. if (PartNumElts > ValueNumElts &&
  564. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  565. EVT ElementVT = PartVT.getVectorElementType();
  566. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  567. // undef elements.
  568. SmallVector<SDValue, 16> Ops;
  569. DAG.ExtractVectorElements(Val, Ops);
  570. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  571. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  572. Ops.push_back(EltUndef);
  573. // FIXME: Use CONCAT for 2x -> 4x.
  574. return DAG.getBuildVector(PartVT, DL, Ops);
  575. }
  576. return SDValue();
  577. }
  578. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  579. /// value split into legal parts.
  580. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  581. SDValue Val, SDValue *Parts, unsigned NumParts,
  582. MVT PartVT, const Value *V,
  583. Optional<CallingConv::ID> CallConv) {
  584. EVT ValueVT = Val.getValueType();
  585. assert(ValueVT.isVector() && "Not a vector");
  586. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  587. const bool IsABIRegCopy = CallConv.hasValue();
  588. if (NumParts == 1) {
  589. EVT PartEVT = PartVT;
  590. if (PartEVT == ValueVT) {
  591. // Nothing to do.
  592. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  593. // Bitconvert vector->vector case.
  594. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  595. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  596. Val = Widened;
  597. } else if (PartVT.isVector() &&
  598. PartEVT.getVectorElementType().bitsGE(
  599. ValueVT.getVectorElementType()) &&
  600. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  601. // Promoted vector extract
  602. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  603. } else {
  604. if (ValueVT.getVectorNumElements() == 1) {
  605. Val = DAG.getNode(
  606. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  607. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  608. } else {
  609. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  610. "lossy conversion of vector to scalar type");
  611. EVT IntermediateType =
  612. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  613. Val = DAG.getBitcast(IntermediateType, Val);
  614. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  615. }
  616. }
  617. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  618. Parts[0] = Val;
  619. return;
  620. }
  621. // Handle a multi-element vector.
  622. EVT IntermediateVT;
  623. MVT RegisterVT;
  624. unsigned NumIntermediates;
  625. unsigned NumRegs;
  626. if (IsABIRegCopy) {
  627. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  628. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  629. NumIntermediates, RegisterVT);
  630. } else {
  631. NumRegs =
  632. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  633. NumIntermediates, RegisterVT);
  634. }
  635. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  636. NumParts = NumRegs; // Silence a compiler warning.
  637. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  638. unsigned IntermediateNumElts = IntermediateVT.isVector() ?
  639. IntermediateVT.getVectorNumElements() : 1;
  640. // Convert the vector to the appropiate type if necessary.
  641. unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
  642. EVT BuiltVectorTy = EVT::getVectorVT(
  643. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  644. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  645. if (ValueVT != BuiltVectorTy) {
  646. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  647. Val = Widened;
  648. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  649. }
  650. // Split the vector into intermediate operands.
  651. SmallVector<SDValue, 8> Ops(NumIntermediates);
  652. for (unsigned i = 0; i != NumIntermediates; ++i) {
  653. if (IntermediateVT.isVector()) {
  654. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  655. DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
  656. } else {
  657. Ops[i] = DAG.getNode(
  658. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  659. DAG.getConstant(i, DL, IdxVT));
  660. }
  661. }
  662. // Split the intermediate operands into legal parts.
  663. if (NumParts == NumIntermediates) {
  664. // If the register was not expanded, promote or copy the value,
  665. // as appropriate.
  666. for (unsigned i = 0; i != NumParts; ++i)
  667. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  668. } else if (NumParts > 0) {
  669. // If the intermediate type was expanded, split each the value into
  670. // legal parts.
  671. assert(NumIntermediates != 0 && "division by zero");
  672. assert(NumParts % NumIntermediates == 0 &&
  673. "Must expand into a divisible number of parts!");
  674. unsigned Factor = NumParts / NumIntermediates;
  675. for (unsigned i = 0; i != NumIntermediates; ++i)
  676. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  677. CallConv);
  678. }
  679. }
  680. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  681. EVT valuevt, Optional<CallingConv::ID> CC)
  682. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  683. RegCount(1, regs.size()), CallConv(CC) {}
  684. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  685. const DataLayout &DL, unsigned Reg, Type *Ty,
  686. Optional<CallingConv::ID> CC) {
  687. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  688. CallConv = CC;
  689. for (EVT ValueVT : ValueVTs) {
  690. unsigned NumRegs =
  691. isABIMangled()
  692. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  693. : TLI.getNumRegisters(Context, ValueVT);
  694. MVT RegisterVT =
  695. isABIMangled()
  696. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  697. : TLI.getRegisterType(Context, ValueVT);
  698. for (unsigned i = 0; i != NumRegs; ++i)
  699. Regs.push_back(Reg + i);
  700. RegVTs.push_back(RegisterVT);
  701. RegCount.push_back(NumRegs);
  702. Reg += NumRegs;
  703. }
  704. }
  705. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  706. FunctionLoweringInfo &FuncInfo,
  707. const SDLoc &dl, SDValue &Chain,
  708. SDValue *Flag, const Value *V) const {
  709. // A Value with type {} or [0 x %t] needs no registers.
  710. if (ValueVTs.empty())
  711. return SDValue();
  712. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  713. // Assemble the legal parts into the final values.
  714. SmallVector<SDValue, 4> Values(ValueVTs.size());
  715. SmallVector<SDValue, 8> Parts;
  716. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  717. // Copy the legal parts from the registers.
  718. EVT ValueVT = ValueVTs[Value];
  719. unsigned NumRegs = RegCount[Value];
  720. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  721. *DAG.getContext(),
  722. CallConv.getValue(), RegVTs[Value])
  723. : RegVTs[Value];
  724. Parts.resize(NumRegs);
  725. for (unsigned i = 0; i != NumRegs; ++i) {
  726. SDValue P;
  727. if (!Flag) {
  728. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  729. } else {
  730. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  731. *Flag = P.getValue(2);
  732. }
  733. Chain = P.getValue(1);
  734. Parts[i] = P;
  735. // If the source register was virtual and if we know something about it,
  736. // add an assert node.
  737. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  738. !RegisterVT.isInteger())
  739. continue;
  740. const FunctionLoweringInfo::LiveOutInfo *LOI =
  741. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  742. if (!LOI)
  743. continue;
  744. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  745. unsigned NumSignBits = LOI->NumSignBits;
  746. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  747. if (NumZeroBits == RegSize) {
  748. // The current value is a zero.
  749. // Explicitly express that as it would be easier for
  750. // optimizations to kick in.
  751. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  752. continue;
  753. }
  754. // FIXME: We capture more information than the dag can represent. For
  755. // now, just use the tightest assertzext/assertsext possible.
  756. bool isSExt;
  757. EVT FromVT(MVT::Other);
  758. if (NumZeroBits) {
  759. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  760. isSExt = false;
  761. } else if (NumSignBits > 1) {
  762. FromVT =
  763. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  764. isSExt = true;
  765. } else {
  766. continue;
  767. }
  768. // Add an assertion node.
  769. assert(FromVT != MVT::Other);
  770. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  771. RegisterVT, P, DAG.getValueType(FromVT));
  772. }
  773. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  774. RegisterVT, ValueVT, V, CallConv);
  775. Part += NumRegs;
  776. Parts.clear();
  777. }
  778. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  779. }
  780. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  781. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  782. const Value *V,
  783. ISD::NodeType PreferredExtendType) const {
  784. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  785. ISD::NodeType ExtendKind = PreferredExtendType;
  786. // Get the list of the values's legal parts.
  787. unsigned NumRegs = Regs.size();
  788. SmallVector<SDValue, 8> Parts(NumRegs);
  789. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  790. unsigned NumParts = RegCount[Value];
  791. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  792. *DAG.getContext(),
  793. CallConv.getValue(), RegVTs[Value])
  794. : RegVTs[Value];
  795. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  796. ExtendKind = ISD::ZERO_EXTEND;
  797. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  798. NumParts, RegisterVT, V, CallConv, ExtendKind);
  799. Part += NumParts;
  800. }
  801. // Copy the parts into the registers.
  802. SmallVector<SDValue, 8> Chains(NumRegs);
  803. for (unsigned i = 0; i != NumRegs; ++i) {
  804. SDValue Part;
  805. if (!Flag) {
  806. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  807. } else {
  808. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  809. *Flag = Part.getValue(1);
  810. }
  811. Chains[i] = Part.getValue(0);
  812. }
  813. if (NumRegs == 1 || Flag)
  814. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  815. // flagged to it. That is the CopyToReg nodes and the user are considered
  816. // a single scheduling unit. If we create a TokenFactor and return it as
  817. // chain, then the TokenFactor is both a predecessor (operand) of the
  818. // user as well as a successor (the TF operands are flagged to the user).
  819. // c1, f1 = CopyToReg
  820. // c2, f2 = CopyToReg
  821. // c3 = TokenFactor c1, c2
  822. // ...
  823. // = op c3, ..., f2
  824. Chain = Chains[NumRegs-1];
  825. else
  826. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  827. }
  828. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  829. unsigned MatchingIdx, const SDLoc &dl,
  830. SelectionDAG &DAG,
  831. std::vector<SDValue> &Ops) const {
  832. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  833. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  834. if (HasMatching)
  835. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  836. else if (!Regs.empty() &&
  837. TargetRegisterInfo::isVirtualRegister(Regs.front())) {
  838. // Put the register class of the virtual registers in the flag word. That
  839. // way, later passes can recompute register class constraints for inline
  840. // assembly as well as normal instructions.
  841. // Don't do this for tied operands that can use the regclass information
  842. // from the def.
  843. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  844. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  845. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  846. }
  847. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  848. Ops.push_back(Res);
  849. if (Code == InlineAsm::Kind_Clobber) {
  850. // Clobbers should always have a 1:1 mapping with registers, and may
  851. // reference registers that have illegal (e.g. vector) types. Hence, we
  852. // shouldn't try to apply any sort of splitting logic to them.
  853. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  854. "No 1:1 mapping from clobbers to regs?");
  855. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  856. (void)SP;
  857. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  858. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  859. assert(
  860. (Regs[I] != SP ||
  861. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  862. "If we clobbered the stack pointer, MFI should know about it.");
  863. }
  864. return;
  865. }
  866. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  867. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  868. MVT RegisterVT = RegVTs[Value];
  869. for (unsigned i = 0; i != NumRegs; ++i) {
  870. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  871. unsigned TheReg = Regs[Reg++];
  872. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  873. }
  874. }
  875. }
  876. SmallVector<std::pair<unsigned, unsigned>, 4>
  877. RegsForValue::getRegsAndSizes() const {
  878. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  879. unsigned I = 0;
  880. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  881. unsigned RegCount = std::get<0>(CountAndVT);
  882. MVT RegisterVT = std::get<1>(CountAndVT);
  883. unsigned RegisterSize = RegisterVT.getSizeInBits();
  884. for (unsigned E = I + RegCount; I != E; ++I)
  885. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  886. }
  887. return OutVec;
  888. }
  889. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  890. const TargetLibraryInfo *li) {
  891. AA = aa;
  892. GFI = gfi;
  893. LibInfo = li;
  894. DL = &DAG.getDataLayout();
  895. Context = DAG.getContext();
  896. LPadToCallSiteMap.clear();
  897. }
  898. void SelectionDAGBuilder::clear() {
  899. NodeMap.clear();
  900. UnusedArgNodeMap.clear();
  901. PendingLoads.clear();
  902. PendingExports.clear();
  903. CurInst = nullptr;
  904. HasTailCall = false;
  905. SDNodeOrder = LowestSDNodeOrder;
  906. StatepointLowering.clear();
  907. }
  908. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  909. DanglingDebugInfoMap.clear();
  910. }
  911. SDValue SelectionDAGBuilder::getRoot() {
  912. if (PendingLoads.empty())
  913. return DAG.getRoot();
  914. if (PendingLoads.size() == 1) {
  915. SDValue Root = PendingLoads[0];
  916. DAG.setRoot(Root);
  917. PendingLoads.clear();
  918. return Root;
  919. }
  920. // Otherwise, we have to make a token factor node.
  921. SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
  922. PendingLoads.clear();
  923. DAG.setRoot(Root);
  924. return Root;
  925. }
  926. SDValue SelectionDAGBuilder::getControlRoot() {
  927. SDValue Root = DAG.getRoot();
  928. if (PendingExports.empty())
  929. return Root;
  930. // Turn all of the CopyToReg chains into one factored node.
  931. if (Root.getOpcode() != ISD::EntryToken) {
  932. unsigned i = 0, e = PendingExports.size();
  933. for (; i != e; ++i) {
  934. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  935. if (PendingExports[i].getNode()->getOperand(0) == Root)
  936. break; // Don't add the root if we already indirectly depend on it.
  937. }
  938. if (i == e)
  939. PendingExports.push_back(Root);
  940. }
  941. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  942. PendingExports);
  943. PendingExports.clear();
  944. DAG.setRoot(Root);
  945. return Root;
  946. }
  947. void SelectionDAGBuilder::visit(const Instruction &I) {
  948. // Set up outgoing PHI node register values before emitting the terminator.
  949. if (I.isTerminator()) {
  950. HandlePHINodesInSuccessorBlocks(I.getParent());
  951. }
  952. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  953. if (!isa<DbgInfoIntrinsic>(I))
  954. ++SDNodeOrder;
  955. CurInst = &I;
  956. visit(I.getOpcode(), I);
  957. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  958. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  959. // maps to this instruction.
  960. // TODO: We could handle all flags (nsw, etc) here.
  961. // TODO: If an IR instruction maps to >1 node, only the final node will have
  962. // flags set.
  963. if (SDNode *Node = getNodeForIRValue(&I)) {
  964. SDNodeFlags IncomingFlags;
  965. IncomingFlags.copyFMF(*FPMO);
  966. if (!Node->getFlags().isDefined())
  967. Node->setFlags(IncomingFlags);
  968. else
  969. Node->intersectFlagsWith(IncomingFlags);
  970. }
  971. }
  972. if (!I.isTerminator() && !HasTailCall &&
  973. !isStatepoint(&I)) // statepoints handle their exports internally
  974. CopyToExportRegsIfNeeded(&I);
  975. CurInst = nullptr;
  976. }
  977. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  978. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  979. }
  980. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  981. // Note: this doesn't use InstVisitor, because it has to work with
  982. // ConstantExpr's in addition to instructions.
  983. switch (Opcode) {
  984. default: llvm_unreachable("Unknown instruction type encountered!");
  985. // Build the switch statement using the Instruction.def file.
  986. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  987. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  988. #include "llvm/IR/Instruction.def"
  989. }
  990. }
  991. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  992. const DIExpression *Expr) {
  993. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  994. const DbgValueInst *DI = DDI.getDI();
  995. DIVariable *DanglingVariable = DI->getVariable();
  996. DIExpression *DanglingExpr = DI->getExpression();
  997. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  998. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  999. return true;
  1000. }
  1001. return false;
  1002. };
  1003. for (auto &DDIMI : DanglingDebugInfoMap) {
  1004. DanglingDebugInfoVector &DDIV = DDIMI.second;
  1005. // If debug info is to be dropped, run it through final checks to see
  1006. // whether it can be salvaged.
  1007. for (auto &DDI : DDIV)
  1008. if (isMatchingDbgValue(DDI))
  1009. salvageUnresolvedDbgValue(DDI);
  1010. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  1011. }
  1012. }
  1013. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1014. // generate the debug data structures now that we've seen its definition.
  1015. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1016. SDValue Val) {
  1017. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1018. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1019. return;
  1020. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1021. for (auto &DDI : DDIV) {
  1022. const DbgValueInst *DI = DDI.getDI();
  1023. assert(DI && "Ill-formed DanglingDebugInfo");
  1024. DebugLoc dl = DDI.getdl();
  1025. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1026. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1027. DILocalVariable *Variable = DI->getVariable();
  1028. DIExpression *Expr = DI->getExpression();
  1029. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1030. "Expected inlined-at fields to agree");
  1031. SDDbgValue *SDV;
  1032. if (Val.getNode()) {
  1033. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1034. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1035. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1036. // in the first place we should not be more successful here). Unless we
  1037. // have some test case that prove this to be correct we should avoid
  1038. // calling EmitFuncArgumentDbgValue here.
  1039. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1040. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1041. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1042. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1043. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1044. // inserted after the definition of Val when emitting the instructions
  1045. // after ISel. An alternative could be to teach
  1046. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1047. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1048. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1049. << ValSDNodeOrder << "\n");
  1050. SDV = getDbgValue(Val, Variable, Expr, dl,
  1051. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1052. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1053. } else
  1054. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1055. << "in EmitFuncArgumentDbgValue\n");
  1056. } else {
  1057. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1058. auto Undef =
  1059. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1060. auto SDV =
  1061. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1062. DAG.AddDbgValue(SDV, nullptr, false);
  1063. }
  1064. }
  1065. DDIV.clear();
  1066. }
  1067. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1068. Value *V = DDI.getDI()->getValue();
  1069. DILocalVariable *Var = DDI.getDI()->getVariable();
  1070. DIExpression *Expr = DDI.getDI()->getExpression();
  1071. DebugLoc DL = DDI.getdl();
  1072. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1073. unsigned SDOrder = DDI.getSDNodeOrder();
  1074. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1075. // that DW_OP_stack_value is desired.
  1076. assert(isa<DbgValueInst>(DDI.getDI()));
  1077. bool StackValue = true;
  1078. // Can this Value can be encoded without any further work?
  1079. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1080. return;
  1081. // Attempt to salvage back through as many instructions as possible. Bail if
  1082. // a non-instruction is seen, such as a constant expression or global
  1083. // variable. FIXME: Further work could recover those too.
  1084. while (isa<Instruction>(V)) {
  1085. Instruction &VAsInst = *cast<Instruction>(V);
  1086. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1087. // If we cannot salvage any further, and haven't yet found a suitable debug
  1088. // expression, bail out.
  1089. if (!NewExpr)
  1090. break;
  1091. // New value and expr now represent this debuginfo.
  1092. V = VAsInst.getOperand(0);
  1093. Expr = NewExpr;
  1094. // Some kind of simplification occurred: check whether the operand of the
  1095. // salvaged debug expression can be encoded in this DAG.
  1096. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1097. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1098. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1099. return;
  1100. }
  1101. }
  1102. // This was the final opportunity to salvage this debug information, and it
  1103. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1104. // any earlier variable location.
  1105. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1106. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1107. DAG.AddDbgValue(SDV, nullptr, false);
  1108. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1109. << "\n");
  1110. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1111. << "\n");
  1112. }
  1113. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1114. DIExpression *Expr, DebugLoc dl,
  1115. DebugLoc InstDL, unsigned Order) {
  1116. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1117. SDDbgValue *SDV;
  1118. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1119. isa<ConstantPointerNull>(V)) {
  1120. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1121. DAG.AddDbgValue(SDV, nullptr, false);
  1122. return true;
  1123. }
  1124. // If the Value is a frame index, we can create a FrameIndex debug value
  1125. // without relying on the DAG at all.
  1126. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1127. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1128. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1129. auto SDV =
  1130. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1131. /*IsIndirect*/ false, dl, SDNodeOrder);
  1132. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1133. // is still available even if the SDNode gets optimized out.
  1134. DAG.AddDbgValue(SDV, nullptr, false);
  1135. return true;
  1136. }
  1137. }
  1138. // Do not use getValue() in here; we don't want to generate code at
  1139. // this point if it hasn't been done yet.
  1140. SDValue N = NodeMap[V];
  1141. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1142. N = UnusedArgNodeMap[V];
  1143. if (N.getNode()) {
  1144. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1145. return true;
  1146. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1147. DAG.AddDbgValue(SDV, N.getNode(), false);
  1148. return true;
  1149. }
  1150. // Special rules apply for the first dbg.values of parameter variables in a
  1151. // function. Identify them by the fact they reference Argument Values, that
  1152. // they're parameters, and they are parameters of the current function. We
  1153. // need to let them dangle until they get an SDNode.
  1154. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1155. !InstDL.getInlinedAt();
  1156. if (!IsParamOfFunc) {
  1157. // The value is not used in this block yet (or it would have an SDNode).
  1158. // We still want the value to appear for the user if possible -- if it has
  1159. // an associated VReg, we can refer to that instead.
  1160. auto VMI = FuncInfo.ValueMap.find(V);
  1161. if (VMI != FuncInfo.ValueMap.end()) {
  1162. unsigned Reg = VMI->second;
  1163. // If this is a PHI node, it may be split up into several MI PHI nodes
  1164. // (in FunctionLoweringInfo::set).
  1165. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1166. V->getType(), None);
  1167. if (RFV.occupiesMultipleRegs()) {
  1168. unsigned Offset = 0;
  1169. unsigned BitsToDescribe = 0;
  1170. if (auto VarSize = Var->getSizeInBits())
  1171. BitsToDescribe = *VarSize;
  1172. if (auto Fragment = Expr->getFragmentInfo())
  1173. BitsToDescribe = Fragment->SizeInBits;
  1174. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1175. unsigned RegisterSize = RegAndSize.second;
  1176. // Bail out if all bits are described already.
  1177. if (Offset >= BitsToDescribe)
  1178. break;
  1179. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1180. ? BitsToDescribe - Offset
  1181. : RegisterSize;
  1182. auto FragmentExpr = DIExpression::createFragmentExpression(
  1183. Expr, Offset, FragmentSize);
  1184. if (!FragmentExpr)
  1185. continue;
  1186. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1187. false, dl, SDNodeOrder);
  1188. DAG.AddDbgValue(SDV, nullptr, false);
  1189. Offset += RegisterSize;
  1190. }
  1191. } else {
  1192. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1193. DAG.AddDbgValue(SDV, nullptr, false);
  1194. }
  1195. return true;
  1196. }
  1197. }
  1198. return false;
  1199. }
  1200. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1201. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1202. for (auto &Pair : DanglingDebugInfoMap)
  1203. for (auto &DDI : Pair.second)
  1204. salvageUnresolvedDbgValue(DDI);
  1205. clearDanglingDebugInfo();
  1206. }
  1207. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1208. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1209. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1210. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1211. SDValue Result;
  1212. if (It != FuncInfo.ValueMap.end()) {
  1213. unsigned InReg = It->second;
  1214. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1215. DAG.getDataLayout(), InReg, Ty,
  1216. None); // This is not an ABI copy.
  1217. SDValue Chain = DAG.getEntryNode();
  1218. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1219. V);
  1220. resolveDanglingDebugInfo(V, Result);
  1221. }
  1222. return Result;
  1223. }
  1224. /// getValue - Return an SDValue for the given Value.
  1225. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1226. // If we already have an SDValue for this value, use it. It's important
  1227. // to do this first, so that we don't create a CopyFromReg if we already
  1228. // have a regular SDValue.
  1229. SDValue &N = NodeMap[V];
  1230. if (N.getNode()) return N;
  1231. // If there's a virtual register allocated and initialized for this
  1232. // value, use it.
  1233. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1234. return copyFromReg;
  1235. // Otherwise create a new SDValue and remember it.
  1236. SDValue Val = getValueImpl(V);
  1237. NodeMap[V] = Val;
  1238. resolveDanglingDebugInfo(V, Val);
  1239. return Val;
  1240. }
  1241. // Return true if SDValue exists for the given Value
  1242. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1243. return (NodeMap.find(V) != NodeMap.end()) ||
  1244. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1245. }
  1246. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1247. /// don't look in FuncInfo.ValueMap for a virtual register.
  1248. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1249. // If we already have an SDValue for this value, use it.
  1250. SDValue &N = NodeMap[V];
  1251. if (N.getNode()) {
  1252. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1253. // Remove the debug location from the node as the node is about to be used
  1254. // in a location which may differ from the original debug location. This
  1255. // is relevant to Constant and ConstantFP nodes because they can appear
  1256. // as constant expressions inside PHI nodes.
  1257. N->setDebugLoc(DebugLoc());
  1258. }
  1259. return N;
  1260. }
  1261. // Otherwise create a new SDValue and remember it.
  1262. SDValue Val = getValueImpl(V);
  1263. NodeMap[V] = Val;
  1264. resolveDanglingDebugInfo(V, Val);
  1265. return Val;
  1266. }
  1267. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1268. /// Create an SDValue for the given value.
  1269. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1270. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1271. if (const Constant *C = dyn_cast<Constant>(V)) {
  1272. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1273. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1274. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1275. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1276. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1277. if (isa<ConstantPointerNull>(C)) {
  1278. unsigned AS = V->getType()->getPointerAddressSpace();
  1279. return DAG.getConstant(0, getCurSDLoc(),
  1280. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1281. }
  1282. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1283. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1284. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1285. return DAG.getUNDEF(VT);
  1286. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1287. visit(CE->getOpcode(), *CE);
  1288. SDValue N1 = NodeMap[V];
  1289. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1290. return N1;
  1291. }
  1292. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1293. SmallVector<SDValue, 4> Constants;
  1294. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1295. OI != OE; ++OI) {
  1296. SDNode *Val = getValue(*OI).getNode();
  1297. // If the operand is an empty aggregate, there are no values.
  1298. if (!Val) continue;
  1299. // Add each leaf value from the operand to the Constants list
  1300. // to form a flattened list of all the values.
  1301. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1302. Constants.push_back(SDValue(Val, i));
  1303. }
  1304. return DAG.getMergeValues(Constants, getCurSDLoc());
  1305. }
  1306. if (const ConstantDataSequential *CDS =
  1307. dyn_cast<ConstantDataSequential>(C)) {
  1308. SmallVector<SDValue, 4> Ops;
  1309. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1310. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1311. // Add each leaf value from the operand to the Constants list
  1312. // to form a flattened list of all the values.
  1313. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1314. Ops.push_back(SDValue(Val, i));
  1315. }
  1316. if (isa<ArrayType>(CDS->getType()))
  1317. return DAG.getMergeValues(Ops, getCurSDLoc());
  1318. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1319. }
  1320. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1321. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1322. "Unknown struct or array constant!");
  1323. SmallVector<EVT, 4> ValueVTs;
  1324. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1325. unsigned NumElts = ValueVTs.size();
  1326. if (NumElts == 0)
  1327. return SDValue(); // empty struct
  1328. SmallVector<SDValue, 4> Constants(NumElts);
  1329. for (unsigned i = 0; i != NumElts; ++i) {
  1330. EVT EltVT = ValueVTs[i];
  1331. if (isa<UndefValue>(C))
  1332. Constants[i] = DAG.getUNDEF(EltVT);
  1333. else if (EltVT.isFloatingPoint())
  1334. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1335. else
  1336. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1337. }
  1338. return DAG.getMergeValues(Constants, getCurSDLoc());
  1339. }
  1340. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1341. return DAG.getBlockAddress(BA, VT);
  1342. VectorType *VecTy = cast<VectorType>(V->getType());
  1343. unsigned NumElements = VecTy->getNumElements();
  1344. // Now that we know the number and type of the elements, get that number of
  1345. // elements into the Ops array based on what kind of constant it is.
  1346. SmallVector<SDValue, 16> Ops;
  1347. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1348. for (unsigned i = 0; i != NumElements; ++i)
  1349. Ops.push_back(getValue(CV->getOperand(i)));
  1350. } else {
  1351. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1352. EVT EltVT =
  1353. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1354. SDValue Op;
  1355. if (EltVT.isFloatingPoint())
  1356. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1357. else
  1358. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1359. Ops.assign(NumElements, Op);
  1360. }
  1361. // Create a BUILD_VECTOR node.
  1362. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1363. }
  1364. // If this is a static alloca, generate it as the frameindex instead of
  1365. // computation.
  1366. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1367. DenseMap<const AllocaInst*, int>::iterator SI =
  1368. FuncInfo.StaticAllocaMap.find(AI);
  1369. if (SI != FuncInfo.StaticAllocaMap.end())
  1370. return DAG.getFrameIndex(SI->second,
  1371. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1372. }
  1373. // If this is an instruction which fast-isel has deferred, select it now.
  1374. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1375. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1376. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1377. Inst->getType(), getABIRegCopyCC(V));
  1378. SDValue Chain = DAG.getEntryNode();
  1379. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1380. }
  1381. llvm_unreachable("Can't get register for value!");
  1382. }
  1383. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1384. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1385. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1386. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1387. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1388. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1389. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1390. if (!IsSEH)
  1391. CatchPadMBB->setIsEHScopeEntry();
  1392. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1393. if (IsMSVCCXX || IsCoreCLR)
  1394. CatchPadMBB->setIsEHFuncletEntry();
  1395. // Wasm does not need catchpads anymore
  1396. if (!IsWasmCXX)
  1397. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1398. getControlRoot()));
  1399. }
  1400. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1401. // Update machine-CFG edge.
  1402. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1403. FuncInfo.MBB->addSuccessor(TargetMBB);
  1404. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1405. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1406. if (IsSEH) {
  1407. // If this is not a fall-through branch or optimizations are switched off,
  1408. // emit the branch.
  1409. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1410. TM.getOptLevel() == CodeGenOpt::None)
  1411. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1412. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1413. return;
  1414. }
  1415. // Figure out the funclet membership for the catchret's successor.
  1416. // This will be used by the FuncletLayout pass to determine how to order the
  1417. // BB's.
  1418. // A 'catchret' returns to the outer scope's color.
  1419. Value *ParentPad = I.getCatchSwitchParentPad();
  1420. const BasicBlock *SuccessorColor;
  1421. if (isa<ConstantTokenNone>(ParentPad))
  1422. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1423. else
  1424. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1425. assert(SuccessorColor && "No parent funclet for catchret!");
  1426. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1427. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1428. // Create the terminator node.
  1429. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1430. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1431. DAG.getBasicBlock(SuccessorColorMBB));
  1432. DAG.setRoot(Ret);
  1433. }
  1434. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1435. // Don't emit any special code for the cleanuppad instruction. It just marks
  1436. // the start of an EH scope/funclet.
  1437. FuncInfo.MBB->setIsEHScopeEntry();
  1438. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1439. if (Pers != EHPersonality::Wasm_CXX) {
  1440. FuncInfo.MBB->setIsEHFuncletEntry();
  1441. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1442. }
  1443. }
  1444. // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
  1445. // the control flow always stops at the single catch pad, as it does for a
  1446. // cleanup pad. In case the exception caught is not of the types the catch pad
  1447. // catches, it will be rethrown by a rethrow.
  1448. static void findWasmUnwindDestinations(
  1449. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1450. BranchProbability Prob,
  1451. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1452. &UnwindDests) {
  1453. while (EHPadBB) {
  1454. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1455. if (isa<CleanupPadInst>(Pad)) {
  1456. // Stop on cleanup pads.
  1457. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1458. UnwindDests.back().first->setIsEHScopeEntry();
  1459. break;
  1460. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1461. // Add the catchpad handlers to the possible destinations. We don't
  1462. // continue to the unwind destination of the catchswitch for wasm.
  1463. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1464. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1465. UnwindDests.back().first->setIsEHScopeEntry();
  1466. }
  1467. break;
  1468. } else {
  1469. continue;
  1470. }
  1471. }
  1472. }
  1473. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1474. /// many places it could ultimately go. In the IR, we have a single unwind
  1475. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1476. /// This function skips over imaginary basic blocks that hold catchswitch
  1477. /// instructions, and finds all the "real" machine
  1478. /// basic block destinations. As those destinations may not be successors of
  1479. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1480. /// The passed-in Prob is the edge probability to EHPadBB.
  1481. static void findUnwindDestinations(
  1482. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1483. BranchProbability Prob,
  1484. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1485. &UnwindDests) {
  1486. EHPersonality Personality =
  1487. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1488. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1489. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1490. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1491. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1492. if (IsWasmCXX) {
  1493. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1494. assert(UnwindDests.size() <= 1 &&
  1495. "There should be at most one unwind destination for wasm");
  1496. return;
  1497. }
  1498. while (EHPadBB) {
  1499. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1500. BasicBlock *NewEHPadBB = nullptr;
  1501. if (isa<LandingPadInst>(Pad)) {
  1502. // Stop on landingpads. They are not funclets.
  1503. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1504. break;
  1505. } else if (isa<CleanupPadInst>(Pad)) {
  1506. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1507. // personalities.
  1508. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1509. UnwindDests.back().first->setIsEHScopeEntry();
  1510. UnwindDests.back().first->setIsEHFuncletEntry();
  1511. break;
  1512. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1513. // Add the catchpad handlers to the possible destinations.
  1514. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1515. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1516. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1517. if (IsMSVCCXX || IsCoreCLR)
  1518. UnwindDests.back().first->setIsEHFuncletEntry();
  1519. if (!IsSEH)
  1520. UnwindDests.back().first->setIsEHScopeEntry();
  1521. }
  1522. NewEHPadBB = CatchSwitch->getUnwindDest();
  1523. } else {
  1524. continue;
  1525. }
  1526. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1527. if (BPI && NewEHPadBB)
  1528. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1529. EHPadBB = NewEHPadBB;
  1530. }
  1531. }
  1532. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1533. // Update successor info.
  1534. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1535. auto UnwindDest = I.getUnwindDest();
  1536. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1537. BranchProbability UnwindDestProb =
  1538. (BPI && UnwindDest)
  1539. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1540. : BranchProbability::getZero();
  1541. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1542. for (auto &UnwindDest : UnwindDests) {
  1543. UnwindDest.first->setIsEHPad();
  1544. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1545. }
  1546. FuncInfo.MBB->normalizeSuccProbs();
  1547. // Create the terminator node.
  1548. SDValue Ret =
  1549. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1550. DAG.setRoot(Ret);
  1551. }
  1552. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1553. report_fatal_error("visitCatchSwitch not yet implemented!");
  1554. }
  1555. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1556. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1557. auto &DL = DAG.getDataLayout();
  1558. SDValue Chain = getControlRoot();
  1559. SmallVector<ISD::OutputArg, 8> Outs;
  1560. SmallVector<SDValue, 8> OutVals;
  1561. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1562. // lower
  1563. //
  1564. // %val = call <ty> @llvm.experimental.deoptimize()
  1565. // ret <ty> %val
  1566. //
  1567. // differently.
  1568. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1569. LowerDeoptimizingReturn();
  1570. return;
  1571. }
  1572. if (!FuncInfo.CanLowerReturn) {
  1573. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1574. const Function *F = I.getParent()->getParent();
  1575. // Emit a store of the return value through the virtual register.
  1576. // Leave Outs empty so that LowerReturn won't try to load return
  1577. // registers the usual way.
  1578. SmallVector<EVT, 1> PtrValueVTs;
  1579. ComputeValueVTs(TLI, DL,
  1580. F->getReturnType()->getPointerTo(
  1581. DAG.getDataLayout().getAllocaAddrSpace()),
  1582. PtrValueVTs);
  1583. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1584. DemoteReg, PtrValueVTs[0]);
  1585. SDValue RetOp = getValue(I.getOperand(0));
  1586. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1587. SmallVector<uint64_t, 4> Offsets;
  1588. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1589. &Offsets);
  1590. unsigned NumValues = ValueVTs.size();
  1591. SmallVector<SDValue, 4> Chains(NumValues);
  1592. for (unsigned i = 0; i != NumValues; ++i) {
  1593. // An aggregate return value cannot wrap around the address space, so
  1594. // offsets to its parts don't wrap either.
  1595. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1596. SDValue Val = RetOp.getValue(i);
  1597. if (MemVTs[i] != ValueVTs[i])
  1598. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1599. Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
  1600. // FIXME: better loc info would be nice.
  1601. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1602. }
  1603. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1604. MVT::Other, Chains);
  1605. } else if (I.getNumOperands() != 0) {
  1606. SmallVector<EVT, 4> ValueVTs;
  1607. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1608. unsigned NumValues = ValueVTs.size();
  1609. if (NumValues) {
  1610. SDValue RetOp = getValue(I.getOperand(0));
  1611. const Function *F = I.getParent()->getParent();
  1612. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1613. I.getOperand(0)->getType(), F->getCallingConv(),
  1614. /*IsVarArg*/ false);
  1615. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1616. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1617. Attribute::SExt))
  1618. ExtendKind = ISD::SIGN_EXTEND;
  1619. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1620. Attribute::ZExt))
  1621. ExtendKind = ISD::ZERO_EXTEND;
  1622. LLVMContext &Context = F->getContext();
  1623. bool RetInReg = F->getAttributes().hasAttribute(
  1624. AttributeList::ReturnIndex, Attribute::InReg);
  1625. for (unsigned j = 0; j != NumValues; ++j) {
  1626. EVT VT = ValueVTs[j];
  1627. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1628. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1629. CallingConv::ID CC = F->getCallingConv();
  1630. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1631. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1632. SmallVector<SDValue, 4> Parts(NumParts);
  1633. getCopyToParts(DAG, getCurSDLoc(),
  1634. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1635. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1636. // 'inreg' on function refers to return value
  1637. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1638. if (RetInReg)
  1639. Flags.setInReg();
  1640. if (I.getOperand(0)->getType()->isPointerTy()) {
  1641. Flags.setPointer();
  1642. Flags.setPointerAddrSpace(
  1643. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1644. }
  1645. if (NeedsRegBlock) {
  1646. Flags.setInConsecutiveRegs();
  1647. if (j == NumValues - 1)
  1648. Flags.setInConsecutiveRegsLast();
  1649. }
  1650. // Propagate extension type if any
  1651. if (ExtendKind == ISD::SIGN_EXTEND)
  1652. Flags.setSExt();
  1653. else if (ExtendKind == ISD::ZERO_EXTEND)
  1654. Flags.setZExt();
  1655. for (unsigned i = 0; i < NumParts; ++i) {
  1656. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1657. VT, /*isfixed=*/true, 0, 0));
  1658. OutVals.push_back(Parts[i]);
  1659. }
  1660. }
  1661. }
  1662. }
  1663. // Push in swifterror virtual register as the last element of Outs. This makes
  1664. // sure swifterror virtual register will be returned in the swifterror
  1665. // physical register.
  1666. const Function *F = I.getParent()->getParent();
  1667. if (TLI.supportSwiftError() &&
  1668. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1669. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1670. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1671. Flags.setSwiftError();
  1672. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1673. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1674. true /*isfixed*/, 1 /*origidx*/,
  1675. 0 /*partOffs*/));
  1676. // Create SDNode for the swifterror virtual register.
  1677. OutVals.push_back(
  1678. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1679. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1680. EVT(TLI.getPointerTy(DL))));
  1681. }
  1682. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1683. CallingConv::ID CallConv =
  1684. DAG.getMachineFunction().getFunction().getCallingConv();
  1685. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1686. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1687. // Verify that the target's LowerReturn behaved as expected.
  1688. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1689. "LowerReturn didn't return a valid chain!");
  1690. // Update the DAG with the new chain value resulting from return lowering.
  1691. DAG.setRoot(Chain);
  1692. }
  1693. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1694. /// created for it, emit nodes to copy the value into the virtual
  1695. /// registers.
  1696. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1697. // Skip empty types
  1698. if (V->getType()->isEmptyTy())
  1699. return;
  1700. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1701. if (VMI != FuncInfo.ValueMap.end()) {
  1702. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1703. CopyValueToVirtualRegister(V, VMI->second);
  1704. }
  1705. }
  1706. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1707. /// the current basic block, add it to ValueMap now so that we'll get a
  1708. /// CopyTo/FromReg.
  1709. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1710. // No need to export constants.
  1711. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1712. // Already exported?
  1713. if (FuncInfo.isExportedInst(V)) return;
  1714. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1715. CopyValueToVirtualRegister(V, Reg);
  1716. }
  1717. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1718. const BasicBlock *FromBB) {
  1719. // The operands of the setcc have to be in this block. We don't know
  1720. // how to export them from some other block.
  1721. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1722. // Can export from current BB.
  1723. if (VI->getParent() == FromBB)
  1724. return true;
  1725. // Is already exported, noop.
  1726. return FuncInfo.isExportedInst(V);
  1727. }
  1728. // If this is an argument, we can export it if the BB is the entry block or
  1729. // if it is already exported.
  1730. if (isa<Argument>(V)) {
  1731. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1732. return true;
  1733. // Otherwise, can only export this if it is already exported.
  1734. return FuncInfo.isExportedInst(V);
  1735. }
  1736. // Otherwise, constants can always be exported.
  1737. return true;
  1738. }
  1739. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1740. BranchProbability
  1741. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1742. const MachineBasicBlock *Dst) const {
  1743. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1744. const BasicBlock *SrcBB = Src->getBasicBlock();
  1745. const BasicBlock *DstBB = Dst->getBasicBlock();
  1746. if (!BPI) {
  1747. // If BPI is not available, set the default probability as 1 / N, where N is
  1748. // the number of successors.
  1749. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1750. return BranchProbability(1, SuccSize);
  1751. }
  1752. return BPI->getEdgeProbability(SrcBB, DstBB);
  1753. }
  1754. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1755. MachineBasicBlock *Dst,
  1756. BranchProbability Prob) {
  1757. if (!FuncInfo.BPI)
  1758. Src->addSuccessorWithoutProb(Dst);
  1759. else {
  1760. if (Prob.isUnknown())
  1761. Prob = getEdgeProbability(Src, Dst);
  1762. Src->addSuccessor(Dst, Prob);
  1763. }
  1764. }
  1765. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1766. if (const Instruction *I = dyn_cast<Instruction>(V))
  1767. return I->getParent() == BB;
  1768. return true;
  1769. }
  1770. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1771. /// This function emits a branch and is used at the leaves of an OR or an
  1772. /// AND operator tree.
  1773. void
  1774. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1775. MachineBasicBlock *TBB,
  1776. MachineBasicBlock *FBB,
  1777. MachineBasicBlock *CurBB,
  1778. MachineBasicBlock *SwitchBB,
  1779. BranchProbability TProb,
  1780. BranchProbability FProb,
  1781. bool InvertCond) {
  1782. const BasicBlock *BB = CurBB->getBasicBlock();
  1783. // If the leaf of the tree is a comparison, merge the condition into
  1784. // the caseblock.
  1785. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1786. // The operands of the cmp have to be in this block. We don't know
  1787. // how to export them from some other block. If this is the first block
  1788. // of the sequence, no exporting is needed.
  1789. if (CurBB == SwitchBB ||
  1790. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1791. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1792. ISD::CondCode Condition;
  1793. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1794. ICmpInst::Predicate Pred =
  1795. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1796. Condition = getICmpCondCode(Pred);
  1797. } else {
  1798. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1799. FCmpInst::Predicate Pred =
  1800. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1801. Condition = getFCmpCondCode(Pred);
  1802. if (TM.Options.NoNaNsFPMath)
  1803. Condition = getFCmpCodeWithoutNaN(Condition);
  1804. }
  1805. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1806. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1807. SwitchCases.push_back(CB);
  1808. return;
  1809. }
  1810. }
  1811. // Create a CaseBlock record representing this branch.
  1812. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1813. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1814. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1815. SwitchCases.push_back(CB);
  1816. }
  1817. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1818. MachineBasicBlock *TBB,
  1819. MachineBasicBlock *FBB,
  1820. MachineBasicBlock *CurBB,
  1821. MachineBasicBlock *SwitchBB,
  1822. Instruction::BinaryOps Opc,
  1823. BranchProbability TProb,
  1824. BranchProbability FProb,
  1825. bool InvertCond) {
  1826. // Skip over not part of the tree and remember to invert op and operands at
  1827. // next level.
  1828. Value *NotCond;
  1829. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1830. InBlock(NotCond, CurBB->getBasicBlock())) {
  1831. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1832. !InvertCond);
  1833. return;
  1834. }
  1835. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1836. // Compute the effective opcode for Cond, taking into account whether it needs
  1837. // to be inverted, e.g.
  1838. // and (not (or A, B)), C
  1839. // gets lowered as
  1840. // and (and (not A, not B), C)
  1841. unsigned BOpc = 0;
  1842. if (BOp) {
  1843. BOpc = BOp->getOpcode();
  1844. if (InvertCond) {
  1845. if (BOpc == Instruction::And)
  1846. BOpc = Instruction::Or;
  1847. else if (BOpc == Instruction::Or)
  1848. BOpc = Instruction::And;
  1849. }
  1850. }
  1851. // If this node is not part of the or/and tree, emit it as a branch.
  1852. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1853. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1854. BOp->getParent() != CurBB->getBasicBlock() ||
  1855. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1856. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1857. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1858. TProb, FProb, InvertCond);
  1859. return;
  1860. }
  1861. // Create TmpBB after CurBB.
  1862. MachineFunction::iterator BBI(CurBB);
  1863. MachineFunction &MF = DAG.getMachineFunction();
  1864. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1865. CurBB->getParent()->insert(++BBI, TmpBB);
  1866. if (Opc == Instruction::Or) {
  1867. // Codegen X | Y as:
  1868. // BB1:
  1869. // jmp_if_X TBB
  1870. // jmp TmpBB
  1871. // TmpBB:
  1872. // jmp_if_Y TBB
  1873. // jmp FBB
  1874. //
  1875. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1876. // The requirement is that
  1877. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1878. // = TrueProb for original BB.
  1879. // Assuming the original probabilities are A and B, one choice is to set
  1880. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1881. // A/(1+B) and 2B/(1+B). This choice assumes that
  1882. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1883. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1884. // TmpBB, but the math is more complicated.
  1885. auto NewTrueProb = TProb / 2;
  1886. auto NewFalseProb = TProb / 2 + FProb;
  1887. // Emit the LHS condition.
  1888. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1889. NewTrueProb, NewFalseProb, InvertCond);
  1890. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1891. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1892. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1893. // Emit the RHS condition into TmpBB.
  1894. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1895. Probs[0], Probs[1], InvertCond);
  1896. } else {
  1897. assert(Opc == Instruction::And && "Unknown merge op!");
  1898. // Codegen X & Y as:
  1899. // BB1:
  1900. // jmp_if_X TmpBB
  1901. // jmp FBB
  1902. // TmpBB:
  1903. // jmp_if_Y TBB
  1904. // jmp FBB
  1905. //
  1906. // This requires creation of TmpBB after CurBB.
  1907. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1908. // The requirement is that
  1909. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1910. // = FalseProb for original BB.
  1911. // Assuming the original probabilities are A and B, one choice is to set
  1912. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1913. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1914. // TrueProb for BB1 * FalseProb for TmpBB.
  1915. auto NewTrueProb = TProb + FProb / 2;
  1916. auto NewFalseProb = FProb / 2;
  1917. // Emit the LHS condition.
  1918. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1919. NewTrueProb, NewFalseProb, InvertCond);
  1920. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1921. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1922. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1923. // Emit the RHS condition into TmpBB.
  1924. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1925. Probs[0], Probs[1], InvertCond);
  1926. }
  1927. }
  1928. /// If the set of cases should be emitted as a series of branches, return true.
  1929. /// If we should emit this as a bunch of and/or'd together conditions, return
  1930. /// false.
  1931. bool
  1932. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1933. if (Cases.size() != 2) return true;
  1934. // If this is two comparisons of the same values or'd or and'd together, they
  1935. // will get folded into a single comparison, so don't emit two blocks.
  1936. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1937. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1938. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1939. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1940. return false;
  1941. }
  1942. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1943. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1944. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1945. Cases[0].CC == Cases[1].CC &&
  1946. isa<Constant>(Cases[0].CmpRHS) &&
  1947. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1948. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1949. return false;
  1950. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1951. return false;
  1952. }
  1953. return true;
  1954. }
  1955. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1956. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1957. // Update machine-CFG edges.
  1958. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1959. if (I.isUnconditional()) {
  1960. // Update machine-CFG edges.
  1961. BrMBB->addSuccessor(Succ0MBB);
  1962. // If this is not a fall-through branch or optimizations are switched off,
  1963. // emit the branch.
  1964. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1965. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1966. MVT::Other, getControlRoot(),
  1967. DAG.getBasicBlock(Succ0MBB)));
  1968. return;
  1969. }
  1970. // If this condition is one of the special cases we handle, do special stuff
  1971. // now.
  1972. const Value *CondVal = I.getCondition();
  1973. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1974. // If this is a series of conditions that are or'd or and'd together, emit
  1975. // this as a sequence of branches instead of setcc's with and/or operations.
  1976. // As long as jumps are not expensive, this should improve performance.
  1977. // For example, instead of something like:
  1978. // cmp A, B
  1979. // C = seteq
  1980. // cmp D, E
  1981. // F = setle
  1982. // or C, F
  1983. // jnz foo
  1984. // Emit:
  1985. // cmp A, B
  1986. // je foo
  1987. // cmp D, E
  1988. // jle foo
  1989. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1990. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1991. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1992. !I.getMetadata(LLVMContext::MD_unpredictable) &&
  1993. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1994. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1995. Opcode,
  1996. getEdgeProbability(BrMBB, Succ0MBB),
  1997. getEdgeProbability(BrMBB, Succ1MBB),
  1998. /*InvertCond=*/false);
  1999. // If the compares in later blocks need to use values not currently
  2000. // exported from this block, export them now. This block should always
  2001. // be the first entry.
  2002. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2003. // Allow some cases to be rejected.
  2004. if (ShouldEmitAsBranches(SwitchCases)) {
  2005. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  2006. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  2007. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  2008. }
  2009. // Emit the branch for this block.
  2010. visitSwitchCase(SwitchCases[0], BrMBB);
  2011. SwitchCases.erase(SwitchCases.begin());
  2012. return;
  2013. }
  2014. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2015. // SwitchCases.
  2016. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  2017. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  2018. SwitchCases.clear();
  2019. }
  2020. }
  2021. // Create a CaseBlock record representing this branch.
  2022. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2023. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2024. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2025. // cond branch.
  2026. visitSwitchCase(CB, BrMBB);
  2027. }
  2028. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2029. /// the binary search tree resulting from lowering a switch instruction.
  2030. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2031. MachineBasicBlock *SwitchBB) {
  2032. SDValue Cond;
  2033. SDValue CondLHS = getValue(CB.CmpLHS);
  2034. SDLoc dl = CB.DL;
  2035. if (CB.CC == ISD::SETTRUE) {
  2036. // Branch or fall through to TrueBB.
  2037. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2038. SwitchBB->normalizeSuccProbs();
  2039. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2040. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2041. DAG.getBasicBlock(CB.TrueBB)));
  2042. }
  2043. return;
  2044. }
  2045. auto &TLI = DAG.getTargetLoweringInfo();
  2046. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2047. // Build the setcc now.
  2048. if (!CB.CmpMHS) {
  2049. // Fold "(X == true)" to X and "(X == false)" to !X to
  2050. // handle common cases produced by branch lowering.
  2051. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2052. CB.CC == ISD::SETEQ)
  2053. Cond = CondLHS;
  2054. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2055. CB.CC == ISD::SETEQ) {
  2056. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2057. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2058. } else {
  2059. SDValue CondRHS = getValue(CB.CmpRHS);
  2060. // If a pointer's DAG type is larger than its memory type then the DAG
  2061. // values are zero-extended. This breaks signed comparisons so truncate
  2062. // back to the underlying type before doing the compare.
  2063. if (CondLHS.getValueType() != MemVT) {
  2064. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2065. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2066. }
  2067. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2068. }
  2069. } else {
  2070. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2071. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2072. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2073. SDValue CmpOp = getValue(CB.CmpMHS);
  2074. EVT VT = CmpOp.getValueType();
  2075. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2076. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2077. ISD::SETLE);
  2078. } else {
  2079. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2080. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2081. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2082. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2083. }
  2084. }
  2085. // Update successor info
  2086. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2087. // TrueBB and FalseBB are always different unless the incoming IR is
  2088. // degenerate. This only happens when running llc on weird IR.
  2089. if (CB.TrueBB != CB.FalseBB)
  2090. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2091. SwitchBB->normalizeSuccProbs();
  2092. // If the lhs block is the next block, invert the condition so that we can
  2093. // fall through to the lhs instead of the rhs block.
  2094. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2095. std::swap(CB.TrueBB, CB.FalseBB);
  2096. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2097. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2098. }
  2099. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2100. MVT::Other, getControlRoot(), Cond,
  2101. DAG.getBasicBlock(CB.TrueBB));
  2102. // Insert the false branch. Do this even if it's a fall through branch,
  2103. // this makes it easier to do DAG optimizations which require inverting
  2104. // the branch condition.
  2105. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2106. DAG.getBasicBlock(CB.FalseBB));
  2107. DAG.setRoot(BrCond);
  2108. }
  2109. /// visitJumpTable - Emit JumpTable node in the current MBB
  2110. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  2111. // Emit the code for the jump table
  2112. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2113. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2114. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2115. JT.Reg, PTy);
  2116. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2117. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2118. MVT::Other, Index.getValue(1),
  2119. Table, Index);
  2120. DAG.setRoot(BrJumpTable);
  2121. }
  2122. /// visitJumpTableHeader - This function emits necessary code to produce index
  2123. /// in the JumpTable from switch case.
  2124. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  2125. JumpTableHeader &JTH,
  2126. MachineBasicBlock *SwitchBB) {
  2127. SDLoc dl = getCurSDLoc();
  2128. // Subtract the lowest switch case value from the value being switched on.
  2129. SDValue SwitchOp = getValue(JTH.SValue);
  2130. EVT VT = SwitchOp.getValueType();
  2131. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2132. DAG.getConstant(JTH.First, dl, VT));
  2133. // The SDNode we just created, which holds the value being switched on minus
  2134. // the smallest case value, needs to be copied to a virtual register so it
  2135. // can be used as an index into the jump table in a subsequent basic block.
  2136. // This value may be smaller or larger than the target's pointer type, and
  2137. // therefore require extension or truncating.
  2138. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2139. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2140. unsigned JumpTableReg =
  2141. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2142. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2143. JumpTableReg, SwitchOp);
  2144. JT.Reg = JumpTableReg;
  2145. if (!JTH.OmitRangeCheck) {
  2146. // Emit the range check for the jump table, and branch to the default block
  2147. // for the switch statement if the value being switched on exceeds the
  2148. // largest case in the switch.
  2149. SDValue CMP = DAG.getSetCC(
  2150. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2151. Sub.getValueType()),
  2152. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2153. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2154. MVT::Other, CopyTo, CMP,
  2155. DAG.getBasicBlock(JT.Default));
  2156. // Avoid emitting unnecessary branches to the next block.
  2157. if (JT.MBB != NextBlock(SwitchBB))
  2158. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2159. DAG.getBasicBlock(JT.MBB));
  2160. DAG.setRoot(BrCond);
  2161. } else {
  2162. // Avoid emitting unnecessary branches to the next block.
  2163. if (JT.MBB != NextBlock(SwitchBB))
  2164. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2165. DAG.getBasicBlock(JT.MBB)));
  2166. else
  2167. DAG.setRoot(CopyTo);
  2168. }
  2169. }
  2170. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2171. /// variable if there exists one.
  2172. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2173. SDValue &Chain) {
  2174. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2175. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2176. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2177. MachineFunction &MF = DAG.getMachineFunction();
  2178. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2179. MachineSDNode *Node =
  2180. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2181. if (Global) {
  2182. MachinePointerInfo MPInfo(Global);
  2183. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2184. MachineMemOperand::MODereferenceable;
  2185. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2186. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  2187. DAG.setNodeMemRefs(Node, {MemRef});
  2188. }
  2189. if (PtrTy != PtrMemTy)
  2190. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2191. return SDValue(Node, 0);
  2192. }
  2193. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2194. /// tail spliced into a stack protector check success bb.
  2195. ///
  2196. /// For a high level explanation of how this fits into the stack protector
  2197. /// generation see the comment on the declaration of class
  2198. /// StackProtectorDescriptor.
  2199. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2200. MachineBasicBlock *ParentBB) {
  2201. // First create the loads to the guard/stack slot for the comparison.
  2202. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2203. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2204. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2205. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2206. int FI = MFI.getStackProtectorIndex();
  2207. SDValue Guard;
  2208. SDLoc dl = getCurSDLoc();
  2209. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2210. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2211. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  2212. // Generate code to load the content of the guard slot.
  2213. SDValue GuardVal = DAG.getLoad(
  2214. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2215. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2216. MachineMemOperand::MOVolatile);
  2217. if (TLI.useStackGuardXorFP())
  2218. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2219. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2220. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2221. // The target provides a guard check function to validate the guard value.
  2222. // Generate a call to that function with the content of the guard slot as
  2223. // argument.
  2224. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2225. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2226. TargetLowering::ArgListTy Args;
  2227. TargetLowering::ArgListEntry Entry;
  2228. Entry.Node = GuardVal;
  2229. Entry.Ty = FnTy->getParamType(0);
  2230. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2231. Entry.IsInReg = true;
  2232. Args.push_back(Entry);
  2233. TargetLowering::CallLoweringInfo CLI(DAG);
  2234. CLI.setDebugLoc(getCurSDLoc())
  2235. .setChain(DAG.getEntryNode())
  2236. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2237. getValue(GuardCheckFn), std::move(Args));
  2238. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2239. DAG.setRoot(Result.second);
  2240. return;
  2241. }
  2242. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2243. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2244. SDValue Chain = DAG.getEntryNode();
  2245. if (TLI.useLoadStackGuardNode()) {
  2246. Guard = getLoadStackGuard(DAG, dl, Chain);
  2247. } else {
  2248. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2249. SDValue GuardPtr = getValue(IRGuard);
  2250. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2251. MachinePointerInfo(IRGuard, 0), Align,
  2252. MachineMemOperand::MOVolatile);
  2253. }
  2254. // Perform the comparison via a subtract/getsetcc.
  2255. EVT VT = Guard.getValueType();
  2256. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2257. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2258. *DAG.getContext(),
  2259. Sub.getValueType()),
  2260. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2261. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2262. // branch to failure MBB.
  2263. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2264. MVT::Other, GuardVal.getOperand(0),
  2265. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2266. // Otherwise branch to success MBB.
  2267. SDValue Br = DAG.getNode(ISD::BR, dl,
  2268. MVT::Other, BrCond,
  2269. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2270. DAG.setRoot(Br);
  2271. }
  2272. /// Codegen the failure basic block for a stack protector check.
  2273. ///
  2274. /// A failure stack protector machine basic block consists simply of a call to
  2275. /// __stack_chk_fail().
  2276. ///
  2277. /// For a high level explanation of how this fits into the stack protector
  2278. /// generation see the comment on the declaration of class
  2279. /// StackProtectorDescriptor.
  2280. void
  2281. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2282. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2283. SDValue Chain =
  2284. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2285. None, false, getCurSDLoc(), false, false).second;
  2286. // On PS4, the "return address" must still be within the calling function,
  2287. // even if it's at the very end, so emit an explicit TRAP here.
  2288. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2289. if (TM.getTargetTriple().isPS4CPU())
  2290. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2291. DAG.setRoot(Chain);
  2292. }
  2293. /// visitBitTestHeader - This function emits necessary code to produce value
  2294. /// suitable for "bit tests"
  2295. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2296. MachineBasicBlock *SwitchBB) {
  2297. SDLoc dl = getCurSDLoc();
  2298. // Subtract the minimum value
  2299. SDValue SwitchOp = getValue(B.SValue);
  2300. EVT VT = SwitchOp.getValueType();
  2301. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2302. DAG.getConstant(B.First, dl, VT));
  2303. // Check range
  2304. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2305. SDValue RangeCmp = DAG.getSetCC(
  2306. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2307. Sub.getValueType()),
  2308. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2309. // Determine the type of the test operands.
  2310. bool UsePtrType = false;
  2311. if (!TLI.isTypeLegal(VT))
  2312. UsePtrType = true;
  2313. else {
  2314. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2315. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2316. // Switch table case range are encoded into series of masks.
  2317. // Just use pointer type, it's guaranteed to fit.
  2318. UsePtrType = true;
  2319. break;
  2320. }
  2321. }
  2322. if (UsePtrType) {
  2323. VT = TLI.getPointerTy(DAG.getDataLayout());
  2324. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2325. }
  2326. B.RegVT = VT.getSimpleVT();
  2327. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2328. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2329. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2330. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2331. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2332. SwitchBB->normalizeSuccProbs();
  2333. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2334. MVT::Other, CopyTo, RangeCmp,
  2335. DAG.getBasicBlock(B.Default));
  2336. // Avoid emitting unnecessary branches to the next block.
  2337. if (MBB != NextBlock(SwitchBB))
  2338. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2339. DAG.getBasicBlock(MBB));
  2340. DAG.setRoot(BrRange);
  2341. }
  2342. /// visitBitTestCase - this function produces one "bit test"
  2343. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2344. MachineBasicBlock* NextMBB,
  2345. BranchProbability BranchProbToNext,
  2346. unsigned Reg,
  2347. BitTestCase &B,
  2348. MachineBasicBlock *SwitchBB) {
  2349. SDLoc dl = getCurSDLoc();
  2350. MVT VT = BB.RegVT;
  2351. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2352. SDValue Cmp;
  2353. unsigned PopCount = countPopulation(B.Mask);
  2354. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2355. if (PopCount == 1) {
  2356. // Testing for a single bit; just compare the shift count with what it
  2357. // would need to be to shift a 1 bit in that position.
  2358. Cmp = DAG.getSetCC(
  2359. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2360. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2361. ISD::SETEQ);
  2362. } else if (PopCount == BB.Range) {
  2363. // There is only one zero bit in the range, test for it directly.
  2364. Cmp = DAG.getSetCC(
  2365. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2366. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2367. ISD::SETNE);
  2368. } else {
  2369. // Make desired shift
  2370. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2371. DAG.getConstant(1, dl, VT), ShiftOp);
  2372. // Emit bit tests and jumps
  2373. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2374. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2375. Cmp = DAG.getSetCC(
  2376. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2377. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2378. }
  2379. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2380. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2381. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2382. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2383. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2384. // one as they are relative probabilities (and thus work more like weights),
  2385. // and hence we need to normalize them to let the sum of them become one.
  2386. SwitchBB->normalizeSuccProbs();
  2387. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2388. MVT::Other, getControlRoot(),
  2389. Cmp, DAG.getBasicBlock(B.TargetBB));
  2390. // Avoid emitting unnecessary branches to the next block.
  2391. if (NextMBB != NextBlock(SwitchBB))
  2392. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2393. DAG.getBasicBlock(NextMBB));
  2394. DAG.setRoot(BrAnd);
  2395. }
  2396. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2397. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2398. // Retrieve successors. Look through artificial IR level blocks like
  2399. // catchswitch for successors.
  2400. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2401. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2402. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2403. // have to do anything here to lower funclet bundles.
  2404. assert(!I.hasOperandBundlesOtherThan(
  2405. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2406. "Cannot lower invokes with arbitrary operand bundles yet!");
  2407. const Value *Callee(I.getCalledValue());
  2408. const Function *Fn = dyn_cast<Function>(Callee);
  2409. if (isa<InlineAsm>(Callee))
  2410. visitInlineAsm(&I);
  2411. else if (Fn && Fn->isIntrinsic()) {
  2412. switch (Fn->getIntrinsicID()) {
  2413. default:
  2414. llvm_unreachable("Cannot invoke this intrinsic");
  2415. case Intrinsic::donothing:
  2416. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2417. break;
  2418. case Intrinsic::experimental_patchpoint_void:
  2419. case Intrinsic::experimental_patchpoint_i64:
  2420. visitPatchpoint(&I, EHPadBB);
  2421. break;
  2422. case Intrinsic::experimental_gc_statepoint:
  2423. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2424. break;
  2425. case Intrinsic::wasm_rethrow_in_catch: {
  2426. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2427. // special because it can be invoked, so we manually lower it to a DAG
  2428. // node here.
  2429. SmallVector<SDValue, 8> Ops;
  2430. Ops.push_back(getRoot()); // inchain
  2431. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2432. Ops.push_back(
  2433. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2434. TLI.getPointerTy(DAG.getDataLayout())));
  2435. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2436. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2437. break;
  2438. }
  2439. }
  2440. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2441. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2442. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2443. // intrinsic, and right now there are no plans to support other intrinsics
  2444. // with deopt state.
  2445. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2446. } else {
  2447. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2448. }
  2449. // If the value of the invoke is used outside of its defining block, make it
  2450. // available as a virtual register.
  2451. // We already took care of the exported value for the statepoint instruction
  2452. // during call to the LowerStatepoint.
  2453. if (!isStatepoint(I)) {
  2454. CopyToExportRegsIfNeeded(&I);
  2455. }
  2456. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2457. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2458. BranchProbability EHPadBBProb =
  2459. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2460. : BranchProbability::getZero();
  2461. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2462. // Update successor info.
  2463. addSuccessorWithProb(InvokeMBB, Return);
  2464. for (auto &UnwindDest : UnwindDests) {
  2465. UnwindDest.first->setIsEHPad();
  2466. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2467. }
  2468. InvokeMBB->normalizeSuccProbs();
  2469. // Drop into normal successor.
  2470. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2471. DAG.getBasicBlock(Return)));
  2472. }
  2473. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2474. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2475. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2476. // have to do anything here to lower funclet bundles.
  2477. assert(!I.hasOperandBundlesOtherThan(
  2478. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2479. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2480. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2481. "Only know how to handle inlineasm callbr");
  2482. visitInlineAsm(&I);
  2483. // Retrieve successors.
  2484. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2485. // Update successor info.
  2486. addSuccessorWithProb(CallBrMBB, Return);
  2487. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2488. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2489. addSuccessorWithProb(CallBrMBB, Target);
  2490. }
  2491. CallBrMBB->normalizeSuccProbs();
  2492. // Drop into default successor.
  2493. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2494. MVT::Other, getControlRoot(),
  2495. DAG.getBasicBlock(Return)));
  2496. }
  2497. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2498. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2499. }
  2500. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2501. assert(FuncInfo.MBB->isEHPad() &&
  2502. "Call to landingpad not in landing pad!");
  2503. // If there aren't registers to copy the values into (e.g., during SjLj
  2504. // exceptions), then don't bother to create these DAG nodes.
  2505. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2506. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2507. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2508. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2509. return;
  2510. // If landingpad's return type is token type, we don't create DAG nodes
  2511. // for its exception pointer and selector value. The extraction of exception
  2512. // pointer or selector value from token type landingpads is not currently
  2513. // supported.
  2514. if (LP.getType()->isTokenTy())
  2515. return;
  2516. SmallVector<EVT, 2> ValueVTs;
  2517. SDLoc dl = getCurSDLoc();
  2518. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2519. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2520. // Get the two live-in registers as SDValues. The physregs have already been
  2521. // copied into virtual registers.
  2522. SDValue Ops[2];
  2523. if (FuncInfo.ExceptionPointerVirtReg) {
  2524. Ops[0] = DAG.getZExtOrTrunc(
  2525. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2526. FuncInfo.ExceptionPointerVirtReg,
  2527. TLI.getPointerTy(DAG.getDataLayout())),
  2528. dl, ValueVTs[0]);
  2529. } else {
  2530. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2531. }
  2532. Ops[1] = DAG.getZExtOrTrunc(
  2533. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2534. FuncInfo.ExceptionSelectorVirtReg,
  2535. TLI.getPointerTy(DAG.getDataLayout())),
  2536. dl, ValueVTs[1]);
  2537. // Merge into one.
  2538. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2539. DAG.getVTList(ValueVTs), Ops);
  2540. setValue(&LP, Res);
  2541. }
  2542. void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
  2543. #ifndef NDEBUG
  2544. for (const CaseCluster &CC : Clusters)
  2545. assert(CC.Low == CC.High && "Input clusters must be single-case");
  2546. #endif
  2547. llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
  2548. return a.Low->getValue().slt(b.Low->getValue());
  2549. });
  2550. // Merge adjacent clusters with the same destination.
  2551. const unsigned N = Clusters.size();
  2552. unsigned DstIndex = 0;
  2553. for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
  2554. CaseCluster &CC = Clusters[SrcIndex];
  2555. const ConstantInt *CaseVal = CC.Low;
  2556. MachineBasicBlock *Succ = CC.MBB;
  2557. if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
  2558. (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
  2559. // If this case has the same successor and is a neighbour, merge it into
  2560. // the previous cluster.
  2561. Clusters[DstIndex - 1].High = CaseVal;
  2562. Clusters[DstIndex - 1].Prob += CC.Prob;
  2563. } else {
  2564. std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
  2565. sizeof(Clusters[SrcIndex]));
  2566. }
  2567. }
  2568. Clusters.resize(DstIndex);
  2569. }
  2570. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2571. MachineBasicBlock *Last) {
  2572. // Update JTCases.
  2573. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  2574. if (JTCases[i].first.HeaderBB == First)
  2575. JTCases[i].first.HeaderBB = Last;
  2576. // Update BitTestCases.
  2577. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  2578. if (BitTestCases[i].Parent == First)
  2579. BitTestCases[i].Parent = Last;
  2580. }
  2581. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2582. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2583. // Update machine-CFG edges with unique successors.
  2584. SmallSet<BasicBlock*, 32> Done;
  2585. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2586. BasicBlock *BB = I.getSuccessor(i);
  2587. bool Inserted = Done.insert(BB).second;
  2588. if (!Inserted)
  2589. continue;
  2590. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2591. addSuccessorWithProb(IndirectBrMBB, Succ);
  2592. }
  2593. IndirectBrMBB->normalizeSuccProbs();
  2594. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2595. MVT::Other, getControlRoot(),
  2596. getValue(I.getAddress())));
  2597. }
  2598. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2599. if (!DAG.getTarget().Options.TrapUnreachable)
  2600. return;
  2601. // We may be able to ignore unreachable behind a noreturn call.
  2602. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2603. const BasicBlock &BB = *I.getParent();
  2604. if (&I != &BB.front()) {
  2605. BasicBlock::const_iterator PredI =
  2606. std::prev(BasicBlock::const_iterator(&I));
  2607. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2608. if (Call->doesNotReturn())
  2609. return;
  2610. }
  2611. }
  2612. }
  2613. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2614. }
  2615. void SelectionDAGBuilder::visitFSub(const User &I) {
  2616. // -0.0 - X --> fneg
  2617. Type *Ty = I.getType();
  2618. if (isa<Constant>(I.getOperand(0)) &&
  2619. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2620. SDValue Op2 = getValue(I.getOperand(1));
  2621. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2622. Op2.getValueType(), Op2));
  2623. return;
  2624. }
  2625. visitBinary(I, ISD::FSUB);
  2626. }
  2627. /// Checks if the given instruction performs a vector reduction, in which case
  2628. /// we have the freedom to alter the elements in the result as long as the
  2629. /// reduction of them stays unchanged.
  2630. static bool isVectorReductionOp(const User *I) {
  2631. const Instruction *Inst = dyn_cast<Instruction>(I);
  2632. if (!Inst || !Inst->getType()->isVectorTy())
  2633. return false;
  2634. auto OpCode = Inst->getOpcode();
  2635. switch (OpCode) {
  2636. case Instruction::Add:
  2637. case Instruction::Mul:
  2638. case Instruction::And:
  2639. case Instruction::Or:
  2640. case Instruction::Xor:
  2641. break;
  2642. case Instruction::FAdd:
  2643. case Instruction::FMul:
  2644. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2645. if (FPOp->getFastMathFlags().isFast())
  2646. break;
  2647. LLVM_FALLTHROUGH;
  2648. default:
  2649. return false;
  2650. }
  2651. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2652. // Ensure the reduction size is a power of 2.
  2653. if (!isPowerOf2_32(ElemNum))
  2654. return false;
  2655. unsigned ElemNumToReduce = ElemNum;
  2656. // Do DFS search on the def-use chain from the given instruction. We only
  2657. // allow four kinds of operations during the search until we reach the
  2658. // instruction that extracts the first element from the vector:
  2659. //
  2660. // 1. The reduction operation of the same opcode as the given instruction.
  2661. //
  2662. // 2. PHI node.
  2663. //
  2664. // 3. ShuffleVector instruction together with a reduction operation that
  2665. // does a partial reduction.
  2666. //
  2667. // 4. ExtractElement that extracts the first element from the vector, and we
  2668. // stop searching the def-use chain here.
  2669. //
  2670. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2671. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2672. // a reduction operation if we meet any other instructions other than those
  2673. // listed above.
  2674. SmallVector<const User *, 16> UsersToVisit{Inst};
  2675. SmallPtrSet<const User *, 16> Visited;
  2676. bool ReduxExtracted = false;
  2677. while (!UsersToVisit.empty()) {
  2678. auto User = UsersToVisit.back();
  2679. UsersToVisit.pop_back();
  2680. if (!Visited.insert(User).second)
  2681. continue;
  2682. for (const auto &U : User->users()) {
  2683. auto Inst = dyn_cast<Instruction>(U);
  2684. if (!Inst)
  2685. return false;
  2686. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2687. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2688. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2689. return false;
  2690. UsersToVisit.push_back(U);
  2691. } else if (const ShuffleVectorInst *ShufInst =
  2692. dyn_cast<ShuffleVectorInst>(U)) {
  2693. // Detect the following pattern: A ShuffleVector instruction together
  2694. // with a reduction that do partial reduction on the first and second
  2695. // ElemNumToReduce / 2 elements, and store the result in
  2696. // ElemNumToReduce / 2 elements in another vector.
  2697. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2698. if (ResultElements < ElemNum)
  2699. return false;
  2700. if (ElemNumToReduce == 1)
  2701. return false;
  2702. if (!isa<UndefValue>(U->getOperand(1)))
  2703. return false;
  2704. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2705. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2706. return false;
  2707. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2708. if (ShufInst->getMaskValue(i) != -1)
  2709. return false;
  2710. // There is only one user of this ShuffleVector instruction, which
  2711. // must be a reduction operation.
  2712. if (!U->hasOneUse())
  2713. return false;
  2714. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2715. if (!U2 || U2->getOpcode() != OpCode)
  2716. return false;
  2717. // Check operands of the reduction operation.
  2718. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2719. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2720. UsersToVisit.push_back(U2);
  2721. ElemNumToReduce /= 2;
  2722. } else
  2723. return false;
  2724. } else if (isa<ExtractElementInst>(U)) {
  2725. // At this moment we should have reduced all elements in the vector.
  2726. if (ElemNumToReduce != 1)
  2727. return false;
  2728. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2729. if (!Val || !Val->isZero())
  2730. return false;
  2731. ReduxExtracted = true;
  2732. } else
  2733. return false;
  2734. }
  2735. }
  2736. return ReduxExtracted;
  2737. }
  2738. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2739. SDNodeFlags Flags;
  2740. SDValue Op = getValue(I.getOperand(0));
  2741. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2742. Op, Flags);
  2743. setValue(&I, UnNodeValue);
  2744. }
  2745. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2746. SDNodeFlags Flags;
  2747. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2748. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2749. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2750. }
  2751. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2752. Flags.setExact(ExactOp->isExact());
  2753. }
  2754. if (isVectorReductionOp(&I)) {
  2755. Flags.setVectorReduction(true);
  2756. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2757. }
  2758. SDValue Op1 = getValue(I.getOperand(0));
  2759. SDValue Op2 = getValue(I.getOperand(1));
  2760. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2761. Op1, Op2, Flags);
  2762. setValue(&I, BinNodeValue);
  2763. }
  2764. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2765. SDValue Op1 = getValue(I.getOperand(0));
  2766. SDValue Op2 = getValue(I.getOperand(1));
  2767. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2768. Op1.getValueType(), DAG.getDataLayout());
  2769. // Coerce the shift amount to the right type if we can.
  2770. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2771. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2772. unsigned Op2Size = Op2.getValueSizeInBits();
  2773. SDLoc DL = getCurSDLoc();
  2774. // If the operand is smaller than the shift count type, promote it.
  2775. if (ShiftSize > Op2Size)
  2776. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2777. // If the operand is larger than the shift count type but the shift
  2778. // count type has enough bits to represent any shift value, truncate
  2779. // it now. This is a common case and it exposes the truncate to
  2780. // optimization early.
  2781. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2782. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2783. // Otherwise we'll need to temporarily settle for some other convenient
  2784. // type. Type legalization will make adjustments once the shiftee is split.
  2785. else
  2786. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2787. }
  2788. bool nuw = false;
  2789. bool nsw = false;
  2790. bool exact = false;
  2791. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2792. if (const OverflowingBinaryOperator *OFBinOp =
  2793. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2794. nuw = OFBinOp->hasNoUnsignedWrap();
  2795. nsw = OFBinOp->hasNoSignedWrap();
  2796. }
  2797. if (const PossiblyExactOperator *ExactOp =
  2798. dyn_cast<const PossiblyExactOperator>(&I))
  2799. exact = ExactOp->isExact();
  2800. }
  2801. SDNodeFlags Flags;
  2802. Flags.setExact(exact);
  2803. Flags.setNoSignedWrap(nsw);
  2804. Flags.setNoUnsignedWrap(nuw);
  2805. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2806. Flags);
  2807. setValue(&I, Res);
  2808. }
  2809. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2810. SDValue Op1 = getValue(I.getOperand(0));
  2811. SDValue Op2 = getValue(I.getOperand(1));
  2812. SDNodeFlags Flags;
  2813. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2814. cast<PossiblyExactOperator>(&I)->isExact());
  2815. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2816. Op2, Flags));
  2817. }
  2818. void SelectionDAGBuilder::visitICmp(const User &I) {
  2819. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2820. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2821. predicate = IC->getPredicate();
  2822. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2823. predicate = ICmpInst::Predicate(IC->getPredicate());
  2824. SDValue Op1 = getValue(I.getOperand(0));
  2825. SDValue Op2 = getValue(I.getOperand(1));
  2826. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2827. auto &TLI = DAG.getTargetLoweringInfo();
  2828. EVT MemVT =
  2829. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2830. // If a pointer's DAG type is larger than its memory type then the DAG values
  2831. // are zero-extended. This breaks signed comparisons so truncate back to the
  2832. // underlying type before doing the compare.
  2833. if (Op1.getValueType() != MemVT) {
  2834. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2835. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2836. }
  2837. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2838. I.getType());
  2839. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2840. }
  2841. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2842. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2843. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2844. predicate = FC->getPredicate();
  2845. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2846. predicate = FCmpInst::Predicate(FC->getPredicate());
  2847. SDValue Op1 = getValue(I.getOperand(0));
  2848. SDValue Op2 = getValue(I.getOperand(1));
  2849. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2850. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2851. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2852. Condition = getFCmpCodeWithoutNaN(Condition);
  2853. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2854. I.getType());
  2855. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2856. }
  2857. // Check if the condition of the select has one use or two users that are both
  2858. // selects with the same condition.
  2859. static bool hasOnlySelectUsers(const Value *Cond) {
  2860. return llvm::all_of(Cond->users(), [](const Value *V) {
  2861. return isa<SelectInst>(V);
  2862. });
  2863. }
  2864. void SelectionDAGBuilder::visitSelect(const User &I) {
  2865. SmallVector<EVT, 4> ValueVTs;
  2866. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2867. ValueVTs);
  2868. unsigned NumValues = ValueVTs.size();
  2869. if (NumValues == 0) return;
  2870. SmallVector<SDValue, 4> Values(NumValues);
  2871. SDValue Cond = getValue(I.getOperand(0));
  2872. SDValue LHSVal = getValue(I.getOperand(1));
  2873. SDValue RHSVal = getValue(I.getOperand(2));
  2874. auto BaseOps = {Cond};
  2875. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2876. ISD::VSELECT : ISD::SELECT;
  2877. bool IsUnaryAbs = false;
  2878. // Min/max matching is only viable if all output VTs are the same.
  2879. if (is_splat(ValueVTs)) {
  2880. EVT VT = ValueVTs[0];
  2881. LLVMContext &Ctx = *DAG.getContext();
  2882. auto &TLI = DAG.getTargetLoweringInfo();
  2883. // We care about the legality of the operation after it has been type
  2884. // legalized.
  2885. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2886. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2887. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2888. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2889. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2890. // min/max is legal on the scalar type.
  2891. bool UseScalarMinMax = VT.isVector() &&
  2892. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2893. Value *LHS, *RHS;
  2894. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2895. ISD::NodeType Opc = ISD::DELETED_NODE;
  2896. switch (SPR.Flavor) {
  2897. case SPF_UMAX: Opc = ISD::UMAX; break;
  2898. case SPF_UMIN: Opc = ISD::UMIN; break;
  2899. case SPF_SMAX: Opc = ISD::SMAX; break;
  2900. case SPF_SMIN: Opc = ISD::SMIN; break;
  2901. case SPF_FMINNUM:
  2902. switch (SPR.NaNBehavior) {
  2903. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2904. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2905. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2906. case SPNB_RETURNS_ANY: {
  2907. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2908. Opc = ISD::FMINNUM;
  2909. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2910. Opc = ISD::FMINIMUM;
  2911. else if (UseScalarMinMax)
  2912. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2913. ISD::FMINNUM : ISD::FMINIMUM;
  2914. break;
  2915. }
  2916. }
  2917. break;
  2918. case SPF_FMAXNUM:
  2919. switch (SPR.NaNBehavior) {
  2920. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2921. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2922. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2923. case SPNB_RETURNS_ANY:
  2924. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2925. Opc = ISD::FMAXNUM;
  2926. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2927. Opc = ISD::FMAXIMUM;
  2928. else if (UseScalarMinMax)
  2929. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2930. ISD::FMAXNUM : ISD::FMAXIMUM;
  2931. break;
  2932. }
  2933. break;
  2934. case SPF_ABS:
  2935. IsUnaryAbs = true;
  2936. Opc = ISD::ABS;
  2937. break;
  2938. case SPF_NABS:
  2939. // TODO: we need to produce sub(0, abs(X)).
  2940. default: break;
  2941. }
  2942. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2943. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2944. (UseScalarMinMax &&
  2945. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2946. // If the underlying comparison instruction is used by any other
  2947. // instruction, the consumed instructions won't be destroyed, so it is
  2948. // not profitable to convert to a min/max.
  2949. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2950. OpCode = Opc;
  2951. LHSVal = getValue(LHS);
  2952. RHSVal = getValue(RHS);
  2953. BaseOps = {};
  2954. }
  2955. if (IsUnaryAbs) {
  2956. OpCode = Opc;
  2957. LHSVal = getValue(LHS);
  2958. BaseOps = {};
  2959. }
  2960. }
  2961. if (IsUnaryAbs) {
  2962. for (unsigned i = 0; i != NumValues; ++i) {
  2963. Values[i] =
  2964. DAG.getNode(OpCode, getCurSDLoc(),
  2965. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2966. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2967. }
  2968. } else {
  2969. for (unsigned i = 0; i != NumValues; ++i) {
  2970. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2971. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2972. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2973. Values[i] = DAG.getNode(
  2974. OpCode, getCurSDLoc(),
  2975. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2976. }
  2977. }
  2978. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2979. DAG.getVTList(ValueVTs), Values));
  2980. }
  2981. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2982. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2983. SDValue N = getValue(I.getOperand(0));
  2984. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2985. I.getType());
  2986. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2987. }
  2988. void SelectionDAGBuilder::visitZExt(const User &I) {
  2989. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2990. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2991. SDValue N = getValue(I.getOperand(0));
  2992. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2993. I.getType());
  2994. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2995. }
  2996. void SelectionDAGBuilder::visitSExt(const User &I) {
  2997. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2998. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2999. SDValue N = getValue(I.getOperand(0));
  3000. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3001. I.getType());
  3002. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  3003. }
  3004. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  3005. // FPTrunc is never a no-op cast, no need to check
  3006. SDValue N = getValue(I.getOperand(0));
  3007. SDLoc dl = getCurSDLoc();
  3008. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3009. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3010. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  3011. DAG.getTargetConstant(
  3012. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  3013. }
  3014. void SelectionDAGBuilder::visitFPExt(const User &I) {
  3015. // FPExt is never a no-op cast, no need to check
  3016. SDValue N = getValue(I.getOperand(0));
  3017. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3018. I.getType());
  3019. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  3020. }
  3021. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  3022. // FPToUI is never a no-op cast, no need to check
  3023. SDValue N = getValue(I.getOperand(0));
  3024. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3025. I.getType());
  3026. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3027. }
  3028. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3029. // FPToSI is never a no-op cast, no need to check
  3030. SDValue N = getValue(I.getOperand(0));
  3031. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3032. I.getType());
  3033. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3034. }
  3035. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3036. // UIToFP is never a no-op cast, no need to check
  3037. SDValue N = getValue(I.getOperand(0));
  3038. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3039. I.getType());
  3040. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3041. }
  3042. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3043. // SIToFP is never a no-op cast, no need to check
  3044. SDValue N = getValue(I.getOperand(0));
  3045. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3046. I.getType());
  3047. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3048. }
  3049. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3050. // What to do depends on the size of the integer and the size of the pointer.
  3051. // We can either truncate, zero extend, or no-op, accordingly.
  3052. SDValue N = getValue(I.getOperand(0));
  3053. auto &TLI = DAG.getTargetLoweringInfo();
  3054. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3055. I.getType());
  3056. EVT PtrMemVT =
  3057. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3058. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3059. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3060. setValue(&I, N);
  3061. }
  3062. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3063. // What to do depends on the size of the integer and the size of the pointer.
  3064. // We can either truncate, zero extend, or no-op, accordingly.
  3065. SDValue N = getValue(I.getOperand(0));
  3066. auto &TLI = DAG.getTargetLoweringInfo();
  3067. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3068. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3069. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3070. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3071. setValue(&I, N);
  3072. }
  3073. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3074. SDValue N = getValue(I.getOperand(0));
  3075. SDLoc dl = getCurSDLoc();
  3076. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3077. I.getType());
  3078. // BitCast assures us that source and destination are the same size so this is
  3079. // either a BITCAST or a no-op.
  3080. if (DestVT != N.getValueType())
  3081. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3082. DestVT, N)); // convert types.
  3083. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3084. // might fold any kind of constant expression to an integer constant and that
  3085. // is not what we are looking for. Only recognize a bitcast of a genuine
  3086. // constant integer as an opaque constant.
  3087. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3088. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3089. /*isOpaque*/true));
  3090. else
  3091. setValue(&I, N); // noop cast.
  3092. }
  3093. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3094. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3095. const Value *SV = I.getOperand(0);
  3096. SDValue N = getValue(SV);
  3097. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3098. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3099. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3100. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3101. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3102. setValue(&I, N);
  3103. }
  3104. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3105. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3106. SDValue InVec = getValue(I.getOperand(0));
  3107. SDValue InVal = getValue(I.getOperand(1));
  3108. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3109. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3110. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3111. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3112. InVec, InVal, InIdx));
  3113. }
  3114. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3115. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3116. SDValue InVec = getValue(I.getOperand(0));
  3117. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3118. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3119. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3120. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3121. InVec, InIdx));
  3122. }
  3123. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3124. SDValue Src1 = getValue(I.getOperand(0));
  3125. SDValue Src2 = getValue(I.getOperand(1));
  3126. SDLoc DL = getCurSDLoc();
  3127. SmallVector<int, 8> Mask;
  3128. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3129. unsigned MaskNumElts = Mask.size();
  3130. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3131. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3132. EVT SrcVT = Src1.getValueType();
  3133. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3134. if (SrcNumElts == MaskNumElts) {
  3135. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3136. return;
  3137. }
  3138. // Normalize the shuffle vector since mask and vector length don't match.
  3139. if (SrcNumElts < MaskNumElts) {
  3140. // Mask is longer than the source vectors. We can use concatenate vector to
  3141. // make the mask and vectors lengths match.
  3142. if (MaskNumElts % SrcNumElts == 0) {
  3143. // Mask length is a multiple of the source vector length.
  3144. // Check if the shuffle is some kind of concatenation of the input
  3145. // vectors.
  3146. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3147. bool IsConcat = true;
  3148. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3149. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3150. int Idx = Mask[i];
  3151. if (Idx < 0)
  3152. continue;
  3153. // Ensure the indices in each SrcVT sized piece are sequential and that
  3154. // the same source is used for the whole piece.
  3155. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3156. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3157. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3158. IsConcat = false;
  3159. break;
  3160. }
  3161. // Remember which source this index came from.
  3162. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3163. }
  3164. // The shuffle is concatenating multiple vectors together. Just emit
  3165. // a CONCAT_VECTORS operation.
  3166. if (IsConcat) {
  3167. SmallVector<SDValue, 8> ConcatOps;
  3168. for (auto Src : ConcatSrcs) {
  3169. if (Src < 0)
  3170. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3171. else if (Src == 0)
  3172. ConcatOps.push_back(Src1);
  3173. else
  3174. ConcatOps.push_back(Src2);
  3175. }
  3176. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3177. return;
  3178. }
  3179. }
  3180. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3181. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3182. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3183. PaddedMaskNumElts);
  3184. // Pad both vectors with undefs to make them the same length as the mask.
  3185. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3186. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3187. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3188. MOps1[0] = Src1;
  3189. MOps2[0] = Src2;
  3190. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3191. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3192. // Readjust mask for new input vector length.
  3193. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3194. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3195. int Idx = Mask[i];
  3196. if (Idx >= (int)SrcNumElts)
  3197. Idx -= SrcNumElts - PaddedMaskNumElts;
  3198. MappedOps[i] = Idx;
  3199. }
  3200. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3201. // If the concatenated vector was padded, extract a subvector with the
  3202. // correct number of elements.
  3203. if (MaskNumElts != PaddedMaskNumElts)
  3204. Result = DAG.getNode(
  3205. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3206. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3207. setValue(&I, Result);
  3208. return;
  3209. }
  3210. if (SrcNumElts > MaskNumElts) {
  3211. // Analyze the access pattern of the vector to see if we can extract
  3212. // two subvectors and do the shuffle.
  3213. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3214. bool CanExtract = true;
  3215. for (int Idx : Mask) {
  3216. unsigned Input = 0;
  3217. if (Idx < 0)
  3218. continue;
  3219. if (Idx >= (int)SrcNumElts) {
  3220. Input = 1;
  3221. Idx -= SrcNumElts;
  3222. }
  3223. // If all the indices come from the same MaskNumElts sized portion of
  3224. // the sources we can use extract. Also make sure the extract wouldn't
  3225. // extract past the end of the source.
  3226. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3227. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3228. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3229. CanExtract = false;
  3230. // Make sure we always update StartIdx as we use it to track if all
  3231. // elements are undef.
  3232. StartIdx[Input] = NewStartIdx;
  3233. }
  3234. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3235. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3236. return;
  3237. }
  3238. if (CanExtract) {
  3239. // Extract appropriate subvector and generate a vector shuffle
  3240. for (unsigned Input = 0; Input < 2; ++Input) {
  3241. SDValue &Src = Input == 0 ? Src1 : Src2;
  3242. if (StartIdx[Input] < 0)
  3243. Src = DAG.getUNDEF(VT);
  3244. else {
  3245. Src = DAG.getNode(
  3246. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3247. DAG.getConstant(StartIdx[Input], DL,
  3248. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3249. }
  3250. }
  3251. // Calculate new mask.
  3252. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3253. for (int &Idx : MappedOps) {
  3254. if (Idx >= (int)SrcNumElts)
  3255. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3256. else if (Idx >= 0)
  3257. Idx -= StartIdx[0];
  3258. }
  3259. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3260. return;
  3261. }
  3262. }
  3263. // We can't use either concat vectors or extract subvectors so fall back to
  3264. // replacing the shuffle with extract and build vector.
  3265. // to insert and build vector.
  3266. EVT EltVT = VT.getVectorElementType();
  3267. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3268. SmallVector<SDValue,8> Ops;
  3269. for (int Idx : Mask) {
  3270. SDValue Res;
  3271. if (Idx < 0) {
  3272. Res = DAG.getUNDEF(EltVT);
  3273. } else {
  3274. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3275. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3276. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3277. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3278. }
  3279. Ops.push_back(Res);
  3280. }
  3281. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3282. }
  3283. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3284. ArrayRef<unsigned> Indices;
  3285. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3286. Indices = IV->getIndices();
  3287. else
  3288. Indices = cast<ConstantExpr>(&I)->getIndices();
  3289. const Value *Op0 = I.getOperand(0);
  3290. const Value *Op1 = I.getOperand(1);
  3291. Type *AggTy = I.getType();
  3292. Type *ValTy = Op1->getType();
  3293. bool IntoUndef = isa<UndefValue>(Op0);
  3294. bool FromUndef = isa<UndefValue>(Op1);
  3295. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3296. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3297. SmallVector<EVT, 4> AggValueVTs;
  3298. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3299. SmallVector<EVT, 4> ValValueVTs;
  3300. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3301. unsigned NumAggValues = AggValueVTs.size();
  3302. unsigned NumValValues = ValValueVTs.size();
  3303. SmallVector<SDValue, 4> Values(NumAggValues);
  3304. // Ignore an insertvalue that produces an empty object
  3305. if (!NumAggValues) {
  3306. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3307. return;
  3308. }
  3309. SDValue Agg = getValue(Op0);
  3310. unsigned i = 0;
  3311. // Copy the beginning value(s) from the original aggregate.
  3312. for (; i != LinearIndex; ++i)
  3313. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3314. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3315. // Copy values from the inserted value(s).
  3316. if (NumValValues) {
  3317. SDValue Val = getValue(Op1);
  3318. for (; i != LinearIndex + NumValValues; ++i)
  3319. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3320. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3321. }
  3322. // Copy remaining value(s) from the original aggregate.
  3323. for (; i != NumAggValues; ++i)
  3324. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3325. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3326. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3327. DAG.getVTList(AggValueVTs), Values));
  3328. }
  3329. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3330. ArrayRef<unsigned> Indices;
  3331. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3332. Indices = EV->getIndices();
  3333. else
  3334. Indices = cast<ConstantExpr>(&I)->getIndices();
  3335. const Value *Op0 = I.getOperand(0);
  3336. Type *AggTy = Op0->getType();
  3337. Type *ValTy = I.getType();
  3338. bool OutOfUndef = isa<UndefValue>(Op0);
  3339. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3340. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3341. SmallVector<EVT, 4> ValValueVTs;
  3342. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3343. unsigned NumValValues = ValValueVTs.size();
  3344. // Ignore a extractvalue that produces an empty object
  3345. if (!NumValValues) {
  3346. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3347. return;
  3348. }
  3349. SmallVector<SDValue, 4> Values(NumValValues);
  3350. SDValue Agg = getValue(Op0);
  3351. // Copy out the selected value(s).
  3352. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3353. Values[i - LinearIndex] =
  3354. OutOfUndef ?
  3355. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3356. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3357. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3358. DAG.getVTList(ValValueVTs), Values));
  3359. }
  3360. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3361. Value *Op0 = I.getOperand(0);
  3362. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3363. // element which holds a pointer.
  3364. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3365. SDValue N = getValue(Op0);
  3366. SDLoc dl = getCurSDLoc();
  3367. auto &TLI = DAG.getTargetLoweringInfo();
  3368. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3369. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3370. // Normalize Vector GEP - all scalar operands should be converted to the
  3371. // splat vector.
  3372. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3373. cast<VectorType>(I.getType())->getVectorNumElements() : 0;
  3374. if (VectorWidth && !N.getValueType().isVector()) {
  3375. LLVMContext &Context = *DAG.getContext();
  3376. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3377. N = DAG.getSplatBuildVector(VT, dl, N);
  3378. }
  3379. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3380. GTI != E; ++GTI) {
  3381. const Value *Idx = GTI.getOperand();
  3382. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3383. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3384. if (Field) {
  3385. // N = N + Offset
  3386. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3387. // In an inbounds GEP with an offset that is nonnegative even when
  3388. // interpreted as signed, assume there is no unsigned overflow.
  3389. SDNodeFlags Flags;
  3390. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3391. Flags.setNoUnsignedWrap(true);
  3392. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3393. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3394. }
  3395. } else {
  3396. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3397. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3398. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3399. // If this is a scalar constant or a splat vector of constants,
  3400. // handle it quickly.
  3401. const auto *CI = dyn_cast<ConstantInt>(Idx);
  3402. if (!CI && isa<ConstantDataVector>(Idx) &&
  3403. cast<ConstantDataVector>(Idx)->getSplatValue())
  3404. CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
  3405. if (CI) {
  3406. if (CI->isZero())
  3407. continue;
  3408. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3409. LLVMContext &Context = *DAG.getContext();
  3410. SDValue OffsVal = VectorWidth ?
  3411. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3412. DAG.getConstant(Offs, dl, IdxTy);
  3413. // In an inbouds GEP with an offset that is nonnegative even when
  3414. // interpreted as signed, assume there is no unsigned overflow.
  3415. SDNodeFlags Flags;
  3416. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3417. Flags.setNoUnsignedWrap(true);
  3418. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3419. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3420. continue;
  3421. }
  3422. // N = N + Idx * ElementSize;
  3423. SDValue IdxN = getValue(Idx);
  3424. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3425. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3426. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3427. }
  3428. // If the index is smaller or larger than intptr_t, truncate or extend
  3429. // it.
  3430. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3431. // If this is a multiply by a power of two, turn it into a shl
  3432. // immediately. This is a very common case.
  3433. if (ElementSize != 1) {
  3434. if (ElementSize.isPowerOf2()) {
  3435. unsigned Amt = ElementSize.logBase2();
  3436. IdxN = DAG.getNode(ISD::SHL, dl,
  3437. N.getValueType(), IdxN,
  3438. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3439. } else {
  3440. SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
  3441. IdxN.getValueType());
  3442. IdxN = DAG.getNode(ISD::MUL, dl,
  3443. N.getValueType(), IdxN, Scale);
  3444. }
  3445. }
  3446. N = DAG.getNode(ISD::ADD, dl,
  3447. N.getValueType(), N, IdxN);
  3448. }
  3449. }
  3450. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3451. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3452. setValue(&I, N);
  3453. }
  3454. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3455. // If this is a fixed sized alloca in the entry block of the function,
  3456. // allocate it statically on the stack.
  3457. if (FuncInfo.StaticAllocaMap.count(&I))
  3458. return; // getValue will auto-populate this.
  3459. SDLoc dl = getCurSDLoc();
  3460. Type *Ty = I.getAllocatedType();
  3461. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3462. auto &DL = DAG.getDataLayout();
  3463. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3464. unsigned Align =
  3465. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3466. SDValue AllocSize = getValue(I.getArraySize());
  3467. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3468. if (AllocSize.getValueType() != IntPtr)
  3469. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3470. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3471. AllocSize,
  3472. DAG.getConstant(TySize, dl, IntPtr));
  3473. // Handle alignment. If the requested alignment is less than or equal to
  3474. // the stack alignment, ignore it. If the size is greater than or equal to
  3475. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3476. unsigned StackAlign =
  3477. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3478. if (Align <= StackAlign)
  3479. Align = 0;
  3480. // Round the size of the allocation up to the stack alignment size
  3481. // by add SA-1 to the size. This doesn't overflow because we're computing
  3482. // an address inside an alloca.
  3483. SDNodeFlags Flags;
  3484. Flags.setNoUnsignedWrap(true);
  3485. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3486. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3487. // Mask out the low bits for alignment purposes.
  3488. AllocSize =
  3489. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3490. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3491. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3492. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3493. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3494. setValue(&I, DSA);
  3495. DAG.setRoot(DSA.getValue(1));
  3496. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3497. }
  3498. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3499. if (I.isAtomic())
  3500. return visitAtomicLoad(I);
  3501. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3502. const Value *SV = I.getOperand(0);
  3503. if (TLI.supportSwiftError()) {
  3504. // Swifterror values can come from either a function parameter with
  3505. // swifterror attribute or an alloca with swifterror attribute.
  3506. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3507. if (Arg->hasSwiftErrorAttr())
  3508. return visitLoadFromSwiftError(I);
  3509. }
  3510. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3511. if (Alloca->isSwiftError())
  3512. return visitLoadFromSwiftError(I);
  3513. }
  3514. }
  3515. SDValue Ptr = getValue(SV);
  3516. Type *Ty = I.getType();
  3517. bool isVolatile = I.isVolatile();
  3518. bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
  3519. bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
  3520. bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
  3521. unsigned Alignment = I.getAlignment();
  3522. AAMDNodes AAInfo;
  3523. I.getAAMetadata(AAInfo);
  3524. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3525. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3526. SmallVector<uint64_t, 4> Offsets;
  3527. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3528. unsigned NumValues = ValueVTs.size();
  3529. if (NumValues == 0)
  3530. return;
  3531. SDValue Root;
  3532. bool ConstantMemory = false;
  3533. if (isVolatile || NumValues > MaxParallelChains)
  3534. // Serialize volatile loads with other side effects.
  3535. Root = getRoot();
  3536. else if (AA &&
  3537. AA->pointsToConstantMemory(MemoryLocation(
  3538. SV,
  3539. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3540. AAInfo))) {
  3541. // Do not serialize (non-volatile) loads of constant memory with anything.
  3542. Root = DAG.getEntryNode();
  3543. ConstantMemory = true;
  3544. } else {
  3545. // Do not serialize non-volatile loads against each other.
  3546. Root = DAG.getRoot();
  3547. }
  3548. SDLoc dl = getCurSDLoc();
  3549. if (isVolatile)
  3550. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3551. // An aggregate load cannot wrap around the address space, so offsets to its
  3552. // parts don't wrap either.
  3553. SDNodeFlags Flags;
  3554. Flags.setNoUnsignedWrap(true);
  3555. SmallVector<SDValue, 4> Values(NumValues);
  3556. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3557. EVT PtrVT = Ptr.getValueType();
  3558. unsigned ChainI = 0;
  3559. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3560. // Serializing loads here may result in excessive register pressure, and
  3561. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3562. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3563. // they are side-effect free or do not alias. The optimizer should really
  3564. // avoid this case by converting large object/array copies to llvm.memcpy
  3565. // (MaxParallelChains should always remain as failsafe).
  3566. if (ChainI == MaxParallelChains) {
  3567. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3568. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3569. makeArrayRef(Chains.data(), ChainI));
  3570. Root = Chain;
  3571. ChainI = 0;
  3572. }
  3573. SDValue A = DAG.getNode(ISD::ADD, dl,
  3574. PtrVT, Ptr,
  3575. DAG.getConstant(Offsets[i], dl, PtrVT),
  3576. Flags);
  3577. auto MMOFlags = MachineMemOperand::MONone;
  3578. if (isVolatile)
  3579. MMOFlags |= MachineMemOperand::MOVolatile;
  3580. if (isNonTemporal)
  3581. MMOFlags |= MachineMemOperand::MONonTemporal;
  3582. if (isInvariant)
  3583. MMOFlags |= MachineMemOperand::MOInvariant;
  3584. if (isDereferenceable)
  3585. MMOFlags |= MachineMemOperand::MODereferenceable;
  3586. MMOFlags |= TLI.getMMOFlags(I);
  3587. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3588. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3589. MMOFlags, AAInfo, Ranges);
  3590. Chains[ChainI] = L.getValue(1);
  3591. if (MemVTs[i] != ValueVTs[i])
  3592. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3593. Values[i] = L;
  3594. }
  3595. if (!ConstantMemory) {
  3596. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3597. makeArrayRef(Chains.data(), ChainI));
  3598. if (isVolatile)
  3599. DAG.setRoot(Chain);
  3600. else
  3601. PendingLoads.push_back(Chain);
  3602. }
  3603. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3604. DAG.getVTList(ValueVTs), Values));
  3605. }
  3606. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3607. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3608. "call visitStoreToSwiftError when backend supports swifterror");
  3609. SmallVector<EVT, 4> ValueVTs;
  3610. SmallVector<uint64_t, 4> Offsets;
  3611. const Value *SrcV = I.getOperand(0);
  3612. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3613. SrcV->getType(), ValueVTs, &Offsets);
  3614. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3615. "expect a single EVT for swifterror");
  3616. SDValue Src = getValue(SrcV);
  3617. // Create a virtual register, then update the virtual register.
  3618. unsigned VReg =
  3619. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3620. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3621. // Chain can be getRoot or getControlRoot.
  3622. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3623. SDValue(Src.getNode(), Src.getResNo()));
  3624. DAG.setRoot(CopyNode);
  3625. }
  3626. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3627. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3628. "call visitLoadFromSwiftError when backend supports swifterror");
  3629. assert(!I.isVolatile() &&
  3630. I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
  3631. I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
  3632. "Support volatile, non temporal, invariant for load_from_swift_error");
  3633. const Value *SV = I.getOperand(0);
  3634. Type *Ty = I.getType();
  3635. AAMDNodes AAInfo;
  3636. I.getAAMetadata(AAInfo);
  3637. assert(
  3638. (!AA ||
  3639. !AA->pointsToConstantMemory(MemoryLocation(
  3640. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3641. AAInfo))) &&
  3642. "load_from_swift_error should not be constant memory");
  3643. SmallVector<EVT, 4> ValueVTs;
  3644. SmallVector<uint64_t, 4> Offsets;
  3645. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3646. ValueVTs, &Offsets);
  3647. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3648. "expect a single EVT for swifterror");
  3649. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3650. SDValue L = DAG.getCopyFromReg(
  3651. getRoot(), getCurSDLoc(),
  3652. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3653. setValue(&I, L);
  3654. }
  3655. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3656. if (I.isAtomic())
  3657. return visitAtomicStore(I);
  3658. const Value *SrcV = I.getOperand(0);
  3659. const Value *PtrV = I.getOperand(1);
  3660. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3661. if (TLI.supportSwiftError()) {
  3662. // Swifterror values can come from either a function parameter with
  3663. // swifterror attribute or an alloca with swifterror attribute.
  3664. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3665. if (Arg->hasSwiftErrorAttr())
  3666. return visitStoreToSwiftError(I);
  3667. }
  3668. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3669. if (Alloca->isSwiftError())
  3670. return visitStoreToSwiftError(I);
  3671. }
  3672. }
  3673. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3674. SmallVector<uint64_t, 4> Offsets;
  3675. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3676. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3677. unsigned NumValues = ValueVTs.size();
  3678. if (NumValues == 0)
  3679. return;
  3680. // Get the lowered operands. Note that we do this after
  3681. // checking if NumResults is zero, because with zero results
  3682. // the operands won't have values in the map.
  3683. SDValue Src = getValue(SrcV);
  3684. SDValue Ptr = getValue(PtrV);
  3685. SDValue Root = getRoot();
  3686. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3687. SDLoc dl = getCurSDLoc();
  3688. EVT PtrVT = Ptr.getValueType();
  3689. unsigned Alignment = I.getAlignment();
  3690. AAMDNodes AAInfo;
  3691. I.getAAMetadata(AAInfo);
  3692. auto MMOFlags = MachineMemOperand::MONone;
  3693. if (I.isVolatile())
  3694. MMOFlags |= MachineMemOperand::MOVolatile;
  3695. if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
  3696. MMOFlags |= MachineMemOperand::MONonTemporal;
  3697. MMOFlags |= TLI.getMMOFlags(I);
  3698. // An aggregate load cannot wrap around the address space, so offsets to its
  3699. // parts don't wrap either.
  3700. SDNodeFlags Flags;
  3701. Flags.setNoUnsignedWrap(true);
  3702. unsigned ChainI = 0;
  3703. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3704. // See visitLoad comments.
  3705. if (ChainI == MaxParallelChains) {
  3706. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3707. makeArrayRef(Chains.data(), ChainI));
  3708. Root = Chain;
  3709. ChainI = 0;
  3710. }
  3711. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3712. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3713. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3714. if (MemVTs[i] != ValueVTs[i])
  3715. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3716. SDValue St =
  3717. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3718. Alignment, MMOFlags, AAInfo);
  3719. Chains[ChainI] = St;
  3720. }
  3721. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3722. makeArrayRef(Chains.data(), ChainI));
  3723. DAG.setRoot(StoreNode);
  3724. }
  3725. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3726. bool IsCompressing) {
  3727. SDLoc sdl = getCurSDLoc();
  3728. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3729. unsigned& Alignment) {
  3730. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3731. Src0 = I.getArgOperand(0);
  3732. Ptr = I.getArgOperand(1);
  3733. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3734. Mask = I.getArgOperand(3);
  3735. };
  3736. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3737. unsigned& Alignment) {
  3738. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3739. Src0 = I.getArgOperand(0);
  3740. Ptr = I.getArgOperand(1);
  3741. Mask = I.getArgOperand(2);
  3742. Alignment = 0;
  3743. };
  3744. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3745. unsigned Alignment;
  3746. if (IsCompressing)
  3747. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3748. else
  3749. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3750. SDValue Ptr = getValue(PtrOperand);
  3751. SDValue Src0 = getValue(Src0Operand);
  3752. SDValue Mask = getValue(MaskOperand);
  3753. EVT VT = Src0.getValueType();
  3754. if (!Alignment)
  3755. Alignment = DAG.getEVTAlignment(VT);
  3756. AAMDNodes AAInfo;
  3757. I.getAAMetadata(AAInfo);
  3758. MachineMemOperand *MMO =
  3759. DAG.getMachineFunction().
  3760. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3761. MachineMemOperand::MOStore, VT.getStoreSize(),
  3762. Alignment, AAInfo);
  3763. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3764. MMO, false /* Truncating */,
  3765. IsCompressing);
  3766. DAG.setRoot(StoreNode);
  3767. setValue(&I, StoreNode);
  3768. }
  3769. // Get a uniform base for the Gather/Scatter intrinsic.
  3770. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3771. // We try to represent it as a base pointer + vector of indices.
  3772. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3773. // The first operand of the GEP may be a single pointer or a vector of pointers
  3774. // Example:
  3775. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3776. // or
  3777. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3778. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3779. //
  3780. // When the first GEP operand is a single pointer - it is the uniform base we
  3781. // are looking for. If first operand of the GEP is a splat vector - we
  3782. // extract the splat value and use it as a uniform base.
  3783. // In all other cases the function returns 'false'.
  3784. static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
  3785. SDValue &Scale, SelectionDAGBuilder* SDB) {
  3786. SelectionDAG& DAG = SDB->DAG;
  3787. LLVMContext &Context = *DAG.getContext();
  3788. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3789. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3790. if (!GEP)
  3791. return false;
  3792. const Value *GEPPtr = GEP->getPointerOperand();
  3793. if (!GEPPtr->getType()->isVectorTy())
  3794. Ptr = GEPPtr;
  3795. else if (!(Ptr = getSplatValue(GEPPtr)))
  3796. return false;
  3797. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3798. Value *IndexVal = GEP->getOperand(FinalIndex);
  3799. // Ensure all the other indices are 0.
  3800. for (unsigned i = 1; i < FinalIndex; ++i) {
  3801. auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
  3802. if (!C || !C->isZero())
  3803. return false;
  3804. }
  3805. // The operands of the GEP may be defined in another basic block.
  3806. // In this case we'll not find nodes for the operands.
  3807. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3808. return false;
  3809. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3810. const DataLayout &DL = DAG.getDataLayout();
  3811. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3812. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3813. Base = SDB->getValue(Ptr);
  3814. Index = SDB->getValue(IndexVal);
  3815. if (!Index.getValueType().isVector()) {
  3816. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3817. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3818. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3819. }
  3820. return true;
  3821. }
  3822. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3823. SDLoc sdl = getCurSDLoc();
  3824. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3825. const Value *Ptr = I.getArgOperand(1);
  3826. SDValue Src0 = getValue(I.getArgOperand(0));
  3827. SDValue Mask = getValue(I.getArgOperand(3));
  3828. EVT VT = Src0.getValueType();
  3829. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3830. if (!Alignment)
  3831. Alignment = DAG.getEVTAlignment(VT);
  3832. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3833. AAMDNodes AAInfo;
  3834. I.getAAMetadata(AAInfo);
  3835. SDValue Base;
  3836. SDValue Index;
  3837. SDValue Scale;
  3838. const Value *BasePtr = Ptr;
  3839. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3840. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3841. MachineMemOperand *MMO = DAG.getMachineFunction().
  3842. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3843. MachineMemOperand::MOStore, VT.getStoreSize(),
  3844. Alignment, AAInfo);
  3845. if (!UniformBase) {
  3846. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3847. Index = getValue(Ptr);
  3848. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3849. }
  3850. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3851. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3852. Ops, MMO);
  3853. DAG.setRoot(Scatter);
  3854. setValue(&I, Scatter);
  3855. }
  3856. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3857. SDLoc sdl = getCurSDLoc();
  3858. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3859. unsigned& Alignment) {
  3860. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3861. Ptr = I.getArgOperand(0);
  3862. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3863. Mask = I.getArgOperand(2);
  3864. Src0 = I.getArgOperand(3);
  3865. };
  3866. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3867. unsigned& Alignment) {
  3868. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3869. Ptr = I.getArgOperand(0);
  3870. Alignment = 0;
  3871. Mask = I.getArgOperand(1);
  3872. Src0 = I.getArgOperand(2);
  3873. };
  3874. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3875. unsigned Alignment;
  3876. if (IsExpanding)
  3877. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3878. else
  3879. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3880. SDValue Ptr = getValue(PtrOperand);
  3881. SDValue Src0 = getValue(Src0Operand);
  3882. SDValue Mask = getValue(MaskOperand);
  3883. EVT VT = Src0.getValueType();
  3884. if (!Alignment)
  3885. Alignment = DAG.getEVTAlignment(VT);
  3886. AAMDNodes AAInfo;
  3887. I.getAAMetadata(AAInfo);
  3888. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3889. // Do not serialize masked loads of constant memory with anything.
  3890. bool AddToChain =
  3891. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3892. PtrOperand,
  3893. LocationSize::precise(
  3894. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3895. AAInfo));
  3896. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3897. MachineMemOperand *MMO =
  3898. DAG.getMachineFunction().
  3899. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3900. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3901. Alignment, AAInfo, Ranges);
  3902. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3903. ISD::NON_EXTLOAD, IsExpanding);
  3904. if (AddToChain)
  3905. PendingLoads.push_back(Load.getValue(1));
  3906. setValue(&I, Load);
  3907. }
  3908. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3909. SDLoc sdl = getCurSDLoc();
  3910. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3911. const Value *Ptr = I.getArgOperand(0);
  3912. SDValue Src0 = getValue(I.getArgOperand(3));
  3913. SDValue Mask = getValue(I.getArgOperand(2));
  3914. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3915. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3916. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3917. if (!Alignment)
  3918. Alignment = DAG.getEVTAlignment(VT);
  3919. AAMDNodes AAInfo;
  3920. I.getAAMetadata(AAInfo);
  3921. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3922. SDValue Root = DAG.getRoot();
  3923. SDValue Base;
  3924. SDValue Index;
  3925. SDValue Scale;
  3926. const Value *BasePtr = Ptr;
  3927. bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
  3928. bool ConstantMemory = false;
  3929. if (UniformBase && AA &&
  3930. AA->pointsToConstantMemory(
  3931. MemoryLocation(BasePtr,
  3932. LocationSize::precise(
  3933. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3934. AAInfo))) {
  3935. // Do not serialize (non-volatile) loads of constant memory with anything.
  3936. Root = DAG.getEntryNode();
  3937. ConstantMemory = true;
  3938. }
  3939. MachineMemOperand *MMO =
  3940. DAG.getMachineFunction().
  3941. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3942. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3943. Alignment, AAInfo, Ranges);
  3944. if (!UniformBase) {
  3945. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3946. Index = getValue(Ptr);
  3947. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3948. }
  3949. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3950. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3951. Ops, MMO);
  3952. SDValue OutChain = Gather.getValue(1);
  3953. if (!ConstantMemory)
  3954. PendingLoads.push_back(OutChain);
  3955. setValue(&I, Gather);
  3956. }
  3957. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3958. SDLoc dl = getCurSDLoc();
  3959. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3960. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3961. SyncScope::ID SSID = I.getSyncScopeID();
  3962. SDValue InChain = getRoot();
  3963. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3964. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3965. auto Alignment = DAG.getEVTAlignment(MemVT);
  3966. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3967. if (I.isVolatile())
  3968. Flags |= MachineMemOperand::MOVolatile;
  3969. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3970. MachineFunction &MF = DAG.getMachineFunction();
  3971. MachineMemOperand *MMO =
  3972. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3973. Flags, MemVT.getStoreSize(), Alignment,
  3974. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3975. FailureOrdering);
  3976. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3977. dl, MemVT, VTs, InChain,
  3978. getValue(I.getPointerOperand()),
  3979. getValue(I.getCompareOperand()),
  3980. getValue(I.getNewValOperand()), MMO);
  3981. SDValue OutChain = L.getValue(2);
  3982. setValue(&I, L);
  3983. DAG.setRoot(OutChain);
  3984. }
  3985. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3986. SDLoc dl = getCurSDLoc();
  3987. ISD::NodeType NT;
  3988. switch (I.getOperation()) {
  3989. default: llvm_unreachable("Unknown atomicrmw operation");
  3990. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3991. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3992. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3993. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3994. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3995. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3996. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3997. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3998. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3999. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  4000. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  4001. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  4002. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  4003. }
  4004. AtomicOrdering Ordering = I.getOrdering();
  4005. SyncScope::ID SSID = I.getSyncScopeID();
  4006. SDValue InChain = getRoot();
  4007. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  4008. auto Alignment = DAG.getEVTAlignment(MemVT);
  4009. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  4010. if (I.isVolatile())
  4011. Flags |= MachineMemOperand::MOVolatile;
  4012. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  4013. MachineFunction &MF = DAG.getMachineFunction();
  4014. MachineMemOperand *MMO =
  4015. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4016. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  4017. nullptr, SSID, Ordering);
  4018. SDValue L =
  4019. DAG.getAtomic(NT, dl, MemVT, InChain,
  4020. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  4021. MMO);
  4022. SDValue OutChain = L.getValue(1);
  4023. setValue(&I, L);
  4024. DAG.setRoot(OutChain);
  4025. }
  4026. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4027. SDLoc dl = getCurSDLoc();
  4028. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4029. SDValue Ops[3];
  4030. Ops[0] = getRoot();
  4031. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  4032. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4033. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  4034. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4035. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  4036. }
  4037. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4038. SDLoc dl = getCurSDLoc();
  4039. AtomicOrdering Order = I.getOrdering();
  4040. SyncScope::ID SSID = I.getSyncScopeID();
  4041. SDValue InChain = getRoot();
  4042. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4043. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4044. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4045. if (!TLI.supportsUnalignedAtomics() &&
  4046. I.getAlignment() < MemVT.getSizeInBits() / 8)
  4047. report_fatal_error("Cannot generate unaligned atomic load");
  4048. auto Flags = MachineMemOperand::MOLoad;
  4049. if (I.isVolatile())
  4050. Flags |= MachineMemOperand::MOVolatile;
  4051. if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
  4052. Flags |= MachineMemOperand::MOInvariant;
  4053. if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
  4054. Flags |= MachineMemOperand::MODereferenceable;
  4055. Flags |= TLI.getMMOFlags(I);
  4056. MachineMemOperand *MMO =
  4057. DAG.getMachineFunction().
  4058. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  4059. Flags, MemVT.getStoreSize(),
  4060. I.getAlignment() ? I.getAlignment() :
  4061. DAG.getEVTAlignment(MemVT),
  4062. AAMDNodes(), nullptr, SSID, Order);
  4063. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4064. SDValue L =
  4065. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4066. getValue(I.getPointerOperand()), MMO);
  4067. SDValue OutChain = L.getValue(1);
  4068. if (MemVT != VT)
  4069. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4070. setValue(&I, L);
  4071. DAG.setRoot(OutChain);
  4072. }
  4073. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4074. SDLoc dl = getCurSDLoc();
  4075. AtomicOrdering Ordering = I.getOrdering();
  4076. SyncScope::ID SSID = I.getSyncScopeID();
  4077. SDValue InChain = getRoot();
  4078. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4079. EVT MemVT =
  4080. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4081. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4082. report_fatal_error("Cannot generate unaligned atomic store");
  4083. auto Flags = MachineMemOperand::MOStore;
  4084. if (I.isVolatile())
  4085. Flags |= MachineMemOperand::MOVolatile;
  4086. Flags |= TLI.getMMOFlags(I);
  4087. MachineFunction &MF = DAG.getMachineFunction();
  4088. MachineMemOperand *MMO =
  4089. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4090. MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4091. nullptr, SSID, Ordering);
  4092. SDValue Val = getValue(I.getValueOperand());
  4093. if (Val.getValueType() != MemVT)
  4094. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4095. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4096. getValue(I.getPointerOperand()), Val, MMO);
  4097. DAG.setRoot(OutChain);
  4098. }
  4099. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4100. /// node.
  4101. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4102. unsigned Intrinsic) {
  4103. // Ignore the callsite's attributes. A specific call site may be marked with
  4104. // readnone, but the lowering code will expect the chain based on the
  4105. // definition.
  4106. const Function *F = I.getCalledFunction();
  4107. bool HasChain = !F->doesNotAccessMemory();
  4108. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4109. // Build the operand list.
  4110. SmallVector<SDValue, 8> Ops;
  4111. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4112. if (OnlyLoad) {
  4113. // We don't need to serialize loads against other loads.
  4114. Ops.push_back(DAG.getRoot());
  4115. } else {
  4116. Ops.push_back(getRoot());
  4117. }
  4118. }
  4119. // Info is set by getTgtMemInstrinsic
  4120. TargetLowering::IntrinsicInfo Info;
  4121. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4122. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4123. DAG.getMachineFunction(),
  4124. Intrinsic);
  4125. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4126. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4127. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4128. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4129. TLI.getPointerTy(DAG.getDataLayout())));
  4130. // Add all operands of the call to the operand list.
  4131. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4132. SDValue Op = getValue(I.getArgOperand(i));
  4133. Ops.push_back(Op);
  4134. }
  4135. SmallVector<EVT, 4> ValueVTs;
  4136. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4137. if (HasChain)
  4138. ValueVTs.push_back(MVT::Other);
  4139. SDVTList VTs = DAG.getVTList(ValueVTs);
  4140. // Create the node.
  4141. SDValue Result;
  4142. if (IsTgtIntrinsic) {
  4143. // This is target intrinsic that touches memory
  4144. Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
  4145. Ops, Info.memVT,
  4146. MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
  4147. Info.flags, Info.size);
  4148. } else if (!HasChain) {
  4149. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4150. } else if (!I.getType()->isVoidTy()) {
  4151. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4152. } else {
  4153. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4154. }
  4155. if (HasChain) {
  4156. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4157. if (OnlyLoad)
  4158. PendingLoads.push_back(Chain);
  4159. else
  4160. DAG.setRoot(Chain);
  4161. }
  4162. if (!I.getType()->isVoidTy()) {
  4163. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4164. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4165. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4166. } else
  4167. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4168. setValue(&I, Result);
  4169. }
  4170. }
  4171. /// GetSignificand - Get the significand and build it into a floating-point
  4172. /// number with exponent of 1:
  4173. ///
  4174. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4175. ///
  4176. /// where Op is the hexadecimal representation of floating point value.
  4177. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4178. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4179. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4180. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4181. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4182. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4183. }
  4184. /// GetExponent - Get the exponent:
  4185. ///
  4186. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4187. ///
  4188. /// where Op is the hexadecimal representation of floating point value.
  4189. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4190. const TargetLowering &TLI, const SDLoc &dl) {
  4191. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4192. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4193. SDValue t1 = DAG.getNode(
  4194. ISD::SRL, dl, MVT::i32, t0,
  4195. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4196. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4197. DAG.getConstant(127, dl, MVT::i32));
  4198. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4199. }
  4200. /// getF32Constant - Get 32-bit floating point constant.
  4201. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4202. const SDLoc &dl) {
  4203. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4204. MVT::f32);
  4205. }
  4206. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4207. SelectionDAG &DAG) {
  4208. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4209. // IntegerPartOfX = ((int32_t)(t0);
  4210. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4211. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4212. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4213. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4214. // IntegerPartOfX <<= 23;
  4215. IntegerPartOfX = DAG.getNode(
  4216. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4217. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4218. DAG.getDataLayout())));
  4219. SDValue TwoToFractionalPartOfX;
  4220. if (LimitFloatPrecision <= 6) {
  4221. // For floating-point precision of 6:
  4222. //
  4223. // TwoToFractionalPartOfX =
  4224. // 0.997535578f +
  4225. // (0.735607626f + 0.252464424f * x) * x;
  4226. //
  4227. // error 0.0144103317, which is 6 bits
  4228. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4229. getF32Constant(DAG, 0x3e814304, dl));
  4230. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4231. getF32Constant(DAG, 0x3f3c50c8, dl));
  4232. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4233. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4234. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4235. } else if (LimitFloatPrecision <= 12) {
  4236. // For floating-point precision of 12:
  4237. //
  4238. // TwoToFractionalPartOfX =
  4239. // 0.999892986f +
  4240. // (0.696457318f +
  4241. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4242. //
  4243. // error 0.000107046256, which is 13 to 14 bits
  4244. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4245. getF32Constant(DAG, 0x3da235e3, dl));
  4246. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4247. getF32Constant(DAG, 0x3e65b8f3, dl));
  4248. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4249. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4250. getF32Constant(DAG, 0x3f324b07, dl));
  4251. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4252. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4253. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4254. } else { // LimitFloatPrecision <= 18
  4255. // For floating-point precision of 18:
  4256. //
  4257. // TwoToFractionalPartOfX =
  4258. // 0.999999982f +
  4259. // (0.693148872f +
  4260. // (0.240227044f +
  4261. // (0.554906021e-1f +
  4262. // (0.961591928e-2f +
  4263. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4264. // error 2.47208000*10^(-7), which is better than 18 bits
  4265. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4266. getF32Constant(DAG, 0x3924b03e, dl));
  4267. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4268. getF32Constant(DAG, 0x3ab24b87, dl));
  4269. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4270. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4271. getF32Constant(DAG, 0x3c1d8c17, dl));
  4272. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4273. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4274. getF32Constant(DAG, 0x3d634a1d, dl));
  4275. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4276. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4277. getF32Constant(DAG, 0x3e75fe14, dl));
  4278. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4279. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4280. getF32Constant(DAG, 0x3f317234, dl));
  4281. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4282. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4283. getF32Constant(DAG, 0x3f800000, dl));
  4284. }
  4285. // Add the exponent into the result in integer domain.
  4286. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4287. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4288. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4289. }
  4290. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4291. /// limited-precision mode.
  4292. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4293. const TargetLowering &TLI) {
  4294. if (Op.getValueType() == MVT::f32 &&
  4295. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4296. // Put the exponent in the right bit position for later addition to the
  4297. // final result:
  4298. //
  4299. // #define LOG2OFe 1.4426950f
  4300. // t0 = Op * LOG2OFe
  4301. // TODO: What fast-math-flags should be set here?
  4302. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4303. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4304. return getLimitedPrecisionExp2(t0, dl, DAG);
  4305. }
  4306. // No special expansion.
  4307. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4308. }
  4309. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4310. /// limited-precision mode.
  4311. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4312. const TargetLowering &TLI) {
  4313. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4314. if (Op.getValueType() == MVT::f32 &&
  4315. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4316. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4317. // Scale the exponent by log(2) [0.69314718f].
  4318. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4319. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4320. getF32Constant(DAG, 0x3f317218, dl));
  4321. // Get the significand and build it into a floating-point number with
  4322. // exponent of 1.
  4323. SDValue X = GetSignificand(DAG, Op1, dl);
  4324. SDValue LogOfMantissa;
  4325. if (LimitFloatPrecision <= 6) {
  4326. // For floating-point precision of 6:
  4327. //
  4328. // LogofMantissa =
  4329. // -1.1609546f +
  4330. // (1.4034025f - 0.23903021f * x) * x;
  4331. //
  4332. // error 0.0034276066, which is better than 8 bits
  4333. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4334. getF32Constant(DAG, 0xbe74c456, dl));
  4335. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4336. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4337. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4338. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4339. getF32Constant(DAG, 0x3f949a29, dl));
  4340. } else if (LimitFloatPrecision <= 12) {
  4341. // For floating-point precision of 12:
  4342. //
  4343. // LogOfMantissa =
  4344. // -1.7417939f +
  4345. // (2.8212026f +
  4346. // (-1.4699568f +
  4347. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4348. //
  4349. // error 0.000061011436, which is 14 bits
  4350. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4351. getF32Constant(DAG, 0xbd67b6d6, dl));
  4352. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4353. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4354. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4355. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4356. getF32Constant(DAG, 0x3fbc278b, dl));
  4357. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4358. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4359. getF32Constant(DAG, 0x40348e95, dl));
  4360. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4361. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4362. getF32Constant(DAG, 0x3fdef31a, dl));
  4363. } else { // LimitFloatPrecision <= 18
  4364. // For floating-point precision of 18:
  4365. //
  4366. // LogOfMantissa =
  4367. // -2.1072184f +
  4368. // (4.2372794f +
  4369. // (-3.7029485f +
  4370. // (2.2781945f +
  4371. // (-0.87823314f +
  4372. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4373. //
  4374. // error 0.0000023660568, which is better than 18 bits
  4375. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4376. getF32Constant(DAG, 0xbc91e5ac, dl));
  4377. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4378. getF32Constant(DAG, 0x3e4350aa, dl));
  4379. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4380. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4381. getF32Constant(DAG, 0x3f60d3e3, dl));
  4382. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4383. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4384. getF32Constant(DAG, 0x4011cdf0, dl));
  4385. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4386. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4387. getF32Constant(DAG, 0x406cfd1c, dl));
  4388. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4389. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4390. getF32Constant(DAG, 0x408797cb, dl));
  4391. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4392. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4393. getF32Constant(DAG, 0x4006dcab, dl));
  4394. }
  4395. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4396. }
  4397. // No special expansion.
  4398. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4399. }
  4400. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4401. /// limited-precision mode.
  4402. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4403. const TargetLowering &TLI) {
  4404. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4405. if (Op.getValueType() == MVT::f32 &&
  4406. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4407. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4408. // Get the exponent.
  4409. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4410. // Get the significand and build it into a floating-point number with
  4411. // exponent of 1.
  4412. SDValue X = GetSignificand(DAG, Op1, dl);
  4413. // Different possible minimax approximations of significand in
  4414. // floating-point for various degrees of accuracy over [1,2].
  4415. SDValue Log2ofMantissa;
  4416. if (LimitFloatPrecision <= 6) {
  4417. // For floating-point precision of 6:
  4418. //
  4419. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4420. //
  4421. // error 0.0049451742, which is more than 7 bits
  4422. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4423. getF32Constant(DAG, 0xbeb08fe0, dl));
  4424. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4425. getF32Constant(DAG, 0x40019463, dl));
  4426. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4427. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4428. getF32Constant(DAG, 0x3fd6633d, dl));
  4429. } else if (LimitFloatPrecision <= 12) {
  4430. // For floating-point precision of 12:
  4431. //
  4432. // Log2ofMantissa =
  4433. // -2.51285454f +
  4434. // (4.07009056f +
  4435. // (-2.12067489f +
  4436. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4437. //
  4438. // error 0.0000876136000, which is better than 13 bits
  4439. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4440. getF32Constant(DAG, 0xbda7262e, dl));
  4441. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4442. getF32Constant(DAG, 0x3f25280b, dl));
  4443. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4444. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4445. getF32Constant(DAG, 0x4007b923, dl));
  4446. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4447. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4448. getF32Constant(DAG, 0x40823e2f, dl));
  4449. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4450. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4451. getF32Constant(DAG, 0x4020d29c, dl));
  4452. } else { // LimitFloatPrecision <= 18
  4453. // For floating-point precision of 18:
  4454. //
  4455. // Log2ofMantissa =
  4456. // -3.0400495f +
  4457. // (6.1129976f +
  4458. // (-5.3420409f +
  4459. // (3.2865683f +
  4460. // (-1.2669343f +
  4461. // (0.27515199f -
  4462. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4463. //
  4464. // error 0.0000018516, which is better than 18 bits
  4465. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4466. getF32Constant(DAG, 0xbcd2769e, dl));
  4467. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4468. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4469. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4470. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4471. getF32Constant(DAG, 0x3fa22ae7, dl));
  4472. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4473. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4474. getF32Constant(DAG, 0x40525723, dl));
  4475. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4476. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4477. getF32Constant(DAG, 0x40aaf200, dl));
  4478. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4479. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4480. getF32Constant(DAG, 0x40c39dad, dl));
  4481. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4482. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4483. getF32Constant(DAG, 0x4042902c, dl));
  4484. }
  4485. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4486. }
  4487. // No special expansion.
  4488. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4489. }
  4490. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4491. /// limited-precision mode.
  4492. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4493. const TargetLowering &TLI) {
  4494. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4495. if (Op.getValueType() == MVT::f32 &&
  4496. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4497. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4498. // Scale the exponent by log10(2) [0.30102999f].
  4499. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4500. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4501. getF32Constant(DAG, 0x3e9a209a, dl));
  4502. // Get the significand and build it into a floating-point number with
  4503. // exponent of 1.
  4504. SDValue X = GetSignificand(DAG, Op1, dl);
  4505. SDValue Log10ofMantissa;
  4506. if (LimitFloatPrecision <= 6) {
  4507. // For floating-point precision of 6:
  4508. //
  4509. // Log10ofMantissa =
  4510. // -0.50419619f +
  4511. // (0.60948995f - 0.10380950f * x) * x;
  4512. //
  4513. // error 0.0014886165, which is 6 bits
  4514. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4515. getF32Constant(DAG, 0xbdd49a13, dl));
  4516. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4517. getF32Constant(DAG, 0x3f1c0789, dl));
  4518. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4519. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4520. getF32Constant(DAG, 0x3f011300, dl));
  4521. } else if (LimitFloatPrecision <= 12) {
  4522. // For floating-point precision of 12:
  4523. //
  4524. // Log10ofMantissa =
  4525. // -0.64831180f +
  4526. // (0.91751397f +
  4527. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4528. //
  4529. // error 0.00019228036, which is better than 12 bits
  4530. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4531. getF32Constant(DAG, 0x3d431f31, dl));
  4532. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4533. getF32Constant(DAG, 0x3ea21fb2, dl));
  4534. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4535. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4536. getF32Constant(DAG, 0x3f6ae232, dl));
  4537. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4538. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4539. getF32Constant(DAG, 0x3f25f7c3, dl));
  4540. } else { // LimitFloatPrecision <= 18
  4541. // For floating-point precision of 18:
  4542. //
  4543. // Log10ofMantissa =
  4544. // -0.84299375f +
  4545. // (1.5327582f +
  4546. // (-1.0688956f +
  4547. // (0.49102474f +
  4548. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4549. //
  4550. // error 0.0000037995730, which is better than 18 bits
  4551. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4552. getF32Constant(DAG, 0x3c5d51ce, dl));
  4553. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4554. getF32Constant(DAG, 0x3e00685a, dl));
  4555. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4556. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4557. getF32Constant(DAG, 0x3efb6798, dl));
  4558. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4559. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4560. getF32Constant(DAG, 0x3f88d192, dl));
  4561. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4562. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4563. getF32Constant(DAG, 0x3fc4316c, dl));
  4564. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4565. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4566. getF32Constant(DAG, 0x3f57ce70, dl));
  4567. }
  4568. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4569. }
  4570. // No special expansion.
  4571. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4572. }
  4573. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4574. /// limited-precision mode.
  4575. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4576. const TargetLowering &TLI) {
  4577. if (Op.getValueType() == MVT::f32 &&
  4578. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4579. return getLimitedPrecisionExp2(Op, dl, DAG);
  4580. // No special expansion.
  4581. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4582. }
  4583. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4584. /// limited-precision mode with x == 10.0f.
  4585. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4586. SelectionDAG &DAG, const TargetLowering &TLI) {
  4587. bool IsExp10 = false;
  4588. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4589. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4590. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4591. APFloat Ten(10.0f);
  4592. IsExp10 = LHSC->isExactlyValue(Ten);
  4593. }
  4594. }
  4595. // TODO: What fast-math-flags should be set on the FMUL node?
  4596. if (IsExp10) {
  4597. // Put the exponent in the right bit position for later addition to the
  4598. // final result:
  4599. //
  4600. // #define LOG2OF10 3.3219281f
  4601. // t0 = Op * LOG2OF10;
  4602. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4603. getF32Constant(DAG, 0x40549a78, dl));
  4604. return getLimitedPrecisionExp2(t0, dl, DAG);
  4605. }
  4606. // No special expansion.
  4607. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4608. }
  4609. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4610. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4611. SelectionDAG &DAG) {
  4612. // If RHS is a constant, we can expand this out to a multiplication tree,
  4613. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4614. // optimizing for size, we only want to do this if the expansion would produce
  4615. // a small number of multiplies, otherwise we do the full expansion.
  4616. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4617. // Get the exponent as a positive value.
  4618. unsigned Val = RHSC->getSExtValue();
  4619. if ((int)Val < 0) Val = -Val;
  4620. // powi(x, 0) -> 1.0
  4621. if (Val == 0)
  4622. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4623. const Function &F = DAG.getMachineFunction().getFunction();
  4624. if (!F.hasOptSize() ||
  4625. // If optimizing for size, don't insert too many multiplies.
  4626. // This inserts up to 5 multiplies.
  4627. countPopulation(Val) + Log2_32(Val) < 7) {
  4628. // We use the simple binary decomposition method to generate the multiply
  4629. // sequence. There are more optimal ways to do this (for example,
  4630. // powi(x,15) generates one more multiply than it should), but this has
  4631. // the benefit of being both really simple and much better than a libcall.
  4632. SDValue Res; // Logically starts equal to 1.0
  4633. SDValue CurSquare = LHS;
  4634. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4635. // nodes.
  4636. while (Val) {
  4637. if (Val & 1) {
  4638. if (Res.getNode())
  4639. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4640. else
  4641. Res = CurSquare; // 1.0*CurSquare.
  4642. }
  4643. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4644. CurSquare, CurSquare);
  4645. Val >>= 1;
  4646. }
  4647. // If the original was negative, invert the result, producing 1/(x*x*x).
  4648. if (RHSC->getSExtValue() < 0)
  4649. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4650. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4651. return Res;
  4652. }
  4653. }
  4654. // Otherwise, expand to a libcall.
  4655. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4656. }
  4657. // getUnderlyingArgReg - Find underlying register used for a truncated or
  4658. // bitcasted argument.
  4659. static unsigned getUnderlyingArgReg(const SDValue &N) {
  4660. switch (N.getOpcode()) {
  4661. case ISD::CopyFromReg:
  4662. return cast<RegisterSDNode>(N.getOperand(1))->getReg();
  4663. case ISD::BITCAST:
  4664. case ISD::AssertZext:
  4665. case ISD::AssertSext:
  4666. case ISD::TRUNCATE:
  4667. return getUnderlyingArgReg(N.getOperand(0));
  4668. default:
  4669. return 0;
  4670. }
  4671. }
  4672. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4673. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4674. /// instruction selection, they will be inserted to the entry BB.
  4675. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4676. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4677. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4678. const Argument *Arg = dyn_cast<Argument>(V);
  4679. if (!Arg)
  4680. return false;
  4681. if (!IsDbgDeclare) {
  4682. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4683. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4684. // the entry block.
  4685. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4686. if (!IsInEntryBlock)
  4687. return false;
  4688. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4689. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4690. // variable that also is a param.
  4691. //
  4692. // Although, if we are at the top of the entry block already, we can still
  4693. // emit using ArgDbgValue. This might catch some situations when the
  4694. // dbg.value refers to an argument that isn't used in the entry block, so
  4695. // any CopyToReg node would be optimized out and the only way to express
  4696. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4697. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4698. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4699. // current function, and the dbg.value intrinsic is found in the entry
  4700. // block.
  4701. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4702. !DL->getInlinedAt();
  4703. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4704. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4705. return false;
  4706. // Here we assume that a function argument on IR level only can be used to
  4707. // describe one input parameter on source level. If we for example have
  4708. // source code like this
  4709. //
  4710. // struct A { long x, y; };
  4711. // void foo(struct A a, long b) {
  4712. // ...
  4713. // b = a.x;
  4714. // ...
  4715. // }
  4716. //
  4717. // and IR like this
  4718. //
  4719. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4720. // entry:
  4721. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4722. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4723. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4724. // ...
  4725. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4726. // ...
  4727. //
  4728. // then the last dbg.value is describing a parameter "b" using a value that
  4729. // is an argument. But since we already has used %a1 to describe a parameter
  4730. // we should not handle that last dbg.value here (that would result in an
  4731. // incorrect hoisting of the DBG_VALUE to the function entry).
  4732. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4733. // for the situation with fragments above.
  4734. if (VariableIsFunctionInputArg) {
  4735. unsigned ArgNo = Arg->getArgNo();
  4736. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4737. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4738. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4739. return false;
  4740. FuncInfo.DescribedArgs.set(ArgNo);
  4741. }
  4742. }
  4743. MachineFunction &MF = DAG.getMachineFunction();
  4744. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4745. bool IsIndirect = false;
  4746. Optional<MachineOperand> Op;
  4747. // Some arguments' frame index is recorded during argument lowering.
  4748. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4749. if (FI != std::numeric_limits<int>::max())
  4750. Op = MachineOperand::CreateFI(FI);
  4751. if (!Op && N.getNode()) {
  4752. unsigned Reg = getUnderlyingArgReg(N);
  4753. if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
  4754. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4755. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  4756. if (PR)
  4757. Reg = PR;
  4758. }
  4759. if (Reg) {
  4760. Op = MachineOperand::CreateReg(Reg, false);
  4761. IsIndirect = IsDbgDeclare;
  4762. }
  4763. }
  4764. if (!Op && N.getNode()) {
  4765. // Check if frame index is available.
  4766. SDValue LCandidate = peekThroughBitcasts(N);
  4767. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4768. if (FrameIndexSDNode *FINode =
  4769. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4770. Op = MachineOperand::CreateFI(FINode->getIndex());
  4771. }
  4772. if (!Op) {
  4773. // Check if ValueMap has reg number.
  4774. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  4775. if (VMI != FuncInfo.ValueMap.end()) {
  4776. const auto &TLI = DAG.getTargetLoweringInfo();
  4777. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4778. V->getType(), getABIRegCopyCC(V));
  4779. if (RFV.occupiesMultipleRegs()) {
  4780. unsigned Offset = 0;
  4781. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  4782. Op = MachineOperand::CreateReg(RegAndSize.first, false);
  4783. auto FragmentExpr = DIExpression::createFragmentExpression(
  4784. Expr, Offset, RegAndSize.second);
  4785. if (!FragmentExpr)
  4786. continue;
  4787. FuncInfo.ArgDbgValues.push_back(
  4788. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4789. Op->getReg(), Variable, *FragmentExpr));
  4790. Offset += RegAndSize.second;
  4791. }
  4792. return true;
  4793. }
  4794. Op = MachineOperand::CreateReg(VMI->second, false);
  4795. IsIndirect = IsDbgDeclare;
  4796. }
  4797. }
  4798. if (!Op)
  4799. return false;
  4800. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4801. "Expected inlined-at fields to agree");
  4802. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4803. FuncInfo.ArgDbgValues.push_back(
  4804. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4805. *Op, Variable, Expr));
  4806. return true;
  4807. }
  4808. /// Return the appropriate SDDbgValue based on N.
  4809. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4810. DILocalVariable *Variable,
  4811. DIExpression *Expr,
  4812. const DebugLoc &dl,
  4813. unsigned DbgSDNodeOrder) {
  4814. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4815. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4816. // stack slot locations.
  4817. //
  4818. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4819. // debug values here after optimization:
  4820. //
  4821. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4822. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4823. //
  4824. // Both describe the direct values of their associated variables.
  4825. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4826. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4827. }
  4828. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4829. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4830. }
  4831. // VisualStudio defines setjmp as _setjmp
  4832. #if defined(_MSC_VER) && defined(setjmp) && \
  4833. !defined(setjmp_undefined_for_msvc)
  4834. # pragma push_macro("setjmp")
  4835. # undef setjmp
  4836. # define setjmp_undefined_for_msvc
  4837. #endif
  4838. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4839. switch (Intrinsic) {
  4840. case Intrinsic::smul_fix:
  4841. return ISD::SMULFIX;
  4842. case Intrinsic::umul_fix:
  4843. return ISD::UMULFIX;
  4844. default:
  4845. llvm_unreachable("Unhandled fixed point intrinsic");
  4846. }
  4847. }
  4848. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  4849. const char *FunctionName) {
  4850. assert(FunctionName && "FunctionName must not be nullptr");
  4851. SDValue Callee = DAG.getExternalSymbol(
  4852. FunctionName,
  4853. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  4854. LowerCallTo(&I, Callee, I.isTailCall());
  4855. }
  4856. /// Lower the call to the specified intrinsic function.
  4857. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  4858. unsigned Intrinsic) {
  4859. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4860. SDLoc sdl = getCurSDLoc();
  4861. DebugLoc dl = getCurDebugLoc();
  4862. SDValue Res;
  4863. switch (Intrinsic) {
  4864. default:
  4865. // By default, turn this into a target intrinsic node.
  4866. visitTargetIntrinsic(I, Intrinsic);
  4867. return;
  4868. case Intrinsic::vastart: visitVAStart(I); return;
  4869. case Intrinsic::vaend: visitVAEnd(I); return;
  4870. case Intrinsic::vacopy: visitVACopy(I); return;
  4871. case Intrinsic::returnaddress:
  4872. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4873. TLI.getPointerTy(DAG.getDataLayout()),
  4874. getValue(I.getArgOperand(0))));
  4875. return;
  4876. case Intrinsic::addressofreturnaddress:
  4877. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4878. TLI.getPointerTy(DAG.getDataLayout())));
  4879. return;
  4880. case Intrinsic::sponentry:
  4881. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4882. TLI.getPointerTy(DAG.getDataLayout())));
  4883. return;
  4884. case Intrinsic::frameaddress:
  4885. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4886. TLI.getPointerTy(DAG.getDataLayout()),
  4887. getValue(I.getArgOperand(0))));
  4888. return;
  4889. case Intrinsic::read_register: {
  4890. Value *Reg = I.getArgOperand(0);
  4891. SDValue Chain = getRoot();
  4892. SDValue RegName =
  4893. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4894. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4895. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4896. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4897. setValue(&I, Res);
  4898. DAG.setRoot(Res.getValue(1));
  4899. return;
  4900. }
  4901. case Intrinsic::write_register: {
  4902. Value *Reg = I.getArgOperand(0);
  4903. Value *RegValue = I.getArgOperand(1);
  4904. SDValue Chain = getRoot();
  4905. SDValue RegName =
  4906. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4907. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4908. RegName, getValue(RegValue)));
  4909. return;
  4910. }
  4911. case Intrinsic::setjmp:
  4912. lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
  4913. return;
  4914. case Intrinsic::longjmp:
  4915. lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
  4916. return;
  4917. case Intrinsic::memcpy: {
  4918. const auto &MCI = cast<MemCpyInst>(I);
  4919. SDValue Op1 = getValue(I.getArgOperand(0));
  4920. SDValue Op2 = getValue(I.getArgOperand(1));
  4921. SDValue Op3 = getValue(I.getArgOperand(2));
  4922. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4923. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4924. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4925. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4926. bool isVol = MCI.isVolatile();
  4927. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4928. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4929. // node.
  4930. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4931. false, isTC,
  4932. MachinePointerInfo(I.getArgOperand(0)),
  4933. MachinePointerInfo(I.getArgOperand(1)));
  4934. updateDAGForMaybeTailCall(MC);
  4935. return;
  4936. }
  4937. case Intrinsic::memset: {
  4938. const auto &MSI = cast<MemSetInst>(I);
  4939. SDValue Op1 = getValue(I.getArgOperand(0));
  4940. SDValue Op2 = getValue(I.getArgOperand(1));
  4941. SDValue Op3 = getValue(I.getArgOperand(2));
  4942. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4943. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4944. bool isVol = MSI.isVolatile();
  4945. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4946. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4947. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4948. updateDAGForMaybeTailCall(MS);
  4949. return;
  4950. }
  4951. case Intrinsic::memmove: {
  4952. const auto &MMI = cast<MemMoveInst>(I);
  4953. SDValue Op1 = getValue(I.getArgOperand(0));
  4954. SDValue Op2 = getValue(I.getArgOperand(1));
  4955. SDValue Op3 = getValue(I.getArgOperand(2));
  4956. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4957. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4958. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4959. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4960. bool isVol = MMI.isVolatile();
  4961. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4962. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4963. // node.
  4964. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4965. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4966. MachinePointerInfo(I.getArgOperand(1)));
  4967. updateDAGForMaybeTailCall(MM);
  4968. return;
  4969. }
  4970. case Intrinsic::memcpy_element_unordered_atomic: {
  4971. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4972. SDValue Dst = getValue(MI.getRawDest());
  4973. SDValue Src = getValue(MI.getRawSource());
  4974. SDValue Length = getValue(MI.getLength());
  4975. unsigned DstAlign = MI.getDestAlignment();
  4976. unsigned SrcAlign = MI.getSourceAlignment();
  4977. Type *LengthTy = MI.getLength()->getType();
  4978. unsigned ElemSz = MI.getElementSizeInBytes();
  4979. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4980. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4981. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4982. MachinePointerInfo(MI.getRawDest()),
  4983. MachinePointerInfo(MI.getRawSource()));
  4984. updateDAGForMaybeTailCall(MC);
  4985. return;
  4986. }
  4987. case Intrinsic::memmove_element_unordered_atomic: {
  4988. auto &MI = cast<AtomicMemMoveInst>(I);
  4989. SDValue Dst = getValue(MI.getRawDest());
  4990. SDValue Src = getValue(MI.getRawSource());
  4991. SDValue Length = getValue(MI.getLength());
  4992. unsigned DstAlign = MI.getDestAlignment();
  4993. unsigned SrcAlign = MI.getSourceAlignment();
  4994. Type *LengthTy = MI.getLength()->getType();
  4995. unsigned ElemSz = MI.getElementSizeInBytes();
  4996. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4997. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  4998. SrcAlign, Length, LengthTy, ElemSz, isTC,
  4999. MachinePointerInfo(MI.getRawDest()),
  5000. MachinePointerInfo(MI.getRawSource()));
  5001. updateDAGForMaybeTailCall(MC);
  5002. return;
  5003. }
  5004. case Intrinsic::memset_element_unordered_atomic: {
  5005. auto &MI = cast<AtomicMemSetInst>(I);
  5006. SDValue Dst = getValue(MI.getRawDest());
  5007. SDValue Val = getValue(MI.getValue());
  5008. SDValue Length = getValue(MI.getLength());
  5009. unsigned DstAlign = MI.getDestAlignment();
  5010. Type *LengthTy = MI.getLength()->getType();
  5011. unsigned ElemSz = MI.getElementSizeInBytes();
  5012. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5013. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  5014. LengthTy, ElemSz, isTC,
  5015. MachinePointerInfo(MI.getRawDest()));
  5016. updateDAGForMaybeTailCall(MC);
  5017. return;
  5018. }
  5019. case Intrinsic::dbg_addr:
  5020. case Intrinsic::dbg_declare: {
  5021. const auto &DI = cast<DbgVariableIntrinsic>(I);
  5022. DILocalVariable *Variable = DI.getVariable();
  5023. DIExpression *Expression = DI.getExpression();
  5024. dropDanglingDebugInfo(Variable, Expression);
  5025. assert(Variable && "Missing variable");
  5026. // Check if address has undef value.
  5027. const Value *Address = DI.getVariableLocation();
  5028. if (!Address || isa<UndefValue>(Address) ||
  5029. (Address->use_empty() && !isa<Argument>(Address))) {
  5030. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5031. return;
  5032. }
  5033. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5034. // Check if this variable can be described by a frame index, typically
  5035. // either as a static alloca or a byval parameter.
  5036. int FI = std::numeric_limits<int>::max();
  5037. if (const auto *AI =
  5038. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5039. if (AI->isStaticAlloca()) {
  5040. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5041. if (I != FuncInfo.StaticAllocaMap.end())
  5042. FI = I->second;
  5043. }
  5044. } else if (const auto *Arg = dyn_cast<Argument>(
  5045. Address->stripInBoundsConstantOffsets())) {
  5046. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5047. }
  5048. // llvm.dbg.addr is control dependent and always generates indirect
  5049. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5050. // the MachineFunction variable table.
  5051. if (FI != std::numeric_limits<int>::max()) {
  5052. if (Intrinsic == Intrinsic::dbg_addr) {
  5053. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5054. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  5055. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  5056. }
  5057. return;
  5058. }
  5059. SDValue &N = NodeMap[Address];
  5060. if (!N.getNode() && isa<Argument>(Address))
  5061. // Check unused arguments map.
  5062. N = UnusedArgNodeMap[Address];
  5063. SDDbgValue *SDV;
  5064. if (N.getNode()) {
  5065. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5066. Address = BCI->getOperand(0);
  5067. // Parameters are handled specially.
  5068. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5069. if (isParameter && FINode) {
  5070. // Byval parameter. We have a frame index at this point.
  5071. SDV =
  5072. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5073. /*IsIndirect*/ true, dl, SDNodeOrder);
  5074. } else if (isa<Argument>(Address)) {
  5075. // Address is an argument, so try to emit its dbg value using
  5076. // virtual register info from the FuncInfo.ValueMap.
  5077. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5078. return;
  5079. } else {
  5080. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5081. true, dl, SDNodeOrder);
  5082. }
  5083. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5084. } else {
  5085. // If Address is an argument then try to emit its dbg value using
  5086. // virtual register info from the FuncInfo.ValueMap.
  5087. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5088. N)) {
  5089. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5090. }
  5091. }
  5092. return;
  5093. }
  5094. case Intrinsic::dbg_label: {
  5095. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5096. DILabel *Label = DI.getLabel();
  5097. assert(Label && "Missing label");
  5098. SDDbgLabel *SDV;
  5099. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5100. DAG.AddDbgLabel(SDV);
  5101. return;
  5102. }
  5103. case Intrinsic::dbg_value: {
  5104. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5105. assert(DI.getVariable() && "Missing variable");
  5106. DILocalVariable *Variable = DI.getVariable();
  5107. DIExpression *Expression = DI.getExpression();
  5108. dropDanglingDebugInfo(Variable, Expression);
  5109. const Value *V = DI.getValue();
  5110. if (!V)
  5111. return;
  5112. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5113. SDNodeOrder))
  5114. return;
  5115. // TODO: Dangling debug info will eventually either be resolved or produce
  5116. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5117. // between the original dbg.value location and its resolved DBG_VALUE, which
  5118. // we should ideally fill with an extra Undef DBG_VALUE.
  5119. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5120. return;
  5121. }
  5122. case Intrinsic::eh_typeid_for: {
  5123. // Find the type id for the given typeinfo.
  5124. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5125. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5126. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5127. setValue(&I, Res);
  5128. return;
  5129. }
  5130. case Intrinsic::eh_return_i32:
  5131. case Intrinsic::eh_return_i64:
  5132. DAG.getMachineFunction().setCallsEHReturn(true);
  5133. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5134. MVT::Other,
  5135. getControlRoot(),
  5136. getValue(I.getArgOperand(0)),
  5137. getValue(I.getArgOperand(1))));
  5138. return;
  5139. case Intrinsic::eh_unwind_init:
  5140. DAG.getMachineFunction().setCallsUnwindInit(true);
  5141. return;
  5142. case Intrinsic::eh_dwarf_cfa:
  5143. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5144. TLI.getPointerTy(DAG.getDataLayout()),
  5145. getValue(I.getArgOperand(0))));
  5146. return;
  5147. case Intrinsic::eh_sjlj_callsite: {
  5148. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5149. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5150. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5151. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5152. MMI.setCurrentCallSite(CI->getZExtValue());
  5153. return;
  5154. }
  5155. case Intrinsic::eh_sjlj_functioncontext: {
  5156. // Get and store the index of the function context.
  5157. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5158. AllocaInst *FnCtx =
  5159. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5160. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5161. MFI.setFunctionContextIndex(FI);
  5162. return;
  5163. }
  5164. case Intrinsic::eh_sjlj_setjmp: {
  5165. SDValue Ops[2];
  5166. Ops[0] = getRoot();
  5167. Ops[1] = getValue(I.getArgOperand(0));
  5168. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5169. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5170. setValue(&I, Op.getValue(0));
  5171. DAG.setRoot(Op.getValue(1));
  5172. return;
  5173. }
  5174. case Intrinsic::eh_sjlj_longjmp:
  5175. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5176. getRoot(), getValue(I.getArgOperand(0))));
  5177. return;
  5178. case Intrinsic::eh_sjlj_setup_dispatch:
  5179. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5180. getRoot()));
  5181. return;
  5182. case Intrinsic::masked_gather:
  5183. visitMaskedGather(I);
  5184. return;
  5185. case Intrinsic::masked_load:
  5186. visitMaskedLoad(I);
  5187. return;
  5188. case Intrinsic::masked_scatter:
  5189. visitMaskedScatter(I);
  5190. return;
  5191. case Intrinsic::masked_store:
  5192. visitMaskedStore(I);
  5193. return;
  5194. case Intrinsic::masked_expandload:
  5195. visitMaskedLoad(I, true /* IsExpanding */);
  5196. return;
  5197. case Intrinsic::masked_compressstore:
  5198. visitMaskedStore(I, true /* IsCompressing */);
  5199. return;
  5200. case Intrinsic::x86_mmx_pslli_w:
  5201. case Intrinsic::x86_mmx_pslli_d:
  5202. case Intrinsic::x86_mmx_pslli_q:
  5203. case Intrinsic::x86_mmx_psrli_w:
  5204. case Intrinsic::x86_mmx_psrli_d:
  5205. case Intrinsic::x86_mmx_psrli_q:
  5206. case Intrinsic::x86_mmx_psrai_w:
  5207. case Intrinsic::x86_mmx_psrai_d: {
  5208. SDValue ShAmt = getValue(I.getArgOperand(1));
  5209. if (isa<ConstantSDNode>(ShAmt)) {
  5210. visitTargetIntrinsic(I, Intrinsic);
  5211. return;
  5212. }
  5213. unsigned NewIntrinsic = 0;
  5214. EVT ShAmtVT = MVT::v2i32;
  5215. switch (Intrinsic) {
  5216. case Intrinsic::x86_mmx_pslli_w:
  5217. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  5218. break;
  5219. case Intrinsic::x86_mmx_pslli_d:
  5220. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  5221. break;
  5222. case Intrinsic::x86_mmx_pslli_q:
  5223. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  5224. break;
  5225. case Intrinsic::x86_mmx_psrli_w:
  5226. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  5227. break;
  5228. case Intrinsic::x86_mmx_psrli_d:
  5229. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  5230. break;
  5231. case Intrinsic::x86_mmx_psrli_q:
  5232. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  5233. break;
  5234. case Intrinsic::x86_mmx_psrai_w:
  5235. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  5236. break;
  5237. case Intrinsic::x86_mmx_psrai_d:
  5238. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  5239. break;
  5240. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5241. }
  5242. // The vector shift intrinsics with scalars uses 32b shift amounts but
  5243. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  5244. // to be zero.
  5245. // We must do this early because v2i32 is not a legal type.
  5246. SDValue ShOps[2];
  5247. ShOps[0] = ShAmt;
  5248. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  5249. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  5250. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5251. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  5252. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  5253. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  5254. getValue(I.getArgOperand(0)), ShAmt);
  5255. setValue(&I, Res);
  5256. return;
  5257. }
  5258. case Intrinsic::powi:
  5259. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5260. getValue(I.getArgOperand(1)), DAG));
  5261. return;
  5262. case Intrinsic::log:
  5263. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5264. return;
  5265. case Intrinsic::log2:
  5266. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5267. return;
  5268. case Intrinsic::log10:
  5269. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5270. return;
  5271. case Intrinsic::exp:
  5272. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5273. return;
  5274. case Intrinsic::exp2:
  5275. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5276. return;
  5277. case Intrinsic::pow:
  5278. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5279. getValue(I.getArgOperand(1)), DAG, TLI));
  5280. return;
  5281. case Intrinsic::sqrt:
  5282. case Intrinsic::fabs:
  5283. case Intrinsic::sin:
  5284. case Intrinsic::cos:
  5285. case Intrinsic::floor:
  5286. case Intrinsic::ceil:
  5287. case Intrinsic::trunc:
  5288. case Intrinsic::rint:
  5289. case Intrinsic::nearbyint:
  5290. case Intrinsic::round:
  5291. case Intrinsic::canonicalize: {
  5292. unsigned Opcode;
  5293. switch (Intrinsic) {
  5294. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5295. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5296. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5297. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5298. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5299. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5300. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5301. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5302. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5303. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5304. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5305. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5306. }
  5307. setValue(&I, DAG.getNode(Opcode, sdl,
  5308. getValue(I.getArgOperand(0)).getValueType(),
  5309. getValue(I.getArgOperand(0))));
  5310. return;
  5311. }
  5312. case Intrinsic::lround:
  5313. case Intrinsic::llround:
  5314. case Intrinsic::lrint:
  5315. case Intrinsic::llrint: {
  5316. unsigned Opcode;
  5317. switch (Intrinsic) {
  5318. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5319. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5320. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5321. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5322. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5323. }
  5324. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5325. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5326. getValue(I.getArgOperand(0))));
  5327. return;
  5328. }
  5329. case Intrinsic::minnum: {
  5330. auto VT = getValue(I.getArgOperand(0)).getValueType();
  5331. unsigned Opc =
  5332. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
  5333. ? ISD::FMINIMUM
  5334. : ISD::FMINNUM;
  5335. setValue(&I, DAG.getNode(Opc, sdl, VT,
  5336. getValue(I.getArgOperand(0)),
  5337. getValue(I.getArgOperand(1))));
  5338. return;
  5339. }
  5340. case Intrinsic::maxnum: {
  5341. auto VT = getValue(I.getArgOperand(0)).getValueType();
  5342. unsigned Opc =
  5343. I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
  5344. ? ISD::FMAXIMUM
  5345. : ISD::FMAXNUM;
  5346. setValue(&I, DAG.getNode(Opc, sdl, VT,
  5347. getValue(I.getArgOperand(0)),
  5348. getValue(I.getArgOperand(1))));
  5349. return;
  5350. }
  5351. case Intrinsic::minimum:
  5352. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5353. getValue(I.getArgOperand(0)).getValueType(),
  5354. getValue(I.getArgOperand(0)),
  5355. getValue(I.getArgOperand(1))));
  5356. return;
  5357. case Intrinsic::maximum:
  5358. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5359. getValue(I.getArgOperand(0)).getValueType(),
  5360. getValue(I.getArgOperand(0)),
  5361. getValue(I.getArgOperand(1))));
  5362. return;
  5363. case Intrinsic::copysign:
  5364. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5365. getValue(I.getArgOperand(0)).getValueType(),
  5366. getValue(I.getArgOperand(0)),
  5367. getValue(I.getArgOperand(1))));
  5368. return;
  5369. case Intrinsic::fma:
  5370. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5371. getValue(I.getArgOperand(0)).getValueType(),
  5372. getValue(I.getArgOperand(0)),
  5373. getValue(I.getArgOperand(1)),
  5374. getValue(I.getArgOperand(2))));
  5375. return;
  5376. case Intrinsic::experimental_constrained_fadd:
  5377. case Intrinsic::experimental_constrained_fsub:
  5378. case Intrinsic::experimental_constrained_fmul:
  5379. case Intrinsic::experimental_constrained_fdiv:
  5380. case Intrinsic::experimental_constrained_frem:
  5381. case Intrinsic::experimental_constrained_fma:
  5382. case Intrinsic::experimental_constrained_fptrunc:
  5383. case Intrinsic::experimental_constrained_fpext:
  5384. case Intrinsic::experimental_constrained_sqrt:
  5385. case Intrinsic::experimental_constrained_pow:
  5386. case Intrinsic::experimental_constrained_powi:
  5387. case Intrinsic::experimental_constrained_sin:
  5388. case Intrinsic::experimental_constrained_cos:
  5389. case Intrinsic::experimental_constrained_exp:
  5390. case Intrinsic::experimental_constrained_exp2:
  5391. case Intrinsic::experimental_constrained_log:
  5392. case Intrinsic::experimental_constrained_log10:
  5393. case Intrinsic::experimental_constrained_log2:
  5394. case Intrinsic::experimental_constrained_rint:
  5395. case Intrinsic::experimental_constrained_nearbyint:
  5396. case Intrinsic::experimental_constrained_maxnum:
  5397. case Intrinsic::experimental_constrained_minnum:
  5398. case Intrinsic::experimental_constrained_ceil:
  5399. case Intrinsic::experimental_constrained_floor:
  5400. case Intrinsic::experimental_constrained_round:
  5401. case Intrinsic::experimental_constrained_trunc:
  5402. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5403. return;
  5404. case Intrinsic::fmuladd: {
  5405. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5406. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5407. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5408. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5409. getValue(I.getArgOperand(0)).getValueType(),
  5410. getValue(I.getArgOperand(0)),
  5411. getValue(I.getArgOperand(1)),
  5412. getValue(I.getArgOperand(2))));
  5413. } else {
  5414. // TODO: Intrinsic calls should have fast-math-flags.
  5415. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5416. getValue(I.getArgOperand(0)).getValueType(),
  5417. getValue(I.getArgOperand(0)),
  5418. getValue(I.getArgOperand(1)));
  5419. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5420. getValue(I.getArgOperand(0)).getValueType(),
  5421. Mul,
  5422. getValue(I.getArgOperand(2)));
  5423. setValue(&I, Add);
  5424. }
  5425. return;
  5426. }
  5427. case Intrinsic::convert_to_fp16:
  5428. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5429. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5430. getValue(I.getArgOperand(0)),
  5431. DAG.getTargetConstant(0, sdl,
  5432. MVT::i32))));
  5433. return;
  5434. case Intrinsic::convert_from_fp16:
  5435. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5436. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5437. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5438. getValue(I.getArgOperand(0)))));
  5439. return;
  5440. case Intrinsic::pcmarker: {
  5441. SDValue Tmp = getValue(I.getArgOperand(0));
  5442. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5443. return;
  5444. }
  5445. case Intrinsic::readcyclecounter: {
  5446. SDValue Op = getRoot();
  5447. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5448. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5449. setValue(&I, Res);
  5450. DAG.setRoot(Res.getValue(1));
  5451. return;
  5452. }
  5453. case Intrinsic::bitreverse:
  5454. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5455. getValue(I.getArgOperand(0)).getValueType(),
  5456. getValue(I.getArgOperand(0))));
  5457. return;
  5458. case Intrinsic::bswap:
  5459. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5460. getValue(I.getArgOperand(0)).getValueType(),
  5461. getValue(I.getArgOperand(0))));
  5462. return;
  5463. case Intrinsic::cttz: {
  5464. SDValue Arg = getValue(I.getArgOperand(0));
  5465. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5466. EVT Ty = Arg.getValueType();
  5467. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5468. sdl, Ty, Arg));
  5469. return;
  5470. }
  5471. case Intrinsic::ctlz: {
  5472. SDValue Arg = getValue(I.getArgOperand(0));
  5473. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5474. EVT Ty = Arg.getValueType();
  5475. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5476. sdl, Ty, Arg));
  5477. return;
  5478. }
  5479. case Intrinsic::ctpop: {
  5480. SDValue Arg = getValue(I.getArgOperand(0));
  5481. EVT Ty = Arg.getValueType();
  5482. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5483. return;
  5484. }
  5485. case Intrinsic::fshl:
  5486. case Intrinsic::fshr: {
  5487. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5488. SDValue X = getValue(I.getArgOperand(0));
  5489. SDValue Y = getValue(I.getArgOperand(1));
  5490. SDValue Z = getValue(I.getArgOperand(2));
  5491. EVT VT = X.getValueType();
  5492. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5493. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5494. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5495. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5496. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5497. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5498. return;
  5499. }
  5500. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5501. // avoid the select that is necessary in the general case to filter out
  5502. // the 0-shift possibility that leads to UB.
  5503. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5504. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5505. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5506. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5507. return;
  5508. }
  5509. // Some targets only rotate one way. Try the opposite direction.
  5510. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5511. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5512. // Negate the shift amount because it is safe to ignore the high bits.
  5513. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5514. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5515. return;
  5516. }
  5517. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5518. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5519. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5520. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5521. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5522. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5523. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5524. return;
  5525. }
  5526. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5527. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5528. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5529. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5530. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5531. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5532. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5533. // and that is undefined. We must compare and select to avoid UB.
  5534. EVT CCVT = MVT::i1;
  5535. if (VT.isVector())
  5536. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5537. // For fshl, 0-shift returns the 1st arg (X).
  5538. // For fshr, 0-shift returns the 2nd arg (Y).
  5539. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5540. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5541. return;
  5542. }
  5543. case Intrinsic::sadd_sat: {
  5544. SDValue Op1 = getValue(I.getArgOperand(0));
  5545. SDValue Op2 = getValue(I.getArgOperand(1));
  5546. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5547. return;
  5548. }
  5549. case Intrinsic::uadd_sat: {
  5550. SDValue Op1 = getValue(I.getArgOperand(0));
  5551. SDValue Op2 = getValue(I.getArgOperand(1));
  5552. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5553. return;
  5554. }
  5555. case Intrinsic::ssub_sat: {
  5556. SDValue Op1 = getValue(I.getArgOperand(0));
  5557. SDValue Op2 = getValue(I.getArgOperand(1));
  5558. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5559. return;
  5560. }
  5561. case Intrinsic::usub_sat: {
  5562. SDValue Op1 = getValue(I.getArgOperand(0));
  5563. SDValue Op2 = getValue(I.getArgOperand(1));
  5564. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5565. return;
  5566. }
  5567. case Intrinsic::smul_fix:
  5568. case Intrinsic::umul_fix: {
  5569. SDValue Op1 = getValue(I.getArgOperand(0));
  5570. SDValue Op2 = getValue(I.getArgOperand(1));
  5571. SDValue Op3 = getValue(I.getArgOperand(2));
  5572. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5573. Op1.getValueType(), Op1, Op2, Op3));
  5574. return;
  5575. }
  5576. case Intrinsic::smul_fix_sat: {
  5577. SDValue Op1 = getValue(I.getArgOperand(0));
  5578. SDValue Op2 = getValue(I.getArgOperand(1));
  5579. SDValue Op3 = getValue(I.getArgOperand(2));
  5580. setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5581. Op3));
  5582. return;
  5583. }
  5584. case Intrinsic::stacksave: {
  5585. SDValue Op = getRoot();
  5586. Res = DAG.getNode(
  5587. ISD::STACKSAVE, sdl,
  5588. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5589. setValue(&I, Res);
  5590. DAG.setRoot(Res.getValue(1));
  5591. return;
  5592. }
  5593. case Intrinsic::stackrestore:
  5594. Res = getValue(I.getArgOperand(0));
  5595. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5596. return;
  5597. case Intrinsic::get_dynamic_area_offset: {
  5598. SDValue Op = getRoot();
  5599. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5600. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5601. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5602. // target.
  5603. if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
  5604. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5605. " intrinsic!");
  5606. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5607. Op);
  5608. DAG.setRoot(Op);
  5609. setValue(&I, Res);
  5610. return;
  5611. }
  5612. case Intrinsic::stackguard: {
  5613. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5614. MachineFunction &MF = DAG.getMachineFunction();
  5615. const Module &M = *MF.getFunction().getParent();
  5616. SDValue Chain = getRoot();
  5617. if (TLI.useLoadStackGuardNode()) {
  5618. Res = getLoadStackGuard(DAG, sdl, Chain);
  5619. } else {
  5620. const Value *Global = TLI.getSDagStackGuard(M);
  5621. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5622. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5623. MachinePointerInfo(Global, 0), Align,
  5624. MachineMemOperand::MOVolatile);
  5625. }
  5626. if (TLI.useStackGuardXorFP())
  5627. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5628. DAG.setRoot(Chain);
  5629. setValue(&I, Res);
  5630. return;
  5631. }
  5632. case Intrinsic::stackprotector: {
  5633. // Emit code into the DAG to store the stack guard onto the stack.
  5634. MachineFunction &MF = DAG.getMachineFunction();
  5635. MachineFrameInfo &MFI = MF.getFrameInfo();
  5636. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5637. SDValue Src, Chain = getRoot();
  5638. if (TLI.useLoadStackGuardNode())
  5639. Src = getLoadStackGuard(DAG, sdl, Chain);
  5640. else
  5641. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5642. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5643. int FI = FuncInfo.StaticAllocaMap[Slot];
  5644. MFI.setStackProtectorIndex(FI);
  5645. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5646. // Store the stack protector onto the stack.
  5647. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5648. DAG.getMachineFunction(), FI),
  5649. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5650. setValue(&I, Res);
  5651. DAG.setRoot(Res);
  5652. return;
  5653. }
  5654. case Intrinsic::objectsize: {
  5655. // If we don't know by now, we're never going to know.
  5656. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5657. assert(CI && "Non-constant type in __builtin_object_size?");
  5658. SDValue Arg = getValue(I.getCalledValue());
  5659. EVT Ty = Arg.getValueType();
  5660. if (CI->isZero())
  5661. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5662. else
  5663. Res = DAG.getConstant(0, sdl, Ty);
  5664. setValue(&I, Res);
  5665. return;
  5666. }
  5667. case Intrinsic::is_constant:
  5668. // If this wasn't constant-folded away by now, then it's not a
  5669. // constant.
  5670. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5671. return;
  5672. case Intrinsic::annotation:
  5673. case Intrinsic::ptr_annotation:
  5674. case Intrinsic::launder_invariant_group:
  5675. case Intrinsic::strip_invariant_group:
  5676. // Drop the intrinsic, but forward the value
  5677. setValue(&I, getValue(I.getOperand(0)));
  5678. return;
  5679. case Intrinsic::assume:
  5680. case Intrinsic::var_annotation:
  5681. case Intrinsic::sideeffect:
  5682. // Discard annotate attributes, assumptions, and artificial side-effects.
  5683. return;
  5684. case Intrinsic::codeview_annotation: {
  5685. // Emit a label associated with this metadata.
  5686. MachineFunction &MF = DAG.getMachineFunction();
  5687. MCSymbol *Label =
  5688. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5689. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5690. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5691. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5692. DAG.setRoot(Res);
  5693. return;
  5694. }
  5695. case Intrinsic::init_trampoline: {
  5696. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5697. SDValue Ops[6];
  5698. Ops[0] = getRoot();
  5699. Ops[1] = getValue(I.getArgOperand(0));
  5700. Ops[2] = getValue(I.getArgOperand(1));
  5701. Ops[3] = getValue(I.getArgOperand(2));
  5702. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5703. Ops[5] = DAG.getSrcValue(F);
  5704. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5705. DAG.setRoot(Res);
  5706. return;
  5707. }
  5708. case Intrinsic::adjust_trampoline:
  5709. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5710. TLI.getPointerTy(DAG.getDataLayout()),
  5711. getValue(I.getArgOperand(0))));
  5712. return;
  5713. case Intrinsic::gcroot: {
  5714. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5715. "only valid in functions with gc specified, enforced by Verifier");
  5716. assert(GFI && "implied by previous");
  5717. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5718. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5719. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5720. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5721. return;
  5722. }
  5723. case Intrinsic::gcread:
  5724. case Intrinsic::gcwrite:
  5725. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5726. case Intrinsic::flt_rounds:
  5727. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5728. return;
  5729. case Intrinsic::expect:
  5730. // Just replace __builtin_expect(exp, c) with EXP.
  5731. setValue(&I, getValue(I.getArgOperand(0)));
  5732. return;
  5733. case Intrinsic::debugtrap:
  5734. case Intrinsic::trap: {
  5735. StringRef TrapFuncName =
  5736. I.getAttributes()
  5737. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5738. .getValueAsString();
  5739. if (TrapFuncName.empty()) {
  5740. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5741. ISD::TRAP : ISD::DEBUGTRAP;
  5742. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5743. return;
  5744. }
  5745. TargetLowering::ArgListTy Args;
  5746. TargetLowering::CallLoweringInfo CLI(DAG);
  5747. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5748. CallingConv::C, I.getType(),
  5749. DAG.getExternalSymbol(TrapFuncName.data(),
  5750. TLI.getPointerTy(DAG.getDataLayout())),
  5751. std::move(Args));
  5752. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5753. DAG.setRoot(Result.second);
  5754. return;
  5755. }
  5756. case Intrinsic::uadd_with_overflow:
  5757. case Intrinsic::sadd_with_overflow:
  5758. case Intrinsic::usub_with_overflow:
  5759. case Intrinsic::ssub_with_overflow:
  5760. case Intrinsic::umul_with_overflow:
  5761. case Intrinsic::smul_with_overflow: {
  5762. ISD::NodeType Op;
  5763. switch (Intrinsic) {
  5764. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5765. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5766. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5767. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5768. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5769. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5770. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5771. }
  5772. SDValue Op1 = getValue(I.getArgOperand(0));
  5773. SDValue Op2 = getValue(I.getArgOperand(1));
  5774. EVT ResultVT = Op1.getValueType();
  5775. EVT OverflowVT = MVT::i1;
  5776. if (ResultVT.isVector())
  5777. OverflowVT = EVT::getVectorVT(
  5778. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5779. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5780. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5781. return;
  5782. }
  5783. case Intrinsic::prefetch: {
  5784. SDValue Ops[5];
  5785. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5786. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5787. Ops[0] = DAG.getRoot();
  5788. Ops[1] = getValue(I.getArgOperand(0));
  5789. Ops[2] = getValue(I.getArgOperand(1));
  5790. Ops[3] = getValue(I.getArgOperand(2));
  5791. Ops[4] = getValue(I.getArgOperand(3));
  5792. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5793. DAG.getVTList(MVT::Other), Ops,
  5794. EVT::getIntegerVT(*Context, 8),
  5795. MachinePointerInfo(I.getArgOperand(0)),
  5796. 0, /* align */
  5797. Flags);
  5798. // Chain the prefetch in parallell with any pending loads, to stay out of
  5799. // the way of later optimizations.
  5800. PendingLoads.push_back(Result);
  5801. Result = getRoot();
  5802. DAG.setRoot(Result);
  5803. return;
  5804. }
  5805. case Intrinsic::lifetime_start:
  5806. case Intrinsic::lifetime_end: {
  5807. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5808. // Stack coloring is not enabled in O0, discard region information.
  5809. if (TM.getOptLevel() == CodeGenOpt::None)
  5810. return;
  5811. const int64_t ObjectSize =
  5812. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5813. Value *const ObjectPtr = I.getArgOperand(1);
  5814. SmallVector<const Value *, 4> Allocas;
  5815. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5816. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5817. E = Allocas.end(); Object != E; ++Object) {
  5818. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5819. // Could not find an Alloca.
  5820. if (!LifetimeObject)
  5821. continue;
  5822. // First check that the Alloca is static, otherwise it won't have a
  5823. // valid frame index.
  5824. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5825. if (SI == FuncInfo.StaticAllocaMap.end())
  5826. return;
  5827. const int FrameIndex = SI->second;
  5828. int64_t Offset;
  5829. if (GetPointerBaseWithConstantOffset(
  5830. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5831. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5832. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5833. Offset);
  5834. DAG.setRoot(Res);
  5835. }
  5836. return;
  5837. }
  5838. case Intrinsic::invariant_start:
  5839. // Discard region information.
  5840. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5841. return;
  5842. case Intrinsic::invariant_end:
  5843. // Discard region information.
  5844. return;
  5845. case Intrinsic::clear_cache:
  5846. /// FunctionName may be null.
  5847. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  5848. lowerCallToExternalSymbol(I, FunctionName);
  5849. return;
  5850. case Intrinsic::donothing:
  5851. // ignore
  5852. return;
  5853. case Intrinsic::experimental_stackmap:
  5854. visitStackmap(I);
  5855. return;
  5856. case Intrinsic::experimental_patchpoint_void:
  5857. case Intrinsic::experimental_patchpoint_i64:
  5858. visitPatchpoint(&I);
  5859. return;
  5860. case Intrinsic::experimental_gc_statepoint:
  5861. LowerStatepoint(ImmutableStatepoint(&I));
  5862. return;
  5863. case Intrinsic::experimental_gc_result:
  5864. visitGCResult(cast<GCResultInst>(I));
  5865. return;
  5866. case Intrinsic::experimental_gc_relocate:
  5867. visitGCRelocate(cast<GCRelocateInst>(I));
  5868. return;
  5869. case Intrinsic::instrprof_increment:
  5870. llvm_unreachable("instrprof failed to lower an increment");
  5871. case Intrinsic::instrprof_value_profile:
  5872. llvm_unreachable("instrprof failed to lower a value profiling call");
  5873. case Intrinsic::localescape: {
  5874. MachineFunction &MF = DAG.getMachineFunction();
  5875. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5876. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5877. // is the same on all targets.
  5878. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5879. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5880. if (isa<ConstantPointerNull>(Arg))
  5881. continue; // Skip null pointers. They represent a hole in index space.
  5882. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5883. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5884. "can only escape static allocas");
  5885. int FI = FuncInfo.StaticAllocaMap[Slot];
  5886. MCSymbol *FrameAllocSym =
  5887. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5888. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5889. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5890. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5891. .addSym(FrameAllocSym)
  5892. .addFrameIndex(FI);
  5893. }
  5894. return;
  5895. }
  5896. case Intrinsic::localrecover: {
  5897. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5898. MachineFunction &MF = DAG.getMachineFunction();
  5899. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5900. // Get the symbol that defines the frame offset.
  5901. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5902. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5903. unsigned IdxVal =
  5904. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5905. MCSymbol *FrameAllocSym =
  5906. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5907. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5908. // Create a MCSymbol for the label to avoid any target lowering
  5909. // that would make this PC relative.
  5910. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5911. SDValue OffsetVal =
  5912. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5913. // Add the offset to the FP.
  5914. Value *FP = I.getArgOperand(1);
  5915. SDValue FPVal = getValue(FP);
  5916. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5917. setValue(&I, Add);
  5918. return;
  5919. }
  5920. case Intrinsic::eh_exceptionpointer:
  5921. case Intrinsic::eh_exceptioncode: {
  5922. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5923. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5924. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5925. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5926. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5927. SDValue N =
  5928. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5929. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5930. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5931. setValue(&I, N);
  5932. return;
  5933. }
  5934. case Intrinsic::xray_customevent: {
  5935. // Here we want to make sure that the intrinsic behaves as if it has a
  5936. // specific calling convention, and only for x86_64.
  5937. // FIXME: Support other platforms later.
  5938. const auto &Triple = DAG.getTarget().getTargetTriple();
  5939. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5940. return;
  5941. SDLoc DL = getCurSDLoc();
  5942. SmallVector<SDValue, 8> Ops;
  5943. // We want to say that we always want the arguments in registers.
  5944. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5945. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5946. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5947. SDValue Chain = getRoot();
  5948. Ops.push_back(LogEntryVal);
  5949. Ops.push_back(StrSizeVal);
  5950. Ops.push_back(Chain);
  5951. // We need to enforce the calling convention for the callsite, so that
  5952. // argument ordering is enforced correctly, and that register allocation can
  5953. // see that some registers may be assumed clobbered and have to preserve
  5954. // them across calls to the intrinsic.
  5955. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5956. DL, NodeTys, Ops);
  5957. SDValue patchableNode = SDValue(MN, 0);
  5958. DAG.setRoot(patchableNode);
  5959. setValue(&I, patchableNode);
  5960. return;
  5961. }
  5962. case Intrinsic::xray_typedevent: {
  5963. // Here we want to make sure that the intrinsic behaves as if it has a
  5964. // specific calling convention, and only for x86_64.
  5965. // FIXME: Support other platforms later.
  5966. const auto &Triple = DAG.getTarget().getTargetTriple();
  5967. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5968. return;
  5969. SDLoc DL = getCurSDLoc();
  5970. SmallVector<SDValue, 8> Ops;
  5971. // We want to say that we always want the arguments in registers.
  5972. // It's unclear to me how manipulating the selection DAG here forces callers
  5973. // to provide arguments in registers instead of on the stack.
  5974. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5975. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5976. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5977. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5978. SDValue Chain = getRoot();
  5979. Ops.push_back(LogTypeId);
  5980. Ops.push_back(LogEntryVal);
  5981. Ops.push_back(StrSizeVal);
  5982. Ops.push_back(Chain);
  5983. // We need to enforce the calling convention for the callsite, so that
  5984. // argument ordering is enforced correctly, and that register allocation can
  5985. // see that some registers may be assumed clobbered and have to preserve
  5986. // them across calls to the intrinsic.
  5987. MachineSDNode *MN = DAG.getMachineNode(
  5988. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  5989. SDValue patchableNode = SDValue(MN, 0);
  5990. DAG.setRoot(patchableNode);
  5991. setValue(&I, patchableNode);
  5992. return;
  5993. }
  5994. case Intrinsic::experimental_deoptimize:
  5995. LowerDeoptimizeCall(&I);
  5996. return;
  5997. case Intrinsic::experimental_vector_reduce_fadd:
  5998. case Intrinsic::experimental_vector_reduce_fmul:
  5999. case Intrinsic::experimental_vector_reduce_add:
  6000. case Intrinsic::experimental_vector_reduce_mul:
  6001. case Intrinsic::experimental_vector_reduce_and:
  6002. case Intrinsic::experimental_vector_reduce_or:
  6003. case Intrinsic::experimental_vector_reduce_xor:
  6004. case Intrinsic::experimental_vector_reduce_smax:
  6005. case Intrinsic::experimental_vector_reduce_smin:
  6006. case Intrinsic::experimental_vector_reduce_umax:
  6007. case Intrinsic::experimental_vector_reduce_umin:
  6008. case Intrinsic::experimental_vector_reduce_fmax:
  6009. case Intrinsic::experimental_vector_reduce_fmin:
  6010. visitVectorReduce(I, Intrinsic);
  6011. return;
  6012. case Intrinsic::icall_branch_funnel: {
  6013. SmallVector<SDValue, 16> Ops;
  6014. Ops.push_back(DAG.getRoot());
  6015. Ops.push_back(getValue(I.getArgOperand(0)));
  6016. int64_t Offset;
  6017. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6018. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  6019. if (!Base)
  6020. report_fatal_error(
  6021. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6022. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  6023. struct BranchFunnelTarget {
  6024. int64_t Offset;
  6025. SDValue Target;
  6026. };
  6027. SmallVector<BranchFunnelTarget, 8> Targets;
  6028. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  6029. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6030. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6031. if (ElemBase != Base)
  6032. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6033. "to the same GlobalValue");
  6034. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6035. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6036. if (!GA)
  6037. report_fatal_error(
  6038. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6039. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6040. GA->getGlobal(), getCurSDLoc(),
  6041. Val.getValueType(), GA->getOffset())});
  6042. }
  6043. llvm::sort(Targets,
  6044. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6045. return T1.Offset < T2.Offset;
  6046. });
  6047. for (auto &T : Targets) {
  6048. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  6049. Ops.push_back(T.Target);
  6050. }
  6051. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  6052. getCurSDLoc(), MVT::Other, Ops),
  6053. 0);
  6054. DAG.setRoot(N);
  6055. setValue(&I, N);
  6056. HasTailCall = true;
  6057. return;
  6058. }
  6059. case Intrinsic::wasm_landingpad_index:
  6060. // Information this intrinsic contained has been transferred to
  6061. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6062. // delete it now.
  6063. return;
  6064. }
  6065. }
  6066. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6067. const ConstrainedFPIntrinsic &FPI) {
  6068. SDLoc sdl = getCurSDLoc();
  6069. unsigned Opcode;
  6070. switch (FPI.getIntrinsicID()) {
  6071. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6072. case Intrinsic::experimental_constrained_fadd:
  6073. Opcode = ISD::STRICT_FADD;
  6074. break;
  6075. case Intrinsic::experimental_constrained_fsub:
  6076. Opcode = ISD::STRICT_FSUB;
  6077. break;
  6078. case Intrinsic::experimental_constrained_fmul:
  6079. Opcode = ISD::STRICT_FMUL;
  6080. break;
  6081. case Intrinsic::experimental_constrained_fdiv:
  6082. Opcode = ISD::STRICT_FDIV;
  6083. break;
  6084. case Intrinsic::experimental_constrained_frem:
  6085. Opcode = ISD::STRICT_FREM;
  6086. break;
  6087. case Intrinsic::experimental_constrained_fma:
  6088. Opcode = ISD::STRICT_FMA;
  6089. break;
  6090. case Intrinsic::experimental_constrained_fptrunc:
  6091. Opcode = ISD::STRICT_FP_ROUND;
  6092. break;
  6093. case Intrinsic::experimental_constrained_fpext:
  6094. Opcode = ISD::STRICT_FP_EXTEND;
  6095. break;
  6096. case Intrinsic::experimental_constrained_sqrt:
  6097. Opcode = ISD::STRICT_FSQRT;
  6098. break;
  6099. case Intrinsic::experimental_constrained_pow:
  6100. Opcode = ISD::STRICT_FPOW;
  6101. break;
  6102. case Intrinsic::experimental_constrained_powi:
  6103. Opcode = ISD::STRICT_FPOWI;
  6104. break;
  6105. case Intrinsic::experimental_constrained_sin:
  6106. Opcode = ISD::STRICT_FSIN;
  6107. break;
  6108. case Intrinsic::experimental_constrained_cos:
  6109. Opcode = ISD::STRICT_FCOS;
  6110. break;
  6111. case Intrinsic::experimental_constrained_exp:
  6112. Opcode = ISD::STRICT_FEXP;
  6113. break;
  6114. case Intrinsic::experimental_constrained_exp2:
  6115. Opcode = ISD::STRICT_FEXP2;
  6116. break;
  6117. case Intrinsic::experimental_constrained_log:
  6118. Opcode = ISD::STRICT_FLOG;
  6119. break;
  6120. case Intrinsic::experimental_constrained_log10:
  6121. Opcode = ISD::STRICT_FLOG10;
  6122. break;
  6123. case Intrinsic::experimental_constrained_log2:
  6124. Opcode = ISD::STRICT_FLOG2;
  6125. break;
  6126. case Intrinsic::experimental_constrained_rint:
  6127. Opcode = ISD::STRICT_FRINT;
  6128. break;
  6129. case Intrinsic::experimental_constrained_nearbyint:
  6130. Opcode = ISD::STRICT_FNEARBYINT;
  6131. break;
  6132. case Intrinsic::experimental_constrained_maxnum:
  6133. Opcode = ISD::STRICT_FMAXNUM;
  6134. break;
  6135. case Intrinsic::experimental_constrained_minnum:
  6136. Opcode = ISD::STRICT_FMINNUM;
  6137. break;
  6138. case Intrinsic::experimental_constrained_ceil:
  6139. Opcode = ISD::STRICT_FCEIL;
  6140. break;
  6141. case Intrinsic::experimental_constrained_floor:
  6142. Opcode = ISD::STRICT_FFLOOR;
  6143. break;
  6144. case Intrinsic::experimental_constrained_round:
  6145. Opcode = ISD::STRICT_FROUND;
  6146. break;
  6147. case Intrinsic::experimental_constrained_trunc:
  6148. Opcode = ISD::STRICT_FTRUNC;
  6149. break;
  6150. }
  6151. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6152. SDValue Chain = getRoot();
  6153. SmallVector<EVT, 4> ValueVTs;
  6154. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6155. ValueVTs.push_back(MVT::Other); // Out chain
  6156. SDVTList VTs = DAG.getVTList(ValueVTs);
  6157. SDValue Result;
  6158. if (Opcode == ISD::STRICT_FP_ROUND)
  6159. Result = DAG.getNode(Opcode, sdl, VTs,
  6160. { Chain, getValue(FPI.getArgOperand(0)),
  6161. DAG.getTargetConstant(0, sdl,
  6162. TLI.getPointerTy(DAG.getDataLayout())) });
  6163. else if (FPI.isUnaryOp())
  6164. Result = DAG.getNode(Opcode, sdl, VTs,
  6165. { Chain, getValue(FPI.getArgOperand(0)) });
  6166. else if (FPI.isTernaryOp())
  6167. Result = DAG.getNode(Opcode, sdl, VTs,
  6168. { Chain, getValue(FPI.getArgOperand(0)),
  6169. getValue(FPI.getArgOperand(1)),
  6170. getValue(FPI.getArgOperand(2)) });
  6171. else
  6172. Result = DAG.getNode(Opcode, sdl, VTs,
  6173. { Chain, getValue(FPI.getArgOperand(0)),
  6174. getValue(FPI.getArgOperand(1)) });
  6175. assert(Result.getNode()->getNumValues() == 2);
  6176. SDValue OutChain = Result.getValue(1);
  6177. DAG.setRoot(OutChain);
  6178. SDValue FPResult = Result.getValue(0);
  6179. setValue(&FPI, FPResult);
  6180. }
  6181. std::pair<SDValue, SDValue>
  6182. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6183. const BasicBlock *EHPadBB) {
  6184. MachineFunction &MF = DAG.getMachineFunction();
  6185. MachineModuleInfo &MMI = MF.getMMI();
  6186. MCSymbol *BeginLabel = nullptr;
  6187. if (EHPadBB) {
  6188. // Insert a label before the invoke call to mark the try range. This can be
  6189. // used to detect deletion of the invoke via the MachineModuleInfo.
  6190. BeginLabel = MMI.getContext().createTempSymbol();
  6191. // For SjLj, keep track of which landing pads go with which invokes
  6192. // so as to maintain the ordering of pads in the LSDA.
  6193. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6194. if (CallSiteIndex) {
  6195. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6196. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6197. // Now that the call site is handled, stop tracking it.
  6198. MMI.setCurrentCallSite(0);
  6199. }
  6200. // Both PendingLoads and PendingExports must be flushed here;
  6201. // this call might not return.
  6202. (void)getRoot();
  6203. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6204. CLI.setChain(getRoot());
  6205. }
  6206. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6207. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6208. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6209. "Non-null chain expected with non-tail call!");
  6210. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6211. "Null value expected with tail call!");
  6212. if (!Result.second.getNode()) {
  6213. // As a special case, a null chain means that a tail call has been emitted
  6214. // and the DAG root is already updated.
  6215. HasTailCall = true;
  6216. // Since there's no actual continuation from this block, nothing can be
  6217. // relying on us setting vregs for them.
  6218. PendingExports.clear();
  6219. } else {
  6220. DAG.setRoot(Result.second);
  6221. }
  6222. if (EHPadBB) {
  6223. // Insert a label at the end of the invoke call to mark the try range. This
  6224. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6225. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6226. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6227. // Inform MachineModuleInfo of range.
  6228. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6229. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6230. // actually use outlined funclets and their LSDA info style.
  6231. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6232. assert(CLI.CS);
  6233. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6234. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6235. BeginLabel, EndLabel);
  6236. } else if (!isScopedEHPersonality(Pers)) {
  6237. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6238. }
  6239. }
  6240. return Result;
  6241. }
  6242. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6243. bool isTailCall,
  6244. const BasicBlock *EHPadBB) {
  6245. auto &DL = DAG.getDataLayout();
  6246. FunctionType *FTy = CS.getFunctionType();
  6247. Type *RetTy = CS.getType();
  6248. TargetLowering::ArgListTy Args;
  6249. Args.reserve(CS.arg_size());
  6250. const Value *SwiftErrorVal = nullptr;
  6251. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6252. // We can't tail call inside a function with a swifterror argument. Lowering
  6253. // does not support this yet. It would have to move into the swifterror
  6254. // register before the call.
  6255. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6256. if (TLI.supportSwiftError() &&
  6257. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6258. isTailCall = false;
  6259. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6260. i != e; ++i) {
  6261. TargetLowering::ArgListEntry Entry;
  6262. const Value *V = *i;
  6263. // Skip empty types
  6264. if (V->getType()->isEmptyTy())
  6265. continue;
  6266. SDValue ArgNode = getValue(V);
  6267. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6268. Entry.setAttributes(&CS, i - CS.arg_begin());
  6269. // Use swifterror virtual register as input to the call.
  6270. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6271. SwiftErrorVal = V;
  6272. // We find the virtual register for the actual swifterror argument.
  6273. // Instead of using the Value, we use the virtual register instead.
  6274. Entry.Node = DAG.getRegister(
  6275. SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
  6276. EVT(TLI.getPointerTy(DL)));
  6277. }
  6278. Args.push_back(Entry);
  6279. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6280. // might point to function-local memory), we can't meaningfully tail-call.
  6281. if (Entry.IsSRet && isa<Instruction>(V))
  6282. isTailCall = false;
  6283. }
  6284. // Check if target-independent constraints permit a tail call here.
  6285. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6286. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6287. isTailCall = false;
  6288. // Disable tail calls if there is an swifterror argument. Targets have not
  6289. // been updated to support tail calls.
  6290. if (TLI.supportSwiftError() && SwiftErrorVal)
  6291. isTailCall = false;
  6292. TargetLowering::CallLoweringInfo CLI(DAG);
  6293. CLI.setDebugLoc(getCurSDLoc())
  6294. .setChain(getRoot())
  6295. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6296. .setTailCall(isTailCall)
  6297. .setConvergent(CS.isConvergent());
  6298. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6299. if (Result.first.getNode()) {
  6300. const Instruction *Inst = CS.getInstruction();
  6301. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6302. setValue(Inst, Result.first);
  6303. }
  6304. // The last element of CLI.InVals has the SDValue for swifterror return.
  6305. // Here we copy it to a virtual register and update SwiftErrorMap for
  6306. // book-keeping.
  6307. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6308. // Get the last element of InVals.
  6309. SDValue Src = CLI.InVals.back();
  6310. unsigned VReg = SwiftError.getOrCreateVRegDefAt(
  6311. CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
  6312. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6313. DAG.setRoot(CopyNode);
  6314. }
  6315. }
  6316. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6317. SelectionDAGBuilder &Builder) {
  6318. // Check to see if this load can be trivially constant folded, e.g. if the
  6319. // input is from a string literal.
  6320. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6321. // Cast pointer to the type we really want to load.
  6322. Type *LoadTy =
  6323. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6324. if (LoadVT.isVector())
  6325. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6326. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6327. PointerType::getUnqual(LoadTy));
  6328. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6329. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6330. return Builder.getValue(LoadCst);
  6331. }
  6332. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6333. // still constant memory, the input chain can be the entry node.
  6334. SDValue Root;
  6335. bool ConstantMemory = false;
  6336. // Do not serialize (non-volatile) loads of constant memory with anything.
  6337. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6338. Root = Builder.DAG.getEntryNode();
  6339. ConstantMemory = true;
  6340. } else {
  6341. // Do not serialize non-volatile loads against each other.
  6342. Root = Builder.DAG.getRoot();
  6343. }
  6344. SDValue Ptr = Builder.getValue(PtrVal);
  6345. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6346. Ptr, MachinePointerInfo(PtrVal),
  6347. /* Alignment = */ 1);
  6348. if (!ConstantMemory)
  6349. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6350. return LoadVal;
  6351. }
  6352. /// Record the value for an instruction that produces an integer result,
  6353. /// converting the type where necessary.
  6354. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6355. SDValue Value,
  6356. bool IsSigned) {
  6357. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6358. I.getType(), true);
  6359. if (IsSigned)
  6360. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6361. else
  6362. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6363. setValue(&I, Value);
  6364. }
  6365. /// See if we can lower a memcmp call into an optimized form. If so, return
  6366. /// true and lower it. Otherwise return false, and it will be lowered like a
  6367. /// normal call.
  6368. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6369. /// correct prototype.
  6370. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6371. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6372. const Value *Size = I.getArgOperand(2);
  6373. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6374. if (CSize && CSize->getZExtValue() == 0) {
  6375. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6376. I.getType(), true);
  6377. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6378. return true;
  6379. }
  6380. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6381. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6382. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6383. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6384. if (Res.first.getNode()) {
  6385. processIntegerCallValue(I, Res.first, true);
  6386. PendingLoads.push_back(Res.second);
  6387. return true;
  6388. }
  6389. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6390. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6391. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6392. return false;
  6393. // If the target has a fast compare for the given size, it will return a
  6394. // preferred load type for that size. Require that the load VT is legal and
  6395. // that the target supports unaligned loads of that type. Otherwise, return
  6396. // INVALID.
  6397. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6398. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6399. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6400. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6401. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6402. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6403. // TODO: Check alignment of src and dest ptrs.
  6404. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6405. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6406. if (!TLI.isTypeLegal(LVT) ||
  6407. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6408. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6409. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6410. }
  6411. return LVT;
  6412. };
  6413. // This turns into unaligned loads. We only do this if the target natively
  6414. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6415. // we'll only produce a small number of byte loads.
  6416. MVT LoadVT;
  6417. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6418. switch (NumBitsToCompare) {
  6419. default:
  6420. return false;
  6421. case 16:
  6422. LoadVT = MVT::i16;
  6423. break;
  6424. case 32:
  6425. LoadVT = MVT::i32;
  6426. break;
  6427. case 64:
  6428. case 128:
  6429. case 256:
  6430. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6431. break;
  6432. }
  6433. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6434. return false;
  6435. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6436. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6437. // Bitcast to a wide integer type if the loads are vectors.
  6438. if (LoadVT.isVector()) {
  6439. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6440. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6441. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6442. }
  6443. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6444. processIntegerCallValue(I, Cmp, false);
  6445. return true;
  6446. }
  6447. /// See if we can lower a memchr call into an optimized form. If so, return
  6448. /// true and lower it. Otherwise return false, and it will be lowered like a
  6449. /// normal call.
  6450. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6451. /// correct prototype.
  6452. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6453. const Value *Src = I.getArgOperand(0);
  6454. const Value *Char = I.getArgOperand(1);
  6455. const Value *Length = I.getArgOperand(2);
  6456. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6457. std::pair<SDValue, SDValue> Res =
  6458. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6459. getValue(Src), getValue(Char), getValue(Length),
  6460. MachinePointerInfo(Src));
  6461. if (Res.first.getNode()) {
  6462. setValue(&I, Res.first);
  6463. PendingLoads.push_back(Res.second);
  6464. return true;
  6465. }
  6466. return false;
  6467. }
  6468. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6469. /// true and lower it. Otherwise return false, and it will be lowered like a
  6470. /// normal call.
  6471. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6472. /// correct prototype.
  6473. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6474. SDValue Dst = getValue(I.getArgOperand(0));
  6475. SDValue Src = getValue(I.getArgOperand(1));
  6476. SDValue Size = getValue(I.getArgOperand(2));
  6477. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6478. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6479. unsigned Align = std::min(DstAlign, SrcAlign);
  6480. if (Align == 0) // Alignment of one or both could not be inferred.
  6481. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6482. bool isVol = false;
  6483. SDLoc sdl = getCurSDLoc();
  6484. // In the mempcpy context we need to pass in a false value for isTailCall
  6485. // because the return pointer needs to be adjusted by the size of
  6486. // the copied memory.
  6487. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6488. false, /*isTailCall=*/false,
  6489. MachinePointerInfo(I.getArgOperand(0)),
  6490. MachinePointerInfo(I.getArgOperand(1)));
  6491. assert(MC.getNode() != nullptr &&
  6492. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6493. DAG.setRoot(MC);
  6494. // Check if Size needs to be truncated or extended.
  6495. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6496. // Adjust return pointer to point just past the last dst byte.
  6497. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6498. Dst, Size);
  6499. setValue(&I, DstPlusSize);
  6500. return true;
  6501. }
  6502. /// See if we can lower a strcpy call into an optimized form. If so, return
  6503. /// true and lower it, otherwise return false and it will be lowered like a
  6504. /// normal call.
  6505. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6506. /// correct prototype.
  6507. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6508. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6509. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6510. std::pair<SDValue, SDValue> Res =
  6511. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6512. getValue(Arg0), getValue(Arg1),
  6513. MachinePointerInfo(Arg0),
  6514. MachinePointerInfo(Arg1), isStpcpy);
  6515. if (Res.first.getNode()) {
  6516. setValue(&I, Res.first);
  6517. DAG.setRoot(Res.second);
  6518. return true;
  6519. }
  6520. return false;
  6521. }
  6522. /// See if we can lower a strcmp call into an optimized form. If so, return
  6523. /// true and lower it, otherwise return false and it will be lowered like a
  6524. /// normal call.
  6525. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6526. /// correct prototype.
  6527. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6528. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6529. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6530. std::pair<SDValue, SDValue> Res =
  6531. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6532. getValue(Arg0), getValue(Arg1),
  6533. MachinePointerInfo(Arg0),
  6534. MachinePointerInfo(Arg1));
  6535. if (Res.first.getNode()) {
  6536. processIntegerCallValue(I, Res.first, true);
  6537. PendingLoads.push_back(Res.second);
  6538. return true;
  6539. }
  6540. return false;
  6541. }
  6542. /// See if we can lower a strlen call into an optimized form. If so, return
  6543. /// true and lower it, otherwise return false and it will be lowered like a
  6544. /// normal call.
  6545. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6546. /// correct prototype.
  6547. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6548. const Value *Arg0 = I.getArgOperand(0);
  6549. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6550. std::pair<SDValue, SDValue> Res =
  6551. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6552. getValue(Arg0), MachinePointerInfo(Arg0));
  6553. if (Res.first.getNode()) {
  6554. processIntegerCallValue(I, Res.first, false);
  6555. PendingLoads.push_back(Res.second);
  6556. return true;
  6557. }
  6558. return false;
  6559. }
  6560. /// See if we can lower a strnlen call into an optimized form. If so, return
  6561. /// true and lower it, otherwise return false and it will be lowered like a
  6562. /// normal call.
  6563. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6564. /// correct prototype.
  6565. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6566. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6567. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6568. std::pair<SDValue, SDValue> Res =
  6569. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6570. getValue(Arg0), getValue(Arg1),
  6571. MachinePointerInfo(Arg0));
  6572. if (Res.first.getNode()) {
  6573. processIntegerCallValue(I, Res.first, false);
  6574. PendingLoads.push_back(Res.second);
  6575. return true;
  6576. }
  6577. return false;
  6578. }
  6579. /// See if we can lower a unary floating-point operation into an SDNode with
  6580. /// the specified Opcode. If so, return true and lower it, otherwise return
  6581. /// false and it will be lowered like a normal call.
  6582. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6583. /// correct prototype.
  6584. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6585. unsigned Opcode) {
  6586. // We already checked this call's prototype; verify it doesn't modify errno.
  6587. if (!I.onlyReadsMemory())
  6588. return false;
  6589. SDValue Tmp = getValue(I.getArgOperand(0));
  6590. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6591. return true;
  6592. }
  6593. /// See if we can lower a binary floating-point operation into an SDNode with
  6594. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6595. /// false, and it will be lowered like a normal call.
  6596. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6597. /// correct prototype.
  6598. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6599. unsigned Opcode) {
  6600. // We already checked this call's prototype; verify it doesn't modify errno.
  6601. if (!I.onlyReadsMemory())
  6602. return false;
  6603. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6604. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6605. EVT VT = Tmp0.getValueType();
  6606. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6607. return true;
  6608. }
  6609. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6610. // Handle inline assembly differently.
  6611. if (isa<InlineAsm>(I.getCalledValue())) {
  6612. visitInlineAsm(&I);
  6613. return;
  6614. }
  6615. if (Function *F = I.getCalledFunction()) {
  6616. if (F->isDeclaration()) {
  6617. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6618. unsigned IID = F->getIntrinsicID();
  6619. if (!IID)
  6620. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6621. IID = II->getIntrinsicID(F);
  6622. if (IID) {
  6623. visitIntrinsicCall(I, IID);
  6624. return;
  6625. }
  6626. }
  6627. // Check for well-known libc/libm calls. If the function is internal, it
  6628. // can't be a library call. Don't do the check if marked as nobuiltin for
  6629. // some reason or the call site requires strict floating point semantics.
  6630. LibFunc Func;
  6631. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6632. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6633. LibInfo->hasOptimizedCodeGen(Func)) {
  6634. switch (Func) {
  6635. default: break;
  6636. case LibFunc_copysign:
  6637. case LibFunc_copysignf:
  6638. case LibFunc_copysignl:
  6639. // We already checked this call's prototype; verify it doesn't modify
  6640. // errno.
  6641. if (I.onlyReadsMemory()) {
  6642. SDValue LHS = getValue(I.getArgOperand(0));
  6643. SDValue RHS = getValue(I.getArgOperand(1));
  6644. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6645. LHS.getValueType(), LHS, RHS));
  6646. return;
  6647. }
  6648. break;
  6649. case LibFunc_fabs:
  6650. case LibFunc_fabsf:
  6651. case LibFunc_fabsl:
  6652. if (visitUnaryFloatCall(I, ISD::FABS))
  6653. return;
  6654. break;
  6655. case LibFunc_fmin:
  6656. case LibFunc_fminf:
  6657. case LibFunc_fminl:
  6658. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6659. return;
  6660. break;
  6661. case LibFunc_fmax:
  6662. case LibFunc_fmaxf:
  6663. case LibFunc_fmaxl:
  6664. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6665. return;
  6666. break;
  6667. case LibFunc_sin:
  6668. case LibFunc_sinf:
  6669. case LibFunc_sinl:
  6670. if (visitUnaryFloatCall(I, ISD::FSIN))
  6671. return;
  6672. break;
  6673. case LibFunc_cos:
  6674. case LibFunc_cosf:
  6675. case LibFunc_cosl:
  6676. if (visitUnaryFloatCall(I, ISD::FCOS))
  6677. return;
  6678. break;
  6679. case LibFunc_sqrt:
  6680. case LibFunc_sqrtf:
  6681. case LibFunc_sqrtl:
  6682. case LibFunc_sqrt_finite:
  6683. case LibFunc_sqrtf_finite:
  6684. case LibFunc_sqrtl_finite:
  6685. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6686. return;
  6687. break;
  6688. case LibFunc_floor:
  6689. case LibFunc_floorf:
  6690. case LibFunc_floorl:
  6691. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6692. return;
  6693. break;
  6694. case LibFunc_nearbyint:
  6695. case LibFunc_nearbyintf:
  6696. case LibFunc_nearbyintl:
  6697. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6698. return;
  6699. break;
  6700. case LibFunc_ceil:
  6701. case LibFunc_ceilf:
  6702. case LibFunc_ceill:
  6703. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6704. return;
  6705. break;
  6706. case LibFunc_rint:
  6707. case LibFunc_rintf:
  6708. case LibFunc_rintl:
  6709. if (visitUnaryFloatCall(I, ISD::FRINT))
  6710. return;
  6711. break;
  6712. case LibFunc_round:
  6713. case LibFunc_roundf:
  6714. case LibFunc_roundl:
  6715. if (visitUnaryFloatCall(I, ISD::FROUND))
  6716. return;
  6717. break;
  6718. case LibFunc_trunc:
  6719. case LibFunc_truncf:
  6720. case LibFunc_truncl:
  6721. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6722. return;
  6723. break;
  6724. case LibFunc_log2:
  6725. case LibFunc_log2f:
  6726. case LibFunc_log2l:
  6727. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6728. return;
  6729. break;
  6730. case LibFunc_exp2:
  6731. case LibFunc_exp2f:
  6732. case LibFunc_exp2l:
  6733. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6734. return;
  6735. break;
  6736. case LibFunc_memcmp:
  6737. if (visitMemCmpCall(I))
  6738. return;
  6739. break;
  6740. case LibFunc_mempcpy:
  6741. if (visitMemPCpyCall(I))
  6742. return;
  6743. break;
  6744. case LibFunc_memchr:
  6745. if (visitMemChrCall(I))
  6746. return;
  6747. break;
  6748. case LibFunc_strcpy:
  6749. if (visitStrCpyCall(I, false))
  6750. return;
  6751. break;
  6752. case LibFunc_stpcpy:
  6753. if (visitStrCpyCall(I, true))
  6754. return;
  6755. break;
  6756. case LibFunc_strcmp:
  6757. if (visitStrCmpCall(I))
  6758. return;
  6759. break;
  6760. case LibFunc_strlen:
  6761. if (visitStrLenCall(I))
  6762. return;
  6763. break;
  6764. case LibFunc_strnlen:
  6765. if (visitStrNLenCall(I))
  6766. return;
  6767. break;
  6768. }
  6769. }
  6770. }
  6771. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6772. // have to do anything here to lower funclet bundles.
  6773. assert(!I.hasOperandBundlesOtherThan(
  6774. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6775. "Cannot lower calls with arbitrary operand bundles!");
  6776. SDValue Callee = getValue(I.getCalledValue());
  6777. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6778. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6779. else
  6780. // Check if we can potentially perform a tail call. More detailed checking
  6781. // is be done within LowerCallTo, after more information about the call is
  6782. // known.
  6783. LowerCallTo(&I, Callee, I.isTailCall());
  6784. }
  6785. namespace {
  6786. /// AsmOperandInfo - This contains information for each constraint that we are
  6787. /// lowering.
  6788. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6789. public:
  6790. /// CallOperand - If this is the result output operand or a clobber
  6791. /// this is null, otherwise it is the incoming operand to the CallInst.
  6792. /// This gets modified as the asm is processed.
  6793. SDValue CallOperand;
  6794. /// AssignedRegs - If this is a register or register class operand, this
  6795. /// contains the set of register corresponding to the operand.
  6796. RegsForValue AssignedRegs;
  6797. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6798. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6799. }
  6800. /// Whether or not this operand accesses memory
  6801. bool hasMemory(const TargetLowering &TLI) const {
  6802. // Indirect operand accesses access memory.
  6803. if (isIndirect)
  6804. return true;
  6805. for (const auto &Code : Codes)
  6806. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6807. return true;
  6808. return false;
  6809. }
  6810. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6811. /// corresponds to. If there is no Value* for this operand, it returns
  6812. /// MVT::Other.
  6813. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6814. const DataLayout &DL) const {
  6815. if (!CallOperandVal) return MVT::Other;
  6816. if (isa<BasicBlock>(CallOperandVal))
  6817. return TLI.getPointerTy(DL);
  6818. llvm::Type *OpTy = CallOperandVal->getType();
  6819. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6820. // If this is an indirect operand, the operand is a pointer to the
  6821. // accessed type.
  6822. if (isIndirect) {
  6823. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6824. if (!PtrTy)
  6825. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6826. OpTy = PtrTy->getElementType();
  6827. }
  6828. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6829. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6830. if (STy->getNumElements() == 1)
  6831. OpTy = STy->getElementType(0);
  6832. // If OpTy is not a single value, it may be a struct/union that we
  6833. // can tile with integers.
  6834. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6835. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6836. switch (BitSize) {
  6837. default: break;
  6838. case 1:
  6839. case 8:
  6840. case 16:
  6841. case 32:
  6842. case 64:
  6843. case 128:
  6844. OpTy = IntegerType::get(Context, BitSize);
  6845. break;
  6846. }
  6847. }
  6848. return TLI.getValueType(DL, OpTy, true);
  6849. }
  6850. };
  6851. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6852. } // end anonymous namespace
  6853. /// Make sure that the output operand \p OpInfo and its corresponding input
  6854. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6855. /// out).
  6856. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6857. SDISelAsmOperandInfo &MatchingOpInfo,
  6858. SelectionDAG &DAG) {
  6859. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6860. return;
  6861. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6862. const auto &TLI = DAG.getTargetLoweringInfo();
  6863. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6864. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6865. OpInfo.ConstraintVT);
  6866. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6867. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6868. MatchingOpInfo.ConstraintVT);
  6869. if ((OpInfo.ConstraintVT.isInteger() !=
  6870. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6871. (MatchRC.second != InputRC.second)) {
  6872. // FIXME: error out in a more elegant fashion
  6873. report_fatal_error("Unsupported asm: input constraint"
  6874. " with a matching output constraint of"
  6875. " incompatible type!");
  6876. }
  6877. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6878. }
  6879. /// Get a direct memory input to behave well as an indirect operand.
  6880. /// This may introduce stores, hence the need for a \p Chain.
  6881. /// \return The (possibly updated) chain.
  6882. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6883. SDISelAsmOperandInfo &OpInfo,
  6884. SelectionDAG &DAG) {
  6885. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6886. // If we don't have an indirect input, put it in the constpool if we can,
  6887. // otherwise spill it to a stack slot.
  6888. // TODO: This isn't quite right. We need to handle these according to
  6889. // the addressing mode that the constraint wants. Also, this may take
  6890. // an additional register for the computation and we don't want that
  6891. // either.
  6892. // If the operand is a float, integer, or vector constant, spill to a
  6893. // constant pool entry to get its address.
  6894. const Value *OpVal = OpInfo.CallOperandVal;
  6895. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6896. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6897. OpInfo.CallOperand = DAG.getConstantPool(
  6898. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6899. return Chain;
  6900. }
  6901. // Otherwise, create a stack slot and emit a store to it before the asm.
  6902. Type *Ty = OpVal->getType();
  6903. auto &DL = DAG.getDataLayout();
  6904. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6905. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6906. MachineFunction &MF = DAG.getMachineFunction();
  6907. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6908. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6909. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6910. MachinePointerInfo::getFixedStack(MF, SSFI),
  6911. TLI.getMemValueType(DL, Ty));
  6912. OpInfo.CallOperand = StackSlot;
  6913. return Chain;
  6914. }
  6915. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6916. /// specified operand. We prefer to assign virtual registers, to allow the
  6917. /// register allocator to handle the assignment process. However, if the asm
  6918. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6919. /// allocation. This produces generally horrible, but correct, code.
  6920. ///
  6921. /// OpInfo describes the operand
  6922. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6923. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6924. SDISelAsmOperandInfo &OpInfo,
  6925. SDISelAsmOperandInfo &RefOpInfo) {
  6926. LLVMContext &Context = *DAG.getContext();
  6927. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6928. MachineFunction &MF = DAG.getMachineFunction();
  6929. SmallVector<unsigned, 4> Regs;
  6930. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6931. // No work to do for memory operations.
  6932. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6933. return;
  6934. // If this is a constraint for a single physreg, or a constraint for a
  6935. // register class, find it.
  6936. unsigned AssignedReg;
  6937. const TargetRegisterClass *RC;
  6938. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6939. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6940. // RC is unset only on failure. Return immediately.
  6941. if (!RC)
  6942. return;
  6943. // Get the actual register value type. This is important, because the user
  6944. // may have asked for (e.g.) the AX register in i32 type. We need to
  6945. // remember that AX is actually i16 to get the right extension.
  6946. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6947. if (OpInfo.ConstraintVT != MVT::Other) {
  6948. // If this is an FP operand in an integer register (or visa versa), or more
  6949. // generally if the operand value disagrees with the register class we plan
  6950. // to stick it in, fix the operand type.
  6951. //
  6952. // If this is an input value, the bitcast to the new type is done now.
  6953. // Bitcast for output value is done at the end of visitInlineAsm().
  6954. if ((OpInfo.Type == InlineAsm::isOutput ||
  6955. OpInfo.Type == InlineAsm::isInput) &&
  6956. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  6957. // Try to convert to the first EVT that the reg class contains. If the
  6958. // types are identical size, use a bitcast to convert (e.g. two differing
  6959. // vector types). Note: output bitcast is done at the end of
  6960. // visitInlineAsm().
  6961. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  6962. // Exclude indirect inputs while they are unsupported because the code
  6963. // to perform the load is missing and thus OpInfo.CallOperand still
  6964. // refers to the input address rather than the pointed-to value.
  6965. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  6966. OpInfo.CallOperand =
  6967. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  6968. OpInfo.ConstraintVT = RegVT;
  6969. // If the operand is an FP value and we want it in integer registers,
  6970. // use the corresponding integer type. This turns an f64 value into
  6971. // i64, which can be passed with two i32 values on a 32-bit machine.
  6972. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  6973. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  6974. if (OpInfo.Type == InlineAsm::isInput)
  6975. OpInfo.CallOperand =
  6976. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  6977. OpInfo.ConstraintVT = VT;
  6978. }
  6979. }
  6980. }
  6981. // No need to allocate a matching input constraint since the constraint it's
  6982. // matching to has already been allocated.
  6983. if (OpInfo.isMatchingInputConstraint())
  6984. return;
  6985. EVT ValueVT = OpInfo.ConstraintVT;
  6986. if (OpInfo.ConstraintVT == MVT::Other)
  6987. ValueVT = RegVT;
  6988. // Initialize NumRegs.
  6989. unsigned NumRegs = 1;
  6990. if (OpInfo.ConstraintVT != MVT::Other)
  6991. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  6992. // If this is a constraint for a specific physical register, like {r17},
  6993. // assign it now.
  6994. // If this associated to a specific register, initialize iterator to correct
  6995. // place. If virtual, make sure we have enough registers
  6996. // Initialize iterator if necessary
  6997. TargetRegisterClass::iterator I = RC->begin();
  6998. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  6999. // Do not check for single registers.
  7000. if (AssignedReg) {
  7001. for (; *I != AssignedReg; ++I)
  7002. assert(I != RC->end() && "AssignedReg should be member of RC");
  7003. }
  7004. for (; NumRegs; --NumRegs, ++I) {
  7005. assert(I != RC->end() && "Ran out of registers to allocate!");
  7006. auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
  7007. Regs.push_back(R);
  7008. }
  7009. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  7010. }
  7011. static unsigned
  7012. findMatchingInlineAsmOperand(unsigned OperandNo,
  7013. const std::vector<SDValue> &AsmNodeOperands) {
  7014. // Scan until we find the definition we already emitted of this operand.
  7015. unsigned CurOp = InlineAsm::Op_FirstOperand;
  7016. for (; OperandNo; --OperandNo) {
  7017. // Advance to the next operand.
  7018. unsigned OpFlag =
  7019. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7020. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7021. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7022. InlineAsm::isMemKind(OpFlag)) &&
  7023. "Skipped past definitions?");
  7024. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7025. }
  7026. return CurOp;
  7027. }
  7028. namespace {
  7029. class ExtraFlags {
  7030. unsigned Flags = 0;
  7031. public:
  7032. explicit ExtraFlags(ImmutableCallSite CS) {
  7033. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7034. if (IA->hasSideEffects())
  7035. Flags |= InlineAsm::Extra_HasSideEffects;
  7036. if (IA->isAlignStack())
  7037. Flags |= InlineAsm::Extra_IsAlignStack;
  7038. if (CS.isConvergent())
  7039. Flags |= InlineAsm::Extra_IsConvergent;
  7040. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7041. }
  7042. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7043. // Ideally, we would only check against memory constraints. However, the
  7044. // meaning of an Other constraint can be target-specific and we can't easily
  7045. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7046. // for Other constraints as well.
  7047. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7048. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7049. if (OpInfo.Type == InlineAsm::isInput)
  7050. Flags |= InlineAsm::Extra_MayLoad;
  7051. else if (OpInfo.Type == InlineAsm::isOutput)
  7052. Flags |= InlineAsm::Extra_MayStore;
  7053. else if (OpInfo.Type == InlineAsm::isClobber)
  7054. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7055. }
  7056. }
  7057. unsigned get() const { return Flags; }
  7058. };
  7059. } // end anonymous namespace
  7060. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7061. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  7062. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7063. /// ConstraintOperands - Information about all of the constraints.
  7064. SDISelAsmOperandInfoVector ConstraintOperands;
  7065. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7066. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7067. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  7068. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7069. // AsmDialect, MayLoad, MayStore).
  7070. bool HasSideEffect = IA->hasSideEffects();
  7071. ExtraFlags ExtraInfo(CS);
  7072. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7073. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7074. for (auto &T : TargetConstraints) {
  7075. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7076. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7077. // Compute the value type for each operand.
  7078. if (OpInfo.Type == InlineAsm::isInput ||
  7079. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  7080. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  7081. // Process the call argument. BasicBlocks are labels, currently appearing
  7082. // only in asm's.
  7083. const Instruction *I = CS.getInstruction();
  7084. if (isa<CallBrInst>(I) &&
  7085. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  7086. cast<CallBrInst>(I)->getNumIndirectDests())) {
  7087. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  7088. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7089. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7090. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7091. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7092. } else {
  7093. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7094. }
  7095. OpInfo.ConstraintVT =
  7096. OpInfo
  7097. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  7098. .getSimpleVT();
  7099. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7100. // The return value of the call is this value. As such, there is no
  7101. // corresponding argument.
  7102. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7103. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7104. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7105. DAG.getDataLayout(), STy->getElementType(ResNo));
  7106. } else {
  7107. assert(ResNo == 0 && "Asm only has one result!");
  7108. OpInfo.ConstraintVT =
  7109. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7110. }
  7111. ++ResNo;
  7112. } else {
  7113. OpInfo.ConstraintVT = MVT::Other;
  7114. }
  7115. if (!HasSideEffect)
  7116. HasSideEffect = OpInfo.hasMemory(TLI);
  7117. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7118. // FIXME: Could we compute this on OpInfo rather than T?
  7119. // Compute the constraint code and ConstraintType to use.
  7120. TLI.ComputeConstraintToUse(T, SDValue());
  7121. ExtraInfo.update(T);
  7122. }
  7123. // We won't need to flush pending loads if this asm doesn't touch
  7124. // memory and is nonvolatile.
  7125. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7126. bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
  7127. if (IsCallBr) {
  7128. // If this is a callbr we need to flush pending exports since inlineasm_br
  7129. // is a terminator. We need to do this before nodes are glued to
  7130. // the inlineasm_br node.
  7131. Chain = getControlRoot();
  7132. }
  7133. // Second pass over the constraints: compute which constraint option to use.
  7134. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7135. // If this is an output operand with a matching input operand, look up the
  7136. // matching input. If their types mismatch, e.g. one is an integer, the
  7137. // other is floating point, or their sizes are different, flag it as an
  7138. // error.
  7139. if (OpInfo.hasMatchingInput()) {
  7140. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7141. patchMatchingInput(OpInfo, Input, DAG);
  7142. }
  7143. // Compute the constraint code and ConstraintType to use.
  7144. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7145. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7146. OpInfo.Type == InlineAsm::isClobber)
  7147. continue;
  7148. // If this is a memory input, and if the operand is not indirect, do what we
  7149. // need to provide an address for the memory input.
  7150. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7151. !OpInfo.isIndirect) {
  7152. assert((OpInfo.isMultipleAlternative ||
  7153. (OpInfo.Type == InlineAsm::isInput)) &&
  7154. "Can only indirectify direct input operands!");
  7155. // Memory operands really want the address of the value.
  7156. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7157. // There is no longer a Value* corresponding to this operand.
  7158. OpInfo.CallOperandVal = nullptr;
  7159. // It is now an indirect operand.
  7160. OpInfo.isIndirect = true;
  7161. }
  7162. }
  7163. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7164. std::vector<SDValue> AsmNodeOperands;
  7165. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7166. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7167. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7168. // If we have a !srcloc metadata node associated with it, we want to attach
  7169. // this to the ultimately generated inline asm machineinstr. To do this, we
  7170. // pass in the third operand as this (potentially null) inline asm MDNode.
  7171. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7172. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7173. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7174. // bits as operand 3.
  7175. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7176. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7177. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7178. // this, assign virtual and physical registers for inputs and otput.
  7179. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7180. // Assign Registers.
  7181. SDISelAsmOperandInfo &RefOpInfo =
  7182. OpInfo.isMatchingInputConstraint()
  7183. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7184. : OpInfo;
  7185. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7186. switch (OpInfo.Type) {
  7187. case InlineAsm::isOutput:
  7188. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7189. (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7190. OpInfo.isIndirect)) {
  7191. unsigned ConstraintID =
  7192. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7193. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7194. "Failed to convert memory constraint code to constraint id.");
  7195. // Add information to the INLINEASM node to know about this output.
  7196. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7197. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7198. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7199. MVT::i32));
  7200. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7201. break;
  7202. } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
  7203. !OpInfo.isIndirect) ||
  7204. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7205. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7206. // Otherwise, this outputs to a register (directly for C_Register /
  7207. // C_RegisterClass, and a target-defined fashion for C_Other). Find a
  7208. // register that we can use.
  7209. if (OpInfo.AssignedRegs.Regs.empty()) {
  7210. emitInlineAsmError(
  7211. CS, "couldn't allocate output register for constraint '" +
  7212. Twine(OpInfo.ConstraintCode) + "'");
  7213. return;
  7214. }
  7215. // Add information to the INLINEASM node to know that this register is
  7216. // set.
  7217. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7218. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7219. : InlineAsm::Kind_RegDef,
  7220. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7221. }
  7222. break;
  7223. case InlineAsm::isInput: {
  7224. SDValue InOperandVal = OpInfo.CallOperand;
  7225. if (OpInfo.isMatchingInputConstraint()) {
  7226. // If this is required to match an output register we have already set,
  7227. // just use its register.
  7228. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7229. AsmNodeOperands);
  7230. unsigned OpFlag =
  7231. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7232. if (InlineAsm::isRegDefKind(OpFlag) ||
  7233. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7234. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7235. if (OpInfo.isIndirect) {
  7236. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7237. emitInlineAsmError(CS, "inline asm not supported yet:"
  7238. " don't know how to handle tied "
  7239. "indirect register inputs");
  7240. return;
  7241. }
  7242. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7243. SmallVector<unsigned, 4> Regs;
  7244. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7245. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7246. MachineRegisterInfo &RegInfo =
  7247. DAG.getMachineFunction().getRegInfo();
  7248. for (unsigned i = 0; i != NumRegs; ++i)
  7249. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7250. } else {
  7251. emitInlineAsmError(CS, "inline asm error: This value type register "
  7252. "class is not natively supported!");
  7253. return;
  7254. }
  7255. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7256. SDLoc dl = getCurSDLoc();
  7257. // Use the produced MatchedRegs object to
  7258. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7259. CS.getInstruction());
  7260. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7261. true, OpInfo.getMatchedOperand(), dl,
  7262. DAG, AsmNodeOperands);
  7263. break;
  7264. }
  7265. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7266. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7267. "Unexpected number of operands");
  7268. // Add information to the INLINEASM node to know about this input.
  7269. // See InlineAsm.h isUseOperandTiedToDef.
  7270. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7271. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7272. OpInfo.getMatchedOperand());
  7273. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7274. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7275. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7276. break;
  7277. }
  7278. // Treat indirect 'X' constraint as memory.
  7279. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  7280. OpInfo.isIndirect)
  7281. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7282. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  7283. std::vector<SDValue> Ops;
  7284. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7285. Ops, DAG);
  7286. if (Ops.empty()) {
  7287. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7288. Twine(OpInfo.ConstraintCode) + "'");
  7289. return;
  7290. }
  7291. // Add information to the INLINEASM node to know about this input.
  7292. unsigned ResOpType =
  7293. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7294. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7295. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7296. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7297. break;
  7298. }
  7299. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7300. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7301. assert(InOperandVal.getValueType() ==
  7302. TLI.getPointerTy(DAG.getDataLayout()) &&
  7303. "Memory operands expect pointer values");
  7304. unsigned ConstraintID =
  7305. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7306. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7307. "Failed to convert memory constraint code to constraint id.");
  7308. // Add information to the INLINEASM node to know about this input.
  7309. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7310. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7311. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7312. getCurSDLoc(),
  7313. MVT::i32));
  7314. AsmNodeOperands.push_back(InOperandVal);
  7315. break;
  7316. }
  7317. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7318. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  7319. "Unknown constraint type!");
  7320. // TODO: Support this.
  7321. if (OpInfo.isIndirect) {
  7322. emitInlineAsmError(
  7323. CS, "Don't know how to handle indirect register inputs yet "
  7324. "for constraint '" +
  7325. Twine(OpInfo.ConstraintCode) + "'");
  7326. return;
  7327. }
  7328. // Copy the input into the appropriate registers.
  7329. if (OpInfo.AssignedRegs.Regs.empty()) {
  7330. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7331. Twine(OpInfo.ConstraintCode) + "'");
  7332. return;
  7333. }
  7334. SDLoc dl = getCurSDLoc();
  7335. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7336. Chain, &Flag, CS.getInstruction());
  7337. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7338. dl, DAG, AsmNodeOperands);
  7339. break;
  7340. }
  7341. case InlineAsm::isClobber:
  7342. // Add the clobbered value to the operand list, so that the register
  7343. // allocator is aware that the physreg got clobbered.
  7344. if (!OpInfo.AssignedRegs.Regs.empty())
  7345. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7346. false, 0, getCurSDLoc(), DAG,
  7347. AsmNodeOperands);
  7348. break;
  7349. }
  7350. }
  7351. // Finish up input operands. Set the input chain and add the flag last.
  7352. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7353. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7354. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7355. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7356. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7357. Flag = Chain.getValue(1);
  7358. // Do additional work to generate outputs.
  7359. SmallVector<EVT, 1> ResultVTs;
  7360. SmallVector<SDValue, 1> ResultValues;
  7361. SmallVector<SDValue, 8> OutChains;
  7362. llvm::Type *CSResultType = CS.getType();
  7363. ArrayRef<Type *> ResultTypes;
  7364. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7365. ResultTypes = StructResult->elements();
  7366. else if (!CSResultType->isVoidTy())
  7367. ResultTypes = makeArrayRef(CSResultType);
  7368. auto CurResultType = ResultTypes.begin();
  7369. auto handleRegAssign = [&](SDValue V) {
  7370. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7371. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7372. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7373. ++CurResultType;
  7374. // If the type of the inline asm call site return value is different but has
  7375. // same size as the type of the asm output bitcast it. One example of this
  7376. // is for vectors with different width / number of elements. This can
  7377. // happen for register classes that can contain multiple different value
  7378. // types. The preg or vreg allocated may not have the same VT as was
  7379. // expected.
  7380. //
  7381. // This can also happen for a return value that disagrees with the register
  7382. // class it is put in, eg. a double in a general-purpose register on a
  7383. // 32-bit machine.
  7384. if (ResultVT != V.getValueType() &&
  7385. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7386. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7387. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7388. V.getValueType().isInteger()) {
  7389. // If a result value was tied to an input value, the computed result
  7390. // may have a wider width than the expected result. Extract the
  7391. // relevant portion.
  7392. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7393. }
  7394. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7395. ResultVTs.push_back(ResultVT);
  7396. ResultValues.push_back(V);
  7397. };
  7398. // Deal with output operands.
  7399. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7400. if (OpInfo.Type == InlineAsm::isOutput) {
  7401. SDValue Val;
  7402. // Skip trivial output operands.
  7403. if (OpInfo.AssignedRegs.Regs.empty())
  7404. continue;
  7405. switch (OpInfo.ConstraintType) {
  7406. case TargetLowering::C_Register:
  7407. case TargetLowering::C_RegisterClass:
  7408. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7409. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7410. break;
  7411. case TargetLowering::C_Other:
  7412. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7413. OpInfo, DAG);
  7414. break;
  7415. case TargetLowering::C_Memory:
  7416. break; // Already handled.
  7417. case TargetLowering::C_Unknown:
  7418. assert(false && "Unexpected unknown constraint");
  7419. }
  7420. // Indirect output manifest as stores. Record output chains.
  7421. if (OpInfo.isIndirect) {
  7422. const Value *Ptr = OpInfo.CallOperandVal;
  7423. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7424. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7425. MachinePointerInfo(Ptr));
  7426. OutChains.push_back(Store);
  7427. } else {
  7428. // generate CopyFromRegs to associated registers.
  7429. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7430. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7431. for (const SDValue &V : Val->op_values())
  7432. handleRegAssign(V);
  7433. } else
  7434. handleRegAssign(Val);
  7435. }
  7436. }
  7437. }
  7438. // Set results.
  7439. if (!ResultValues.empty()) {
  7440. assert(CurResultType == ResultTypes.end() &&
  7441. "Mismatch in number of ResultTypes");
  7442. assert(ResultValues.size() == ResultTypes.size() &&
  7443. "Mismatch in number of output operands in asm result");
  7444. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7445. DAG.getVTList(ResultVTs), ResultValues);
  7446. setValue(CS.getInstruction(), V);
  7447. }
  7448. // Collect store chains.
  7449. if (!OutChains.empty())
  7450. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7451. // Only Update Root if inline assembly has a memory effect.
  7452. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
  7453. DAG.setRoot(Chain);
  7454. }
  7455. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7456. const Twine &Message) {
  7457. LLVMContext &Ctx = *DAG.getContext();
  7458. Ctx.emitError(CS.getInstruction(), Message);
  7459. // Make sure we leave the DAG in a valid state
  7460. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7461. SmallVector<EVT, 1> ValueVTs;
  7462. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7463. if (ValueVTs.empty())
  7464. return;
  7465. SmallVector<SDValue, 1> Ops;
  7466. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7467. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7468. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7469. }
  7470. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7471. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7472. MVT::Other, getRoot(),
  7473. getValue(I.getArgOperand(0)),
  7474. DAG.getSrcValue(I.getArgOperand(0))));
  7475. }
  7476. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7477. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7478. const DataLayout &DL = DAG.getDataLayout();
  7479. SDValue V = DAG.getVAArg(
  7480. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  7481. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  7482. DL.getABITypeAlignment(I.getType()));
  7483. DAG.setRoot(V.getValue(1));
  7484. if (I.getType()->isPointerTy())
  7485. V = DAG.getPtrExtOrTrunc(
  7486. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  7487. setValue(&I, V);
  7488. }
  7489. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7490. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7491. MVT::Other, getRoot(),
  7492. getValue(I.getArgOperand(0)),
  7493. DAG.getSrcValue(I.getArgOperand(0))));
  7494. }
  7495. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7496. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7497. MVT::Other, getRoot(),
  7498. getValue(I.getArgOperand(0)),
  7499. getValue(I.getArgOperand(1)),
  7500. DAG.getSrcValue(I.getArgOperand(0)),
  7501. DAG.getSrcValue(I.getArgOperand(1))));
  7502. }
  7503. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7504. const Instruction &I,
  7505. SDValue Op) {
  7506. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7507. if (!Range)
  7508. return Op;
  7509. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7510. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7511. return Op;
  7512. APInt Lo = CR.getUnsignedMin();
  7513. if (!Lo.isMinValue())
  7514. return Op;
  7515. APInt Hi = CR.getUnsignedMax();
  7516. unsigned Bits = std::max(Hi.getActiveBits(),
  7517. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7518. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7519. SDLoc SL = getCurSDLoc();
  7520. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7521. DAG.getValueType(SmallVT));
  7522. unsigned NumVals = Op.getNode()->getNumValues();
  7523. if (NumVals == 1)
  7524. return ZExt;
  7525. SmallVector<SDValue, 4> Ops;
  7526. Ops.push_back(ZExt);
  7527. for (unsigned I = 1; I != NumVals; ++I)
  7528. Ops.push_back(Op.getValue(I));
  7529. return DAG.getMergeValues(Ops, SL);
  7530. }
  7531. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7532. /// the call being lowered.
  7533. ///
  7534. /// This is a helper for lowering intrinsics that follow a target calling
  7535. /// convention or require stack pointer adjustment. Only a subset of the
  7536. /// intrinsic's operands need to participate in the calling convention.
  7537. void SelectionDAGBuilder::populateCallLoweringInfo(
  7538. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7539. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7540. bool IsPatchPoint) {
  7541. TargetLowering::ArgListTy Args;
  7542. Args.reserve(NumArgs);
  7543. // Populate the argument list.
  7544. // Attributes for args start at offset 1, after the return attribute.
  7545. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7546. ArgI != ArgE; ++ArgI) {
  7547. const Value *V = Call->getOperand(ArgI);
  7548. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7549. TargetLowering::ArgListEntry Entry;
  7550. Entry.Node = getValue(V);
  7551. Entry.Ty = V->getType();
  7552. Entry.setAttributes(Call, ArgI);
  7553. Args.push_back(Entry);
  7554. }
  7555. CLI.setDebugLoc(getCurSDLoc())
  7556. .setChain(getRoot())
  7557. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7558. .setDiscardResult(Call->use_empty())
  7559. .setIsPatchPoint(IsPatchPoint);
  7560. }
  7561. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7562. /// or patchpoint target node's operand list.
  7563. ///
  7564. /// Constants are converted to TargetConstants purely as an optimization to
  7565. /// avoid constant materialization and register allocation.
  7566. ///
  7567. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7568. /// generate addess computation nodes, and so ExpandISelPseudo can convert the
  7569. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7570. /// address materialization and register allocation, but may also be required
  7571. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7572. /// alloca in the entry block, then the runtime may assume that the alloca's
  7573. /// StackMap location can be read immediately after compilation and that the
  7574. /// location is valid at any point during execution (this is similar to the
  7575. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7576. /// only available in a register, then the runtime would need to trap when
  7577. /// execution reaches the StackMap in order to read the alloca's location.
  7578. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7579. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7580. SelectionDAGBuilder &Builder) {
  7581. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7582. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7583. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7584. Ops.push_back(
  7585. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7586. Ops.push_back(
  7587. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7588. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7589. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7590. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7591. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7592. } else
  7593. Ops.push_back(OpVal);
  7594. }
  7595. }
  7596. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7597. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7598. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7599. // [live variables...])
  7600. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7601. SDValue Chain, InFlag, Callee, NullPtr;
  7602. SmallVector<SDValue, 32> Ops;
  7603. SDLoc DL = getCurSDLoc();
  7604. Callee = getValue(CI.getCalledValue());
  7605. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7606. // The stackmap intrinsic only records the live variables (the arguemnts
  7607. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7608. // intrinsic, this won't be lowered to a function call. This means we don't
  7609. // have to worry about calling conventions and target specific lowering code.
  7610. // Instead we perform the call lowering right here.
  7611. //
  7612. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7613. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7614. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7615. //
  7616. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7617. InFlag = Chain.getValue(1);
  7618. // Add the <id> and <numBytes> constants.
  7619. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7620. Ops.push_back(DAG.getTargetConstant(
  7621. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7622. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7623. Ops.push_back(DAG.getTargetConstant(
  7624. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7625. MVT::i32));
  7626. // Push live variables for the stack map.
  7627. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7628. // We are not pushing any register mask info here on the operands list,
  7629. // because the stackmap doesn't clobber anything.
  7630. // Push the chain and the glue flag.
  7631. Ops.push_back(Chain);
  7632. Ops.push_back(InFlag);
  7633. // Create the STACKMAP node.
  7634. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7635. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7636. Chain = SDValue(SM, 0);
  7637. InFlag = Chain.getValue(1);
  7638. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7639. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7640. // Set the root to the target-lowered call chain.
  7641. DAG.setRoot(Chain);
  7642. // Inform the Frame Information that we have a stackmap in this function.
  7643. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7644. }
  7645. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7646. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7647. const BasicBlock *EHPadBB) {
  7648. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7649. // i32 <numBytes>,
  7650. // i8* <target>,
  7651. // i32 <numArgs>,
  7652. // [Args...],
  7653. // [live variables...])
  7654. CallingConv::ID CC = CS.getCallingConv();
  7655. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7656. bool HasDef = !CS->getType()->isVoidTy();
  7657. SDLoc dl = getCurSDLoc();
  7658. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7659. // Handle immediate and symbolic callees.
  7660. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7661. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7662. /*isTarget=*/true);
  7663. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7664. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7665. SDLoc(SymbolicCallee),
  7666. SymbolicCallee->getValueType(0));
  7667. // Get the real number of arguments participating in the call <numArgs>
  7668. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7669. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7670. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7671. // Intrinsics include all meta-operands up to but not including CC.
  7672. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7673. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7674. "Not enough arguments provided to the patchpoint intrinsic");
  7675. // For AnyRegCC the arguments are lowered later on manually.
  7676. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7677. Type *ReturnTy =
  7678. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7679. TargetLowering::CallLoweringInfo CLI(DAG);
  7680. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7681. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7682. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7683. SDNode *CallEnd = Result.second.getNode();
  7684. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7685. CallEnd = CallEnd->getOperand(0).getNode();
  7686. /// Get a call instruction from the call sequence chain.
  7687. /// Tail calls are not allowed.
  7688. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7689. "Expected a callseq node.");
  7690. SDNode *Call = CallEnd->getOperand(0).getNode();
  7691. bool HasGlue = Call->getGluedNode();
  7692. // Replace the target specific call node with the patchable intrinsic.
  7693. SmallVector<SDValue, 8> Ops;
  7694. // Add the <id> and <numBytes> constants.
  7695. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7696. Ops.push_back(DAG.getTargetConstant(
  7697. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7698. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7699. Ops.push_back(DAG.getTargetConstant(
  7700. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7701. MVT::i32));
  7702. // Add the callee.
  7703. Ops.push_back(Callee);
  7704. // Adjust <numArgs> to account for any arguments that have been passed on the
  7705. // stack instead.
  7706. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7707. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7708. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7709. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7710. // Add the calling convention
  7711. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7712. // Add the arguments we omitted previously. The register allocator should
  7713. // place these in any free register.
  7714. if (IsAnyRegCC)
  7715. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7716. Ops.push_back(getValue(CS.getArgument(i)));
  7717. // Push the arguments from the call instruction up to the register mask.
  7718. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7719. Ops.append(Call->op_begin() + 2, e);
  7720. // Push live variables for the stack map.
  7721. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7722. // Push the register mask info.
  7723. if (HasGlue)
  7724. Ops.push_back(*(Call->op_end()-2));
  7725. else
  7726. Ops.push_back(*(Call->op_end()-1));
  7727. // Push the chain (this is originally the first operand of the call, but
  7728. // becomes now the last or second to last operand).
  7729. Ops.push_back(*(Call->op_begin()));
  7730. // Push the glue flag (last operand).
  7731. if (HasGlue)
  7732. Ops.push_back(*(Call->op_end()-1));
  7733. SDVTList NodeTys;
  7734. if (IsAnyRegCC && HasDef) {
  7735. // Create the return types based on the intrinsic definition
  7736. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7737. SmallVector<EVT, 3> ValueVTs;
  7738. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7739. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7740. // There is always a chain and a glue type at the end
  7741. ValueVTs.push_back(MVT::Other);
  7742. ValueVTs.push_back(MVT::Glue);
  7743. NodeTys = DAG.getVTList(ValueVTs);
  7744. } else
  7745. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7746. // Replace the target specific call node with a PATCHPOINT node.
  7747. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7748. dl, NodeTys, Ops);
  7749. // Update the NodeMap.
  7750. if (HasDef) {
  7751. if (IsAnyRegCC)
  7752. setValue(CS.getInstruction(), SDValue(MN, 0));
  7753. else
  7754. setValue(CS.getInstruction(), Result.first);
  7755. }
  7756. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7757. // call sequence. Furthermore the location of the chain and glue can change
  7758. // when the AnyReg calling convention is used and the intrinsic returns a
  7759. // value.
  7760. if (IsAnyRegCC && HasDef) {
  7761. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7762. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7763. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7764. } else
  7765. DAG.ReplaceAllUsesWith(Call, MN);
  7766. DAG.DeleteNode(Call);
  7767. // Inform the Frame Information that we have a patchpoint in this function.
  7768. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7769. }
  7770. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7771. unsigned Intrinsic) {
  7772. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7773. SDValue Op1 = getValue(I.getArgOperand(0));
  7774. SDValue Op2;
  7775. if (I.getNumArgOperands() > 1)
  7776. Op2 = getValue(I.getArgOperand(1));
  7777. SDLoc dl = getCurSDLoc();
  7778. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7779. SDValue Res;
  7780. FastMathFlags FMF;
  7781. if (isa<FPMathOperator>(I))
  7782. FMF = I.getFastMathFlags();
  7783. switch (Intrinsic) {
  7784. case Intrinsic::experimental_vector_reduce_fadd:
  7785. if (FMF.isFast())
  7786. Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
  7787. else
  7788. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7789. break;
  7790. case Intrinsic::experimental_vector_reduce_fmul:
  7791. if (FMF.isFast())
  7792. Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
  7793. else
  7794. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7795. break;
  7796. case Intrinsic::experimental_vector_reduce_add:
  7797. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7798. break;
  7799. case Intrinsic::experimental_vector_reduce_mul:
  7800. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7801. break;
  7802. case Intrinsic::experimental_vector_reduce_and:
  7803. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7804. break;
  7805. case Intrinsic::experimental_vector_reduce_or:
  7806. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7807. break;
  7808. case Intrinsic::experimental_vector_reduce_xor:
  7809. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7810. break;
  7811. case Intrinsic::experimental_vector_reduce_smax:
  7812. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7813. break;
  7814. case Intrinsic::experimental_vector_reduce_smin:
  7815. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7816. break;
  7817. case Intrinsic::experimental_vector_reduce_umax:
  7818. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7819. break;
  7820. case Intrinsic::experimental_vector_reduce_umin:
  7821. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7822. break;
  7823. case Intrinsic::experimental_vector_reduce_fmax:
  7824. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7825. break;
  7826. case Intrinsic::experimental_vector_reduce_fmin:
  7827. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7828. break;
  7829. default:
  7830. llvm_unreachable("Unhandled vector reduce intrinsic");
  7831. }
  7832. setValue(&I, Res);
  7833. }
  7834. /// Returns an AttributeList representing the attributes applied to the return
  7835. /// value of the given call.
  7836. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7837. SmallVector<Attribute::AttrKind, 2> Attrs;
  7838. if (CLI.RetSExt)
  7839. Attrs.push_back(Attribute::SExt);
  7840. if (CLI.RetZExt)
  7841. Attrs.push_back(Attribute::ZExt);
  7842. if (CLI.IsInReg)
  7843. Attrs.push_back(Attribute::InReg);
  7844. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7845. Attrs);
  7846. }
  7847. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7848. /// implementation, which just calls LowerCall.
  7849. /// FIXME: When all targets are
  7850. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7851. std::pair<SDValue, SDValue>
  7852. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7853. // Handle the incoming return values from the call.
  7854. CLI.Ins.clear();
  7855. Type *OrigRetTy = CLI.RetTy;
  7856. SmallVector<EVT, 4> RetTys;
  7857. SmallVector<uint64_t, 4> Offsets;
  7858. auto &DL = CLI.DAG.getDataLayout();
  7859. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7860. if (CLI.IsPostTypeLegalization) {
  7861. // If we are lowering a libcall after legalization, split the return type.
  7862. SmallVector<EVT, 4> OldRetTys;
  7863. SmallVector<uint64_t, 4> OldOffsets;
  7864. RetTys.swap(OldRetTys);
  7865. Offsets.swap(OldOffsets);
  7866. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7867. EVT RetVT = OldRetTys[i];
  7868. uint64_t Offset = OldOffsets[i];
  7869. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7870. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7871. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7872. RetTys.append(NumRegs, RegisterVT);
  7873. for (unsigned j = 0; j != NumRegs; ++j)
  7874. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7875. }
  7876. }
  7877. SmallVector<ISD::OutputArg, 4> Outs;
  7878. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7879. bool CanLowerReturn =
  7880. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7881. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7882. SDValue DemoteStackSlot;
  7883. int DemoteStackIdx = -100;
  7884. if (!CanLowerReturn) {
  7885. // FIXME: equivalent assert?
  7886. // assert(!CS.hasInAllocaArgument() &&
  7887. // "sret demotion is incompatible with inalloca");
  7888. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7889. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7890. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7891. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7892. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7893. DL.getAllocaAddrSpace());
  7894. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7895. ArgListEntry Entry;
  7896. Entry.Node = DemoteStackSlot;
  7897. Entry.Ty = StackSlotPtrType;
  7898. Entry.IsSExt = false;
  7899. Entry.IsZExt = false;
  7900. Entry.IsInReg = false;
  7901. Entry.IsSRet = true;
  7902. Entry.IsNest = false;
  7903. Entry.IsByVal = false;
  7904. Entry.IsReturned = false;
  7905. Entry.IsSwiftSelf = false;
  7906. Entry.IsSwiftError = false;
  7907. Entry.Alignment = Align;
  7908. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7909. CLI.NumFixedArgs += 1;
  7910. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7911. // sret demotion isn't compatible with tail-calls, since the sret argument
  7912. // points into the callers stack frame.
  7913. CLI.IsTailCall = false;
  7914. } else {
  7915. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7916. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  7917. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7918. ISD::ArgFlagsTy Flags;
  7919. if (NeedsRegBlock) {
  7920. Flags.setInConsecutiveRegs();
  7921. if (I == RetTys.size() - 1)
  7922. Flags.setInConsecutiveRegsLast();
  7923. }
  7924. EVT VT = RetTys[I];
  7925. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7926. CLI.CallConv, VT);
  7927. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  7928. CLI.CallConv, VT);
  7929. for (unsigned i = 0; i != NumRegs; ++i) {
  7930. ISD::InputArg MyFlags;
  7931. MyFlags.Flags = Flags;
  7932. MyFlags.VT = RegisterVT;
  7933. MyFlags.ArgVT = VT;
  7934. MyFlags.Used = CLI.IsReturnValueUsed;
  7935. if (CLI.RetTy->isPointerTy()) {
  7936. MyFlags.Flags.setPointer();
  7937. MyFlags.Flags.setPointerAddrSpace(
  7938. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  7939. }
  7940. if (CLI.RetSExt)
  7941. MyFlags.Flags.setSExt();
  7942. if (CLI.RetZExt)
  7943. MyFlags.Flags.setZExt();
  7944. if (CLI.IsInReg)
  7945. MyFlags.Flags.setInReg();
  7946. CLI.Ins.push_back(MyFlags);
  7947. }
  7948. }
  7949. }
  7950. // We push in swifterror return as the last element of CLI.Ins.
  7951. ArgListTy &Args = CLI.getArgs();
  7952. if (supportSwiftError()) {
  7953. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7954. if (Args[i].IsSwiftError) {
  7955. ISD::InputArg MyFlags;
  7956. MyFlags.VT = getPointerTy(DL);
  7957. MyFlags.ArgVT = EVT(getPointerTy(DL));
  7958. MyFlags.Flags.setSwiftError();
  7959. CLI.Ins.push_back(MyFlags);
  7960. }
  7961. }
  7962. }
  7963. // Handle all of the outgoing arguments.
  7964. CLI.Outs.clear();
  7965. CLI.OutVals.clear();
  7966. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  7967. SmallVector<EVT, 4> ValueVTs;
  7968. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  7969. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  7970. Type *FinalType = Args[i].Ty;
  7971. if (Args[i].IsByVal)
  7972. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  7973. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7974. FinalType, CLI.CallConv, CLI.IsVarArg);
  7975. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  7976. ++Value) {
  7977. EVT VT = ValueVTs[Value];
  7978. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  7979. SDValue Op = SDValue(Args[i].Node.getNode(),
  7980. Args[i].Node.getResNo() + Value);
  7981. ISD::ArgFlagsTy Flags;
  7982. // Certain targets (such as MIPS), may have a different ABI alignment
  7983. // for a type depending on the context. Give the target a chance to
  7984. // specify the alignment it wants.
  7985. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  7986. if (Args[i].Ty->isPointerTy()) {
  7987. Flags.setPointer();
  7988. Flags.setPointerAddrSpace(
  7989. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  7990. }
  7991. if (Args[i].IsZExt)
  7992. Flags.setZExt();
  7993. if (Args[i].IsSExt)
  7994. Flags.setSExt();
  7995. if (Args[i].IsInReg) {
  7996. // If we are using vectorcall calling convention, a structure that is
  7997. // passed InReg - is surely an HVA
  7998. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  7999. isa<StructType>(FinalType)) {
  8000. // The first value of a structure is marked
  8001. if (0 == Value)
  8002. Flags.setHvaStart();
  8003. Flags.setHva();
  8004. }
  8005. // Set InReg Flag
  8006. Flags.setInReg();
  8007. }
  8008. if (Args[i].IsSRet)
  8009. Flags.setSRet();
  8010. if (Args[i].IsSwiftSelf)
  8011. Flags.setSwiftSelf();
  8012. if (Args[i].IsSwiftError)
  8013. Flags.setSwiftError();
  8014. if (Args[i].IsByVal)
  8015. Flags.setByVal();
  8016. if (Args[i].IsInAlloca) {
  8017. Flags.setInAlloca();
  8018. // Set the byval flag for CCAssignFn callbacks that don't know about
  8019. // inalloca. This way we can know how many bytes we should've allocated
  8020. // and how many bytes a callee cleanup function will pop. If we port
  8021. // inalloca to more targets, we'll have to add custom inalloca handling
  8022. // in the various CC lowering callbacks.
  8023. Flags.setByVal();
  8024. }
  8025. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  8026. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  8027. Type *ElementTy = Ty->getElementType();
  8028. unsigned FrameSize = DL.getTypeAllocSize(
  8029. Args[i].ByValType ? Args[i].ByValType : ElementTy);
  8030. Flags.setByValSize(FrameSize);
  8031. // info is not there but there are cases it cannot get right.
  8032. unsigned FrameAlign;
  8033. if (Args[i].Alignment)
  8034. FrameAlign = Args[i].Alignment;
  8035. else
  8036. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  8037. Flags.setByValAlign(FrameAlign);
  8038. }
  8039. if (Args[i].IsNest)
  8040. Flags.setNest();
  8041. if (NeedsRegBlock)
  8042. Flags.setInConsecutiveRegs();
  8043. Flags.setOrigAlign(OriginalAlignment);
  8044. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8045. CLI.CallConv, VT);
  8046. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8047. CLI.CallConv, VT);
  8048. SmallVector<SDValue, 4> Parts(NumParts);
  8049. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8050. if (Args[i].IsSExt)
  8051. ExtendKind = ISD::SIGN_EXTEND;
  8052. else if (Args[i].IsZExt)
  8053. ExtendKind = ISD::ZERO_EXTEND;
  8054. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8055. // for now.
  8056. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8057. CanLowerReturn) {
  8058. assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
  8059. "unexpected use of 'returned'");
  8060. // Before passing 'returned' to the target lowering code, ensure that
  8061. // either the register MVT and the actual EVT are the same size or that
  8062. // the return value and argument are extended in the same way; in these
  8063. // cases it's safe to pass the argument register value unchanged as the
  8064. // return register value (although it's at the target's option whether
  8065. // to do so)
  8066. // TODO: allow code generation to take advantage of partially preserved
  8067. // registers rather than clobbering the entire register when the
  8068. // parameter extension method is not compatible with the return
  8069. // extension method
  8070. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8071. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8072. CLI.RetZExt == Args[i].IsZExt))
  8073. Flags.setReturned();
  8074. }
  8075. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  8076. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  8077. for (unsigned j = 0; j != NumParts; ++j) {
  8078. // if it isn't first piece, alignment must be 1
  8079. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  8080. i < CLI.NumFixedArgs,
  8081. i, j*Parts[j].getValueType().getStoreSize());
  8082. if (NumParts > 1 && j == 0)
  8083. MyFlags.Flags.setSplit();
  8084. else if (j != 0) {
  8085. MyFlags.Flags.setOrigAlign(1);
  8086. if (j == NumParts - 1)
  8087. MyFlags.Flags.setSplitEnd();
  8088. }
  8089. CLI.Outs.push_back(MyFlags);
  8090. CLI.OutVals.push_back(Parts[j]);
  8091. }
  8092. if (NeedsRegBlock && Value == NumValues - 1)
  8093. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8094. }
  8095. }
  8096. SmallVector<SDValue, 4> InVals;
  8097. CLI.Chain = LowerCall(CLI, InVals);
  8098. // Update CLI.InVals to use outside of this function.
  8099. CLI.InVals = InVals;
  8100. // Verify that the target's LowerCall behaved as expected.
  8101. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8102. "LowerCall didn't return a valid chain!");
  8103. assert((!CLI.IsTailCall || InVals.empty()) &&
  8104. "LowerCall emitted a return value for a tail call!");
  8105. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8106. "LowerCall didn't emit the correct number of values!");
  8107. // For a tail call, the return value is merely live-out and there aren't
  8108. // any nodes in the DAG representing it. Return a special value to
  8109. // indicate that a tail call has been emitted and no more Instructions
  8110. // should be processed in the current block.
  8111. if (CLI.IsTailCall) {
  8112. CLI.DAG.setRoot(CLI.Chain);
  8113. return std::make_pair(SDValue(), SDValue());
  8114. }
  8115. #ifndef NDEBUG
  8116. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8117. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8118. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8119. "LowerCall emitted a value with the wrong type!");
  8120. }
  8121. #endif
  8122. SmallVector<SDValue, 4> ReturnValues;
  8123. if (!CanLowerReturn) {
  8124. // The instruction result is the result of loading from the
  8125. // hidden sret parameter.
  8126. SmallVector<EVT, 1> PVTs;
  8127. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8128. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8129. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8130. EVT PtrVT = PVTs[0];
  8131. unsigned NumValues = RetTys.size();
  8132. ReturnValues.resize(NumValues);
  8133. SmallVector<SDValue, 4> Chains(NumValues);
  8134. // An aggregate return value cannot wrap around the address space, so
  8135. // offsets to its parts don't wrap either.
  8136. SDNodeFlags Flags;
  8137. Flags.setNoUnsignedWrap(true);
  8138. for (unsigned i = 0; i < NumValues; ++i) {
  8139. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8140. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8141. PtrVT), Flags);
  8142. SDValue L = CLI.DAG.getLoad(
  8143. RetTys[i], CLI.DL, CLI.Chain, Add,
  8144. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8145. DemoteStackIdx, Offsets[i]),
  8146. /* Alignment = */ 1);
  8147. ReturnValues[i] = L;
  8148. Chains[i] = L.getValue(1);
  8149. }
  8150. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8151. } else {
  8152. // Collect the legal value parts into potentially illegal values
  8153. // that correspond to the original function's return values.
  8154. Optional<ISD::NodeType> AssertOp;
  8155. if (CLI.RetSExt)
  8156. AssertOp = ISD::AssertSext;
  8157. else if (CLI.RetZExt)
  8158. AssertOp = ISD::AssertZext;
  8159. unsigned CurReg = 0;
  8160. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8161. EVT VT = RetTys[I];
  8162. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8163. CLI.CallConv, VT);
  8164. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8165. CLI.CallConv, VT);
  8166. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8167. NumRegs, RegisterVT, VT, nullptr,
  8168. CLI.CallConv, AssertOp));
  8169. CurReg += NumRegs;
  8170. }
  8171. // For a function returning void, there is no return value. We can't create
  8172. // such a node, so we just return a null return value in that case. In
  8173. // that case, nothing will actually look at the value.
  8174. if (ReturnValues.empty())
  8175. return std::make_pair(SDValue(), CLI.Chain);
  8176. }
  8177. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8178. CLI.DAG.getVTList(RetTys), ReturnValues);
  8179. return std::make_pair(Res, CLI.Chain);
  8180. }
  8181. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8182. SmallVectorImpl<SDValue> &Results,
  8183. SelectionDAG &DAG) const {
  8184. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8185. Results.push_back(Res);
  8186. }
  8187. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8188. llvm_unreachable("LowerOperation not implemented for this target!");
  8189. }
  8190. void
  8191. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8192. SDValue Op = getNonRegisterValue(V);
  8193. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8194. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8195. "Copy from a reg to the same reg!");
  8196. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  8197. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8198. // If this is an InlineAsm we have to match the registers required, not the
  8199. // notional registers required by the type.
  8200. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8201. None); // This is not an ABI copy.
  8202. SDValue Chain = DAG.getEntryNode();
  8203. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8204. FuncInfo.PreferredExtendType.end())
  8205. ? ISD::ANY_EXTEND
  8206. : FuncInfo.PreferredExtendType[V];
  8207. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8208. PendingExports.push_back(Chain);
  8209. }
  8210. #include "llvm/CodeGen/SelectionDAGISel.h"
  8211. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8212. /// entry block, return true. This includes arguments used by switches, since
  8213. /// the switch may expand into multiple basic blocks.
  8214. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8215. // With FastISel active, we may be splitting blocks, so force creation
  8216. // of virtual registers for all non-dead arguments.
  8217. if (FastISel)
  8218. return A->use_empty();
  8219. const BasicBlock &Entry = A->getParent()->front();
  8220. for (const User *U : A->users())
  8221. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8222. return false; // Use not in entry block.
  8223. return true;
  8224. }
  8225. using ArgCopyElisionMapTy =
  8226. DenseMap<const Argument *,
  8227. std::pair<const AllocaInst *, const StoreInst *>>;
  8228. /// Scan the entry block of the function in FuncInfo for arguments that look
  8229. /// like copies into a local alloca. Record any copied arguments in
  8230. /// ArgCopyElisionCandidates.
  8231. static void
  8232. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8233. FunctionLoweringInfo *FuncInfo,
  8234. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8235. // Record the state of every static alloca used in the entry block. Argument
  8236. // allocas are all used in the entry block, so we need approximately as many
  8237. // entries as we have arguments.
  8238. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8239. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8240. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8241. StaticAllocas.reserve(NumArgs * 2);
  8242. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8243. if (!V)
  8244. return nullptr;
  8245. V = V->stripPointerCasts();
  8246. const auto *AI = dyn_cast<AllocaInst>(V);
  8247. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8248. return nullptr;
  8249. auto Iter = StaticAllocas.insert({AI, Unknown});
  8250. return &Iter.first->second;
  8251. };
  8252. // Look for stores of arguments to static allocas. Look through bitcasts and
  8253. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8254. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8255. // unanalyzed store might write it.
  8256. // FIXME: Handle structs initialized with multiple stores.
  8257. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8258. // Look for stores, and handle non-store uses conservatively.
  8259. const auto *SI = dyn_cast<StoreInst>(&I);
  8260. if (!SI) {
  8261. // We will look through cast uses, so ignore them completely.
  8262. if (I.isCast())
  8263. continue;
  8264. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8265. if (isa<DbgInfoIntrinsic>(I))
  8266. continue;
  8267. // This is an unknown instruction. Assume it escapes or writes to all
  8268. // static alloca operands.
  8269. for (const Use &U : I.operands()) {
  8270. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8271. *Info = StaticAllocaInfo::Clobbered;
  8272. }
  8273. continue;
  8274. }
  8275. // If the stored value is a static alloca, mark it as escaped.
  8276. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8277. *Info = StaticAllocaInfo::Clobbered;
  8278. // Check if the destination is a static alloca.
  8279. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8280. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8281. if (!Info)
  8282. continue;
  8283. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8284. // Skip allocas that have been initialized or clobbered.
  8285. if (*Info != StaticAllocaInfo::Unknown)
  8286. continue;
  8287. // Check if the stored value is an argument, and that this store fully
  8288. // initializes the alloca. Don't elide copies from the same argument twice.
  8289. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8290. const auto *Arg = dyn_cast<Argument>(Val);
  8291. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8292. Arg->getType()->isEmptyTy() ||
  8293. DL.getTypeStoreSize(Arg->getType()) !=
  8294. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8295. ArgCopyElisionCandidates.count(Arg)) {
  8296. *Info = StaticAllocaInfo::Clobbered;
  8297. continue;
  8298. }
  8299. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8300. << '\n');
  8301. // Mark this alloca and store for argument copy elision.
  8302. *Info = StaticAllocaInfo::Elidable;
  8303. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8304. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8305. // builds, which is useful, because -O0 builds have large entry blocks and
  8306. // many allocas.
  8307. if (ArgCopyElisionCandidates.size() == NumArgs)
  8308. break;
  8309. }
  8310. }
  8311. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8312. /// ArgVal is a load from a suitable fixed stack object.
  8313. static void tryToElideArgumentCopy(
  8314. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8315. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8316. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8317. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8318. SDValue ArgVal, bool &ArgHasUses) {
  8319. // Check if this is a load from a fixed stack object.
  8320. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8321. if (!LNode)
  8322. return;
  8323. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8324. if (!FINode)
  8325. return;
  8326. // Check that the fixed stack object is the right size and alignment.
  8327. // Look at the alignment that the user wrote on the alloca instead of looking
  8328. // at the stack object.
  8329. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8330. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8331. const AllocaInst *AI = ArgCopyIter->second.first;
  8332. int FixedIndex = FINode->getIndex();
  8333. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8334. int OldIndex = AllocaIndex;
  8335. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8336. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8337. LLVM_DEBUG(
  8338. dbgs() << " argument copy elision failed due to bad fixed stack "
  8339. "object size\n");
  8340. return;
  8341. }
  8342. unsigned RequiredAlignment = AI->getAlignment();
  8343. if (!RequiredAlignment) {
  8344. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8345. AI->getAllocatedType());
  8346. }
  8347. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8348. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8349. "greater than stack argument alignment ("
  8350. << RequiredAlignment << " vs "
  8351. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8352. return;
  8353. }
  8354. // Perform the elision. Delete the old stack object and replace its only use
  8355. // in the variable info map. Mark the stack object as mutable.
  8356. LLVM_DEBUG({
  8357. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8358. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8359. << '\n';
  8360. });
  8361. MFI.RemoveStackObject(OldIndex);
  8362. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8363. AllocaIndex = FixedIndex;
  8364. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8365. Chains.push_back(ArgVal.getValue(1));
  8366. // Avoid emitting code for the store implementing the copy.
  8367. const StoreInst *SI = ArgCopyIter->second.second;
  8368. ElidedArgCopyInstrs.insert(SI);
  8369. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8370. // if it is't used by anything other than the store.
  8371. for (const Value *U : Arg.users()) {
  8372. if (U != SI) {
  8373. ArgHasUses = true;
  8374. break;
  8375. }
  8376. }
  8377. }
  8378. void SelectionDAGISel::LowerArguments(const Function &F) {
  8379. SelectionDAG &DAG = SDB->DAG;
  8380. SDLoc dl = SDB->getCurSDLoc();
  8381. const DataLayout &DL = DAG.getDataLayout();
  8382. SmallVector<ISD::InputArg, 16> Ins;
  8383. if (!FuncInfo->CanLowerReturn) {
  8384. // Put in an sret pointer parameter before all the other parameters.
  8385. SmallVector<EVT, 1> ValueVTs;
  8386. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8387. F.getReturnType()->getPointerTo(
  8388. DAG.getDataLayout().getAllocaAddrSpace()),
  8389. ValueVTs);
  8390. // NOTE: Assuming that a pointer will never break down to more than one VT
  8391. // or one register.
  8392. ISD::ArgFlagsTy Flags;
  8393. Flags.setSRet();
  8394. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8395. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8396. ISD::InputArg::NoArgIndex, 0);
  8397. Ins.push_back(RetArg);
  8398. }
  8399. // Look for stores of arguments to static allocas. Mark such arguments with a
  8400. // flag to ask the target to give us the memory location of that argument if
  8401. // available.
  8402. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8403. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8404. // Set up the incoming argument description vector.
  8405. for (const Argument &Arg : F.args()) {
  8406. unsigned ArgNo = Arg.getArgNo();
  8407. SmallVector<EVT, 4> ValueVTs;
  8408. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8409. bool isArgValueUsed = !Arg.use_empty();
  8410. unsigned PartBase = 0;
  8411. Type *FinalType = Arg.getType();
  8412. if (Arg.hasAttribute(Attribute::ByVal))
  8413. FinalType = cast<PointerType>(FinalType)->getElementType();
  8414. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8415. FinalType, F.getCallingConv(), F.isVarArg());
  8416. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8417. Value != NumValues; ++Value) {
  8418. EVT VT = ValueVTs[Value];
  8419. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8420. ISD::ArgFlagsTy Flags;
  8421. // Certain targets (such as MIPS), may have a different ABI alignment
  8422. // for a type depending on the context. Give the target a chance to
  8423. // specify the alignment it wants.
  8424. unsigned OriginalAlignment =
  8425. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8426. if (Arg.getType()->isPointerTy()) {
  8427. Flags.setPointer();
  8428. Flags.setPointerAddrSpace(
  8429. cast<PointerType>(Arg.getType())->getAddressSpace());
  8430. }
  8431. if (Arg.hasAttribute(Attribute::ZExt))
  8432. Flags.setZExt();
  8433. if (Arg.hasAttribute(Attribute::SExt))
  8434. Flags.setSExt();
  8435. if (Arg.hasAttribute(Attribute::InReg)) {
  8436. // If we are using vectorcall calling convention, a structure that is
  8437. // passed InReg - is surely an HVA
  8438. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8439. isa<StructType>(Arg.getType())) {
  8440. // The first value of a structure is marked
  8441. if (0 == Value)
  8442. Flags.setHvaStart();
  8443. Flags.setHva();
  8444. }
  8445. // Set InReg Flag
  8446. Flags.setInReg();
  8447. }
  8448. if (Arg.hasAttribute(Attribute::StructRet))
  8449. Flags.setSRet();
  8450. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8451. Flags.setSwiftSelf();
  8452. if (Arg.hasAttribute(Attribute::SwiftError))
  8453. Flags.setSwiftError();
  8454. if (Arg.hasAttribute(Attribute::ByVal))
  8455. Flags.setByVal();
  8456. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8457. Flags.setInAlloca();
  8458. // Set the byval flag for CCAssignFn callbacks that don't know about
  8459. // inalloca. This way we can know how many bytes we should've allocated
  8460. // and how many bytes a callee cleanup function will pop. If we port
  8461. // inalloca to more targets, we'll have to add custom inalloca handling
  8462. // in the various CC lowering callbacks.
  8463. Flags.setByVal();
  8464. }
  8465. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8466. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8467. if (ArgNo == 0)
  8468. Flags.setByVal();
  8469. }
  8470. if (Flags.isByVal() || Flags.isInAlloca()) {
  8471. PointerType *Ty = cast<PointerType>(Arg.getType());
  8472. Type *ElementTy = Ty->getElementType();
  8473. // For ByVal, size and alignment should be passed from FE. BE will
  8474. // guess if this info is not there but there are cases it cannot get
  8475. // right.
  8476. unsigned FrameSize = DL.getTypeAllocSize(
  8477. Arg.getParamByValType() ? Arg.getParamByValType() : ElementTy);
  8478. Flags.setByValSize(FrameSize);
  8479. unsigned FrameAlign;
  8480. if (Arg.getParamAlignment())
  8481. FrameAlign = Arg.getParamAlignment();
  8482. else
  8483. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8484. Flags.setByValAlign(FrameAlign);
  8485. }
  8486. if (Arg.hasAttribute(Attribute::Nest))
  8487. Flags.setNest();
  8488. if (NeedsRegBlock)
  8489. Flags.setInConsecutiveRegs();
  8490. Flags.setOrigAlign(OriginalAlignment);
  8491. if (ArgCopyElisionCandidates.count(&Arg))
  8492. Flags.setCopyElisionCandidate();
  8493. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8494. *CurDAG->getContext(), F.getCallingConv(), VT);
  8495. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8496. *CurDAG->getContext(), F.getCallingConv(), VT);
  8497. for (unsigned i = 0; i != NumRegs; ++i) {
  8498. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8499. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8500. if (NumRegs > 1 && i == 0)
  8501. MyFlags.Flags.setSplit();
  8502. // if it isn't first piece, alignment must be 1
  8503. else if (i > 0) {
  8504. MyFlags.Flags.setOrigAlign(1);
  8505. if (i == NumRegs - 1)
  8506. MyFlags.Flags.setSplitEnd();
  8507. }
  8508. Ins.push_back(MyFlags);
  8509. }
  8510. if (NeedsRegBlock && Value == NumValues - 1)
  8511. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8512. PartBase += VT.getStoreSize();
  8513. }
  8514. }
  8515. // Call the target to set up the argument values.
  8516. SmallVector<SDValue, 8> InVals;
  8517. SDValue NewRoot = TLI->LowerFormalArguments(
  8518. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8519. // Verify that the target's LowerFormalArguments behaved as expected.
  8520. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8521. "LowerFormalArguments didn't return a valid chain!");
  8522. assert(InVals.size() == Ins.size() &&
  8523. "LowerFormalArguments didn't emit the correct number of values!");
  8524. LLVM_DEBUG({
  8525. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8526. assert(InVals[i].getNode() &&
  8527. "LowerFormalArguments emitted a null value!");
  8528. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8529. "LowerFormalArguments emitted a value with the wrong type!");
  8530. }
  8531. });
  8532. // Update the DAG with the new chain value resulting from argument lowering.
  8533. DAG.setRoot(NewRoot);
  8534. // Set up the argument values.
  8535. unsigned i = 0;
  8536. if (!FuncInfo->CanLowerReturn) {
  8537. // Create a virtual register for the sret pointer, and put in a copy
  8538. // from the sret argument into it.
  8539. SmallVector<EVT, 1> ValueVTs;
  8540. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8541. F.getReturnType()->getPointerTo(
  8542. DAG.getDataLayout().getAllocaAddrSpace()),
  8543. ValueVTs);
  8544. MVT VT = ValueVTs[0].getSimpleVT();
  8545. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8546. Optional<ISD::NodeType> AssertOp = None;
  8547. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8548. nullptr, F.getCallingConv(), AssertOp);
  8549. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8550. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8551. unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8552. FuncInfo->DemoteRegister = SRetReg;
  8553. NewRoot =
  8554. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8555. DAG.setRoot(NewRoot);
  8556. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8557. ++i;
  8558. }
  8559. SmallVector<SDValue, 4> Chains;
  8560. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8561. for (const Argument &Arg : F.args()) {
  8562. SmallVector<SDValue, 4> ArgValues;
  8563. SmallVector<EVT, 4> ValueVTs;
  8564. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8565. unsigned NumValues = ValueVTs.size();
  8566. if (NumValues == 0)
  8567. continue;
  8568. bool ArgHasUses = !Arg.use_empty();
  8569. // Elide the copying store if the target loaded this argument from a
  8570. // suitable fixed stack object.
  8571. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8572. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8573. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8574. InVals[i], ArgHasUses);
  8575. }
  8576. // If this argument is unused then remember its value. It is used to generate
  8577. // debugging information.
  8578. bool isSwiftErrorArg =
  8579. TLI->supportSwiftError() &&
  8580. Arg.hasAttribute(Attribute::SwiftError);
  8581. if (!ArgHasUses && !isSwiftErrorArg) {
  8582. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8583. // Also remember any frame index for use in FastISel.
  8584. if (FrameIndexSDNode *FI =
  8585. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8586. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8587. }
  8588. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8589. EVT VT = ValueVTs[Val];
  8590. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8591. F.getCallingConv(), VT);
  8592. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8593. *CurDAG->getContext(), F.getCallingConv(), VT);
  8594. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8595. // we do generate a copy for it that can be used on return from the
  8596. // function.
  8597. if (ArgHasUses || isSwiftErrorArg) {
  8598. Optional<ISD::NodeType> AssertOp;
  8599. if (Arg.hasAttribute(Attribute::SExt))
  8600. AssertOp = ISD::AssertSext;
  8601. else if (Arg.hasAttribute(Attribute::ZExt))
  8602. AssertOp = ISD::AssertZext;
  8603. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8604. PartVT, VT, nullptr,
  8605. F.getCallingConv(), AssertOp));
  8606. }
  8607. i += NumParts;
  8608. }
  8609. // We don't need to do anything else for unused arguments.
  8610. if (ArgValues.empty())
  8611. continue;
  8612. // Note down frame index.
  8613. if (FrameIndexSDNode *FI =
  8614. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8615. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8616. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8617. SDB->getCurSDLoc());
  8618. SDB->setValue(&Arg, Res);
  8619. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8620. // We want to associate the argument with the frame index, among
  8621. // involved operands, that correspond to the lowest address. The
  8622. // getCopyFromParts function, called earlier, is swapping the order of
  8623. // the operands to BUILD_PAIR depending on endianness. The result of
  8624. // that swapping is that the least significant bits of the argument will
  8625. // be in the first operand of the BUILD_PAIR node, and the most
  8626. // significant bits will be in the second operand.
  8627. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8628. if (LoadSDNode *LNode =
  8629. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8630. if (FrameIndexSDNode *FI =
  8631. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8632. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8633. }
  8634. // Update the SwiftErrorVRegDefMap.
  8635. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8636. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8637. if (TargetRegisterInfo::isVirtualRegister(Reg))
  8638. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  8639. Reg);
  8640. }
  8641. // If this argument is live outside of the entry block, insert a copy from
  8642. // wherever we got it to the vreg that other BB's will reference it as.
  8643. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
  8644. // If we can, though, try to skip creating an unnecessary vreg.
  8645. // FIXME: This isn't very clean... it would be nice to make this more
  8646. // general. It's also subtly incompatible with the hacks FastISel
  8647. // uses with vregs.
  8648. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8649. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  8650. FuncInfo->ValueMap[&Arg] = Reg;
  8651. continue;
  8652. }
  8653. }
  8654. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8655. FuncInfo->InitializeRegForValue(&Arg);
  8656. SDB->CopyToExportRegsIfNeeded(&Arg);
  8657. }
  8658. }
  8659. if (!Chains.empty()) {
  8660. Chains.push_back(NewRoot);
  8661. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8662. }
  8663. DAG.setRoot(NewRoot);
  8664. assert(i == InVals.size() && "Argument register count mismatch!");
  8665. // If any argument copy elisions occurred and we have debug info, update the
  8666. // stale frame indices used in the dbg.declare variable info table.
  8667. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8668. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8669. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8670. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8671. if (I != ArgCopyElisionFrameIndexMap.end())
  8672. VI.Slot = I->second;
  8673. }
  8674. }
  8675. // Finally, if the target has anything special to do, allow it to do so.
  8676. EmitFunctionEntryCode();
  8677. }
  8678. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8679. /// ensure constants are generated when needed. Remember the virtual registers
  8680. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8681. /// directly add them, because expansion might result in multiple MBB's for one
  8682. /// BB. As such, the start of the BB might correspond to a different MBB than
  8683. /// the end.
  8684. void
  8685. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8686. const Instruction *TI = LLVMBB->getTerminator();
  8687. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8688. // Check PHI nodes in successors that expect a value to be available from this
  8689. // block.
  8690. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8691. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8692. if (!isa<PHINode>(SuccBB->begin())) continue;
  8693. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8694. // If this terminator has multiple identical successors (common for
  8695. // switches), only handle each succ once.
  8696. if (!SuccsHandled.insert(SuccMBB).second)
  8697. continue;
  8698. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8699. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8700. // nodes and Machine PHI nodes, but the incoming operands have not been
  8701. // emitted yet.
  8702. for (const PHINode &PN : SuccBB->phis()) {
  8703. // Ignore dead phi's.
  8704. if (PN.use_empty())
  8705. continue;
  8706. // Skip empty types
  8707. if (PN.getType()->isEmptyTy())
  8708. continue;
  8709. unsigned Reg;
  8710. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8711. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8712. unsigned &RegOut = ConstantsOut[C];
  8713. if (RegOut == 0) {
  8714. RegOut = FuncInfo.CreateRegs(C);
  8715. CopyValueToVirtualRegister(C, RegOut);
  8716. }
  8717. Reg = RegOut;
  8718. } else {
  8719. DenseMap<const Value *, unsigned>::iterator I =
  8720. FuncInfo.ValueMap.find(PHIOp);
  8721. if (I != FuncInfo.ValueMap.end())
  8722. Reg = I->second;
  8723. else {
  8724. assert(isa<AllocaInst>(PHIOp) &&
  8725. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8726. "Didn't codegen value into a register!??");
  8727. Reg = FuncInfo.CreateRegs(PHIOp);
  8728. CopyValueToVirtualRegister(PHIOp, Reg);
  8729. }
  8730. }
  8731. // Remember that this register needs to added to the machine PHI node as
  8732. // the input for this MBB.
  8733. SmallVector<EVT, 4> ValueVTs;
  8734. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8735. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8736. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8737. EVT VT = ValueVTs[vti];
  8738. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8739. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8740. FuncInfo.PHINodesToUpdate.push_back(
  8741. std::make_pair(&*MBBI++, Reg + i));
  8742. Reg += NumRegisters;
  8743. }
  8744. }
  8745. }
  8746. ConstantsOut.clear();
  8747. }
  8748. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8749. /// is 0.
  8750. MachineBasicBlock *
  8751. SelectionDAGBuilder::StackProtectorDescriptor::
  8752. AddSuccessorMBB(const BasicBlock *BB,
  8753. MachineBasicBlock *ParentMBB,
  8754. bool IsLikely,
  8755. MachineBasicBlock *SuccMBB) {
  8756. // If SuccBB has not been created yet, create it.
  8757. if (!SuccMBB) {
  8758. MachineFunction *MF = ParentMBB->getParent();
  8759. MachineFunction::iterator BBI(ParentMBB);
  8760. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8761. MF->insert(++BBI, SuccMBB);
  8762. }
  8763. // Add it as a successor of ParentMBB.
  8764. ParentMBB->addSuccessor(
  8765. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8766. return SuccMBB;
  8767. }
  8768. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8769. MachineFunction::iterator I(MBB);
  8770. if (++I == FuncInfo.MF->end())
  8771. return nullptr;
  8772. return &*I;
  8773. }
  8774. /// During lowering new call nodes can be created (such as memset, etc.).
  8775. /// Those will become new roots of the current DAG, but complications arise
  8776. /// when they are tail calls. In such cases, the call lowering will update
  8777. /// the root, but the builder still needs to know that a tail call has been
  8778. /// lowered in order to avoid generating an additional return.
  8779. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8780. // If the node is null, we do have a tail call.
  8781. if (MaybeTC.getNode() != nullptr)
  8782. DAG.setRoot(MaybeTC);
  8783. else
  8784. HasTailCall = true;
  8785. }
  8786. uint64_t
  8787. SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
  8788. unsigned First, unsigned Last) const {
  8789. assert(Last >= First);
  8790. const APInt &LowCase = Clusters[First].Low->getValue();
  8791. const APInt &HighCase = Clusters[Last].High->getValue();
  8792. assert(LowCase.getBitWidth() == HighCase.getBitWidth());
  8793. // FIXME: A range of consecutive cases has 100% density, but only requires one
  8794. // comparison to lower. We should discriminate against such consecutive ranges
  8795. // in jump tables.
  8796. return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
  8797. }
  8798. uint64_t SelectionDAGBuilder::getJumpTableNumCases(
  8799. const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
  8800. unsigned Last) const {
  8801. assert(Last >= First);
  8802. assert(TotalCases[Last] >= TotalCases[First]);
  8803. uint64_t NumCases =
  8804. TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
  8805. return NumCases;
  8806. }
  8807. bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
  8808. unsigned First, unsigned Last,
  8809. const SwitchInst *SI,
  8810. MachineBasicBlock *DefaultMBB,
  8811. CaseCluster &JTCluster) {
  8812. assert(First <= Last);
  8813. auto Prob = BranchProbability::getZero();
  8814. unsigned NumCmps = 0;
  8815. std::vector<MachineBasicBlock*> Table;
  8816. DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
  8817. // Initialize probabilities in JTProbs.
  8818. for (unsigned I = First; I <= Last; ++I)
  8819. JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
  8820. for (unsigned I = First; I <= Last; ++I) {
  8821. assert(Clusters[I].Kind == CC_Range);
  8822. Prob += Clusters[I].Prob;
  8823. const APInt &Low = Clusters[I].Low->getValue();
  8824. const APInt &High = Clusters[I].High->getValue();
  8825. NumCmps += (Low == High) ? 1 : 2;
  8826. if (I != First) {
  8827. // Fill the gap between this and the previous cluster.
  8828. const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
  8829. assert(PreviousHigh.slt(Low));
  8830. uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
  8831. for (uint64_t J = 0; J < Gap; J++)
  8832. Table.push_back(DefaultMBB);
  8833. }
  8834. uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
  8835. for (uint64_t J = 0; J < ClusterSize; ++J)
  8836. Table.push_back(Clusters[I].MBB);
  8837. JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
  8838. }
  8839. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8840. unsigned NumDests = JTProbs.size();
  8841. if (TLI.isSuitableForBitTests(
  8842. NumDests, NumCmps, Clusters[First].Low->getValue(),
  8843. Clusters[Last].High->getValue(), DAG.getDataLayout())) {
  8844. // Clusters[First..Last] should be lowered as bit tests instead.
  8845. return false;
  8846. }
  8847. // Create the MBB that will load from and jump through the table.
  8848. // Note: We create it here, but it's not inserted into the function yet.
  8849. MachineFunction *CurMF = FuncInfo.MF;
  8850. MachineBasicBlock *JumpTableMBB =
  8851. CurMF->CreateMachineBasicBlock(SI->getParent());
  8852. // Add successors. Note: use table order for determinism.
  8853. SmallPtrSet<MachineBasicBlock *, 8> Done;
  8854. for (MachineBasicBlock *Succ : Table) {
  8855. if (Done.count(Succ))
  8856. continue;
  8857. addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
  8858. Done.insert(Succ);
  8859. }
  8860. JumpTableMBB->normalizeSuccProbs();
  8861. unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
  8862. ->createJumpTableIndex(Table);
  8863. // Set up the jump table info.
  8864. JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
  8865. JumpTableHeader JTH(Clusters[First].Low->getValue(),
  8866. Clusters[Last].High->getValue(), SI->getCondition(),
  8867. nullptr, false);
  8868. JTCases.emplace_back(std::move(JTH), std::move(JT));
  8869. JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
  8870. JTCases.size() - 1, Prob);
  8871. return true;
  8872. }
  8873. void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
  8874. const SwitchInst *SI,
  8875. MachineBasicBlock *DefaultMBB) {
  8876. #ifndef NDEBUG
  8877. // Clusters must be non-empty, sorted, and only contain Range clusters.
  8878. assert(!Clusters.empty());
  8879. for (CaseCluster &C : Clusters)
  8880. assert(C.Kind == CC_Range);
  8881. for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
  8882. assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
  8883. #endif
  8884. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8885. if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
  8886. return;
  8887. const int64_t N = Clusters.size();
  8888. const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
  8889. const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
  8890. if (N < 2 || N < MinJumpTableEntries)
  8891. return;
  8892. // TotalCases[i]: Total nbr of cases in Clusters[0..i].
  8893. SmallVector<unsigned, 8> TotalCases(N);
  8894. for (unsigned i = 0; i < N; ++i) {
  8895. const APInt &Hi = Clusters[i].High->getValue();
  8896. const APInt &Lo = Clusters[i].Low->getValue();
  8897. TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
  8898. if (i != 0)
  8899. TotalCases[i] += TotalCases[i - 1];
  8900. }
  8901. // Cheap case: the whole range may be suitable for jump table.
  8902. uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
  8903. uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
  8904. assert(NumCases < UINT64_MAX / 100);
  8905. assert(Range >= NumCases);
  8906. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8907. CaseCluster JTCluster;
  8908. if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
  8909. Clusters[0] = JTCluster;
  8910. Clusters.resize(1);
  8911. return;
  8912. }
  8913. }
  8914. // The algorithm below is not suitable for -O0.
  8915. if (TM.getOptLevel() == CodeGenOpt::None)
  8916. return;
  8917. // Split Clusters into minimum number of dense partitions. The algorithm uses
  8918. // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
  8919. // for the Case Statement'" (1994), but builds the MinPartitions array in
  8920. // reverse order to make it easier to reconstruct the partitions in ascending
  8921. // order. In the choice between two optimal partitionings, it picks the one
  8922. // which yields more jump tables.
  8923. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  8924. SmallVector<unsigned, 8> MinPartitions(N);
  8925. // LastElement[i] is the last element of the partition starting at i.
  8926. SmallVector<unsigned, 8> LastElement(N);
  8927. // PartitionsScore[i] is used to break ties when choosing between two
  8928. // partitionings resulting in the same number of partitions.
  8929. SmallVector<unsigned, 8> PartitionsScore(N);
  8930. // For PartitionsScore, a small number of comparisons is considered as good as
  8931. // a jump table and a single comparison is considered better than a jump
  8932. // table.
  8933. enum PartitionScores : unsigned {
  8934. NoTable = 0,
  8935. Table = 1,
  8936. FewCases = 1,
  8937. SingleCase = 2
  8938. };
  8939. // Base case: There is only one way to partition Clusters[N-1].
  8940. MinPartitions[N - 1] = 1;
  8941. LastElement[N - 1] = N - 1;
  8942. PartitionsScore[N - 1] = PartitionScores::SingleCase;
  8943. // Note: loop indexes are signed to avoid underflow.
  8944. for (int64_t i = N - 2; i >= 0; i--) {
  8945. // Find optimal partitioning of Clusters[i..N-1].
  8946. // Baseline: Put Clusters[i] into a partition on its own.
  8947. MinPartitions[i] = MinPartitions[i + 1] + 1;
  8948. LastElement[i] = i;
  8949. PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
  8950. // Search for a solution that results in fewer partitions.
  8951. for (int64_t j = N - 1; j > i; j--) {
  8952. // Try building a partition from Clusters[i..j].
  8953. uint64_t Range = getJumpTableRange(Clusters, i, j);
  8954. uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
  8955. assert(NumCases < UINT64_MAX / 100);
  8956. assert(Range >= NumCases);
  8957. if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
  8958. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  8959. unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
  8960. int64_t NumEntries = j - i + 1;
  8961. if (NumEntries == 1)
  8962. Score += PartitionScores::SingleCase;
  8963. else if (NumEntries <= SmallNumberOfEntries)
  8964. Score += PartitionScores::FewCases;
  8965. else if (NumEntries >= MinJumpTableEntries)
  8966. Score += PartitionScores::Table;
  8967. // If this leads to fewer partitions, or to the same number of
  8968. // partitions with better score, it is a better partitioning.
  8969. if (NumPartitions < MinPartitions[i] ||
  8970. (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
  8971. MinPartitions[i] = NumPartitions;
  8972. LastElement[i] = j;
  8973. PartitionsScore[i] = Score;
  8974. }
  8975. }
  8976. }
  8977. }
  8978. // Iterate over the partitions, replacing some with jump tables in-place.
  8979. unsigned DstIndex = 0;
  8980. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  8981. Last = LastElement[First];
  8982. assert(Last >= First);
  8983. assert(DstIndex <= First);
  8984. unsigned NumClusters = Last - First + 1;
  8985. CaseCluster JTCluster;
  8986. if (NumClusters >= MinJumpTableEntries &&
  8987. buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
  8988. Clusters[DstIndex++] = JTCluster;
  8989. } else {
  8990. for (unsigned I = First; I <= Last; ++I)
  8991. std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
  8992. }
  8993. }
  8994. Clusters.resize(DstIndex);
  8995. }
  8996. bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
  8997. unsigned First, unsigned Last,
  8998. const SwitchInst *SI,
  8999. CaseCluster &BTCluster) {
  9000. assert(First <= Last);
  9001. if (First == Last)
  9002. return false;
  9003. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  9004. unsigned NumCmps = 0;
  9005. for (int64_t I = First; I <= Last; ++I) {
  9006. assert(Clusters[I].Kind == CC_Range);
  9007. Dests.set(Clusters[I].MBB->getNumber());
  9008. NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
  9009. }
  9010. unsigned NumDests = Dests.count();
  9011. APInt Low = Clusters[First].Low->getValue();
  9012. APInt High = Clusters[Last].High->getValue();
  9013. assert(Low.slt(High));
  9014. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9015. const DataLayout &DL = DAG.getDataLayout();
  9016. if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
  9017. return false;
  9018. APInt LowBound;
  9019. APInt CmpRange;
  9020. const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
  9021. assert(TLI.rangeFitsInWord(Low, High, DL) &&
  9022. "Case range must fit in bit mask!");
  9023. // Check if the clusters cover a contiguous range such that no value in the
  9024. // range will jump to the default statement.
  9025. bool ContiguousRange = true;
  9026. for (int64_t I = First + 1; I <= Last; ++I) {
  9027. if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
  9028. ContiguousRange = false;
  9029. break;
  9030. }
  9031. }
  9032. if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
  9033. // Optimize the case where all the case values fit in a word without having
  9034. // to subtract minValue. In this case, we can optimize away the subtraction.
  9035. LowBound = APInt::getNullValue(Low.getBitWidth());
  9036. CmpRange = High;
  9037. ContiguousRange = false;
  9038. } else {
  9039. LowBound = Low;
  9040. CmpRange = High - Low;
  9041. }
  9042. CaseBitsVector CBV;
  9043. auto TotalProb = BranchProbability::getZero();
  9044. for (unsigned i = First; i <= Last; ++i) {
  9045. // Find the CaseBits for this destination.
  9046. unsigned j;
  9047. for (j = 0; j < CBV.size(); ++j)
  9048. if (CBV[j].BB == Clusters[i].MBB)
  9049. break;
  9050. if (j == CBV.size())
  9051. CBV.push_back(
  9052. CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
  9053. CaseBits *CB = &CBV[j];
  9054. // Update Mask, Bits and ExtraProb.
  9055. uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
  9056. uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
  9057. assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
  9058. CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
  9059. CB->Bits += Hi - Lo + 1;
  9060. CB->ExtraProb += Clusters[i].Prob;
  9061. TotalProb += Clusters[i].Prob;
  9062. }
  9063. BitTestInfo BTI;
  9064. llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
  9065. // Sort by probability first, number of bits second, bit mask third.
  9066. if (a.ExtraProb != b.ExtraProb)
  9067. return a.ExtraProb > b.ExtraProb;
  9068. if (a.Bits != b.Bits)
  9069. return a.Bits > b.Bits;
  9070. return a.Mask < b.Mask;
  9071. });
  9072. for (auto &CB : CBV) {
  9073. MachineBasicBlock *BitTestBB =
  9074. FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
  9075. BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
  9076. }
  9077. BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
  9078. SI->getCondition(), -1U, MVT::Other, false,
  9079. ContiguousRange, nullptr, nullptr, std::move(BTI),
  9080. TotalProb);
  9081. BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
  9082. BitTestCases.size() - 1, TotalProb);
  9083. return true;
  9084. }
  9085. void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
  9086. const SwitchInst *SI) {
  9087. // Partition Clusters into as few subsets as possible, where each subset has a
  9088. // range that fits in a machine word and has <= 3 unique destinations.
  9089. #ifndef NDEBUG
  9090. // Clusters must be sorted and contain Range or JumpTable clusters.
  9091. assert(!Clusters.empty());
  9092. assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
  9093. for (const CaseCluster &C : Clusters)
  9094. assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
  9095. for (unsigned i = 1; i < Clusters.size(); ++i)
  9096. assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
  9097. #endif
  9098. // The algorithm below is not suitable for -O0.
  9099. if (TM.getOptLevel() == CodeGenOpt::None)
  9100. return;
  9101. // If target does not have legal shift left, do not emit bit tests at all.
  9102. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9103. const DataLayout &DL = DAG.getDataLayout();
  9104. EVT PTy = TLI.getPointerTy(DL);
  9105. if (!TLI.isOperationLegal(ISD::SHL, PTy))
  9106. return;
  9107. int BitWidth = PTy.getSizeInBits();
  9108. const int64_t N = Clusters.size();
  9109. // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
  9110. SmallVector<unsigned, 8> MinPartitions(N);
  9111. // LastElement[i] is the last element of the partition starting at i.
  9112. SmallVector<unsigned, 8> LastElement(N);
  9113. // FIXME: This might not be the best algorithm for finding bit test clusters.
  9114. // Base case: There is only one way to partition Clusters[N-1].
  9115. MinPartitions[N - 1] = 1;
  9116. LastElement[N - 1] = N - 1;
  9117. // Note: loop indexes are signed to avoid underflow.
  9118. for (int64_t i = N - 2; i >= 0; --i) {
  9119. // Find optimal partitioning of Clusters[i..N-1].
  9120. // Baseline: Put Clusters[i] into a partition on its own.
  9121. MinPartitions[i] = MinPartitions[i + 1] + 1;
  9122. LastElement[i] = i;
  9123. // Search for a solution that results in fewer partitions.
  9124. // Note: the search is limited by BitWidth, reducing time complexity.
  9125. for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
  9126. // Try building a partition from Clusters[i..j].
  9127. // Check the range.
  9128. if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
  9129. Clusters[j].High->getValue(), DL))
  9130. continue;
  9131. // Check nbr of destinations and cluster types.
  9132. // FIXME: This works, but doesn't seem very efficient.
  9133. bool RangesOnly = true;
  9134. BitVector Dests(FuncInfo.MF->getNumBlockIDs());
  9135. for (int64_t k = i; k <= j; k++) {
  9136. if (Clusters[k].Kind != CC_Range) {
  9137. RangesOnly = false;
  9138. break;
  9139. }
  9140. Dests.set(Clusters[k].MBB->getNumber());
  9141. }
  9142. if (!RangesOnly || Dests.count() > 3)
  9143. break;
  9144. // Check if it's a better partition.
  9145. unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
  9146. if (NumPartitions < MinPartitions[i]) {
  9147. // Found a better partition.
  9148. MinPartitions[i] = NumPartitions;
  9149. LastElement[i] = j;
  9150. }
  9151. }
  9152. }
  9153. // Iterate over the partitions, replacing with bit-test clusters in-place.
  9154. unsigned DstIndex = 0;
  9155. for (unsigned First = 0, Last; First < N; First = Last + 1) {
  9156. Last = LastElement[First];
  9157. assert(First <= Last);
  9158. assert(DstIndex <= First);
  9159. CaseCluster BitTestCluster;
  9160. if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
  9161. Clusters[DstIndex++] = BitTestCluster;
  9162. } else {
  9163. size_t NumClusters = Last - First + 1;
  9164. std::memmove(&Clusters[DstIndex], &Clusters[First],
  9165. sizeof(Clusters[0]) * NumClusters);
  9166. DstIndex += NumClusters;
  9167. }
  9168. }
  9169. Clusters.resize(DstIndex);
  9170. }
  9171. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  9172. MachineBasicBlock *SwitchMBB,
  9173. MachineBasicBlock *DefaultMBB) {
  9174. MachineFunction *CurMF = FuncInfo.MF;
  9175. MachineBasicBlock *NextMBB = nullptr;
  9176. MachineFunction::iterator BBI(W.MBB);
  9177. if (++BBI != FuncInfo.MF->end())
  9178. NextMBB = &*BBI;
  9179. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  9180. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9181. if (Size == 2 && W.MBB == SwitchMBB) {
  9182. // If any two of the cases has the same destination, and if one value
  9183. // is the same as the other, but has one bit unset that the other has set,
  9184. // use bit manipulation to do two compares at once. For example:
  9185. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  9186. // TODO: This could be extended to merge any 2 cases in switches with 3
  9187. // cases.
  9188. // TODO: Handle cases where W.CaseBB != SwitchBB.
  9189. CaseCluster &Small = *W.FirstCluster;
  9190. CaseCluster &Big = *W.LastCluster;
  9191. if (Small.Low == Small.High && Big.Low == Big.High &&
  9192. Small.MBB == Big.MBB) {
  9193. const APInt &SmallValue = Small.Low->getValue();
  9194. const APInt &BigValue = Big.Low->getValue();
  9195. // Check that there is only one bit different.
  9196. APInt CommonBit = BigValue ^ SmallValue;
  9197. if (CommonBit.isPowerOf2()) {
  9198. SDValue CondLHS = getValue(Cond);
  9199. EVT VT = CondLHS.getValueType();
  9200. SDLoc DL = getCurSDLoc();
  9201. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  9202. DAG.getConstant(CommonBit, DL, VT));
  9203. SDValue Cond = DAG.getSetCC(
  9204. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  9205. ISD::SETEQ);
  9206. // Update successor info.
  9207. // Both Small and Big will jump to Small.BB, so we sum up the
  9208. // probabilities.
  9209. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  9210. if (BPI)
  9211. addSuccessorWithProb(
  9212. SwitchMBB, DefaultMBB,
  9213. // The default destination is the first successor in IR.
  9214. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  9215. else
  9216. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  9217. // Insert the true branch.
  9218. SDValue BrCond =
  9219. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  9220. DAG.getBasicBlock(Small.MBB));
  9221. // Insert the false branch.
  9222. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  9223. DAG.getBasicBlock(DefaultMBB));
  9224. DAG.setRoot(BrCond);
  9225. return;
  9226. }
  9227. }
  9228. }
  9229. if (TM.getOptLevel() != CodeGenOpt::None) {
  9230. // Here, we order cases by probability so the most likely case will be
  9231. // checked first. However, two clusters can have the same probability in
  9232. // which case their relative ordering is non-deterministic. So we use Low
  9233. // as a tie-breaker as clusters are guaranteed to never overlap.
  9234. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  9235. [](const CaseCluster &a, const CaseCluster &b) {
  9236. return a.Prob != b.Prob ?
  9237. a.Prob > b.Prob :
  9238. a.Low->getValue().slt(b.Low->getValue());
  9239. });
  9240. // Rearrange the case blocks so that the last one falls through if possible
  9241. // without changing the order of probabilities.
  9242. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  9243. --I;
  9244. if (I->Prob > W.LastCluster->Prob)
  9245. break;
  9246. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  9247. std::swap(*I, *W.LastCluster);
  9248. break;
  9249. }
  9250. }
  9251. }
  9252. // Compute total probability.
  9253. BranchProbability DefaultProb = W.DefaultProb;
  9254. BranchProbability UnhandledProbs = DefaultProb;
  9255. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  9256. UnhandledProbs += I->Prob;
  9257. MachineBasicBlock *CurMBB = W.MBB;
  9258. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  9259. bool FallthroughUnreachable = false;
  9260. MachineBasicBlock *Fallthrough;
  9261. if (I == W.LastCluster) {
  9262. // For the last cluster, fall through to the default destination.
  9263. Fallthrough = DefaultMBB;
  9264. FallthroughUnreachable = isa<UnreachableInst>(
  9265. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  9266. } else {
  9267. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  9268. CurMF->insert(BBI, Fallthrough);
  9269. // Put Cond in a virtual register to make it available from the new blocks.
  9270. ExportFromCurrentBlock(Cond);
  9271. }
  9272. UnhandledProbs -= I->Prob;
  9273. switch (I->Kind) {
  9274. case CC_JumpTable: {
  9275. // FIXME: Optimize away range check based on pivot comparisons.
  9276. JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
  9277. JumpTable *JT = &JTCases[I->JTCasesIndex].second;
  9278. // The jump block hasn't been inserted yet; insert it here.
  9279. MachineBasicBlock *JumpMBB = JT->MBB;
  9280. CurMF->insert(BBI, JumpMBB);
  9281. auto JumpProb = I->Prob;
  9282. auto FallthroughProb = UnhandledProbs;
  9283. // If the default statement is a target of the jump table, we evenly
  9284. // distribute the default probability to successors of CurMBB. Also
  9285. // update the probability on the edge from JumpMBB to Fallthrough.
  9286. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  9287. SE = JumpMBB->succ_end();
  9288. SI != SE; ++SI) {
  9289. if (*SI == DefaultMBB) {
  9290. JumpProb += DefaultProb / 2;
  9291. FallthroughProb -= DefaultProb / 2;
  9292. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  9293. JumpMBB->normalizeSuccProbs();
  9294. break;
  9295. }
  9296. }
  9297. if (FallthroughUnreachable) {
  9298. // Skip the range check if the fallthrough block is unreachable.
  9299. JTH->OmitRangeCheck = true;
  9300. }
  9301. if (!JTH->OmitRangeCheck)
  9302. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  9303. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  9304. CurMBB->normalizeSuccProbs();
  9305. // The jump table header will be inserted in our current block, do the
  9306. // range check, and fall through to our fallthrough block.
  9307. JTH->HeaderBB = CurMBB;
  9308. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  9309. // If we're in the right place, emit the jump table header right now.
  9310. if (CurMBB == SwitchMBB) {
  9311. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  9312. JTH->Emitted = true;
  9313. }
  9314. break;
  9315. }
  9316. case CC_BitTests: {
  9317. // FIXME: If Fallthrough is unreachable, skip the range check.
  9318. // FIXME: Optimize away range check based on pivot comparisons.
  9319. BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
  9320. // The bit test blocks haven't been inserted yet; insert them here.
  9321. for (BitTestCase &BTC : BTB->Cases)
  9322. CurMF->insert(BBI, BTC.ThisBB);
  9323. // Fill in fields of the BitTestBlock.
  9324. BTB->Parent = CurMBB;
  9325. BTB->Default = Fallthrough;
  9326. BTB->DefaultProb = UnhandledProbs;
  9327. // If the cases in bit test don't form a contiguous range, we evenly
  9328. // distribute the probability on the edge to Fallthrough to two
  9329. // successors of CurMBB.
  9330. if (!BTB->ContiguousRange) {
  9331. BTB->Prob += DefaultProb / 2;
  9332. BTB->DefaultProb -= DefaultProb / 2;
  9333. }
  9334. // If we're in the right place, emit the bit test header right now.
  9335. if (CurMBB == SwitchMBB) {
  9336. visitBitTestHeader(*BTB, SwitchMBB);
  9337. BTB->Emitted = true;
  9338. }
  9339. break;
  9340. }
  9341. case CC_Range: {
  9342. const Value *RHS, *LHS, *MHS;
  9343. ISD::CondCode CC;
  9344. if (I->Low == I->High) {
  9345. // Check Cond == I->Low.
  9346. CC = ISD::SETEQ;
  9347. LHS = Cond;
  9348. RHS=I->Low;
  9349. MHS = nullptr;
  9350. } else {
  9351. // Check I->Low <= Cond <= I->High.
  9352. CC = ISD::SETLE;
  9353. LHS = I->Low;
  9354. MHS = Cond;
  9355. RHS = I->High;
  9356. }
  9357. // If Fallthrough is unreachable, fold away the comparison.
  9358. if (FallthroughUnreachable)
  9359. CC = ISD::SETTRUE;
  9360. // The false probability is the sum of all unhandled cases.
  9361. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9362. getCurSDLoc(), I->Prob, UnhandledProbs);
  9363. if (CurMBB == SwitchMBB)
  9364. visitSwitchCase(CB, SwitchMBB);
  9365. else
  9366. SwitchCases.push_back(CB);
  9367. break;
  9368. }
  9369. }
  9370. CurMBB = Fallthrough;
  9371. }
  9372. }
  9373. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9374. CaseClusterIt First,
  9375. CaseClusterIt Last) {
  9376. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9377. if (X.Prob != CC.Prob)
  9378. return X.Prob > CC.Prob;
  9379. // Ties are broken by comparing the case value.
  9380. return X.Low->getValue().slt(CC.Low->getValue());
  9381. });
  9382. }
  9383. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9384. const SwitchWorkListItem &W,
  9385. Value *Cond,
  9386. MachineBasicBlock *SwitchMBB) {
  9387. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9388. "Clusters not sorted?");
  9389. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9390. // Balance the tree based on branch probabilities to create a near-optimal (in
  9391. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9392. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9393. CaseClusterIt LastLeft = W.FirstCluster;
  9394. CaseClusterIt FirstRight = W.LastCluster;
  9395. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9396. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9397. // Move LastLeft and FirstRight towards each other from opposite directions to
  9398. // find a partitioning of the clusters which balances the probability on both
  9399. // sides. If LeftProb and RightProb are equal, alternate which side is
  9400. // taken to ensure 0-probability nodes are distributed evenly.
  9401. unsigned I = 0;
  9402. while (LastLeft + 1 < FirstRight) {
  9403. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9404. LeftProb += (++LastLeft)->Prob;
  9405. else
  9406. RightProb += (--FirstRight)->Prob;
  9407. I++;
  9408. }
  9409. while (true) {
  9410. // Our binary search tree differs from a typical BST in that ours can have up
  9411. // to three values in each leaf. The pivot selection above doesn't take that
  9412. // into account, which means the tree might require more nodes and be less
  9413. // efficient. We compensate for this here.
  9414. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9415. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9416. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9417. // If one side has less than 3 clusters, and the other has more than 3,
  9418. // consider taking a cluster from the other side.
  9419. if (NumLeft < NumRight) {
  9420. // Consider moving the first cluster on the right to the left side.
  9421. CaseCluster &CC = *FirstRight;
  9422. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9423. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9424. if (LeftSideRank <= RightSideRank) {
  9425. // Moving the cluster to the left does not demote it.
  9426. ++LastLeft;
  9427. ++FirstRight;
  9428. continue;
  9429. }
  9430. } else {
  9431. assert(NumRight < NumLeft);
  9432. // Consider moving the last element on the left to the right side.
  9433. CaseCluster &CC = *LastLeft;
  9434. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9435. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9436. if (RightSideRank <= LeftSideRank) {
  9437. // Moving the cluster to the right does not demot it.
  9438. --LastLeft;
  9439. --FirstRight;
  9440. continue;
  9441. }
  9442. }
  9443. }
  9444. break;
  9445. }
  9446. assert(LastLeft + 1 == FirstRight);
  9447. assert(LastLeft >= W.FirstCluster);
  9448. assert(FirstRight <= W.LastCluster);
  9449. // Use the first element on the right as pivot since we will make less-than
  9450. // comparisons against it.
  9451. CaseClusterIt PivotCluster = FirstRight;
  9452. assert(PivotCluster > W.FirstCluster);
  9453. assert(PivotCluster <= W.LastCluster);
  9454. CaseClusterIt FirstLeft = W.FirstCluster;
  9455. CaseClusterIt LastRight = W.LastCluster;
  9456. const ConstantInt *Pivot = PivotCluster->Low;
  9457. // New blocks will be inserted immediately after the current one.
  9458. MachineFunction::iterator BBI(W.MBB);
  9459. ++BBI;
  9460. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9461. // we can branch to its destination directly if it's squeezed exactly in
  9462. // between the known lower bound and Pivot - 1.
  9463. MachineBasicBlock *LeftMBB;
  9464. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9465. FirstLeft->Low == W.GE &&
  9466. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9467. LeftMBB = FirstLeft->MBB;
  9468. } else {
  9469. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9470. FuncInfo.MF->insert(BBI, LeftMBB);
  9471. WorkList.push_back(
  9472. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9473. // Put Cond in a virtual register to make it available from the new blocks.
  9474. ExportFromCurrentBlock(Cond);
  9475. }
  9476. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9477. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9478. // directly if RHS.High equals the current upper bound.
  9479. MachineBasicBlock *RightMBB;
  9480. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9481. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9482. RightMBB = FirstRight->MBB;
  9483. } else {
  9484. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9485. FuncInfo.MF->insert(BBI, RightMBB);
  9486. WorkList.push_back(
  9487. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9488. // Put Cond in a virtual register to make it available from the new blocks.
  9489. ExportFromCurrentBlock(Cond);
  9490. }
  9491. // Create the CaseBlock record that will be used to lower the branch.
  9492. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9493. getCurSDLoc(), LeftProb, RightProb);
  9494. if (W.MBB == SwitchMBB)
  9495. visitSwitchCase(CB, SwitchMBB);
  9496. else
  9497. SwitchCases.push_back(CB);
  9498. }
  9499. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9500. // from the swith statement.
  9501. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9502. BranchProbability PeeledCaseProb) {
  9503. if (PeeledCaseProb == BranchProbability::getOne())
  9504. return BranchProbability::getZero();
  9505. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9506. uint32_t Numerator = CaseProb.getNumerator();
  9507. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9508. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9509. }
  9510. // Try to peel the top probability case if it exceeds the threshold.
  9511. // Return current MachineBasicBlock for the switch statement if the peeling
  9512. // does not occur.
  9513. // If the peeling is performed, return the newly created MachineBasicBlock
  9514. // for the peeled switch statement. Also update Clusters to remove the peeled
  9515. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9516. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9517. const SwitchInst &SI, CaseClusterVector &Clusters,
  9518. BranchProbability &PeeledCaseProb) {
  9519. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9520. // Don't perform if there is only one cluster or optimizing for size.
  9521. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9522. TM.getOptLevel() == CodeGenOpt::None ||
  9523. SwitchMBB->getParent()->getFunction().hasMinSize())
  9524. return SwitchMBB;
  9525. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9526. unsigned PeeledCaseIndex = 0;
  9527. bool SwitchPeeled = false;
  9528. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9529. CaseCluster &CC = Clusters[Index];
  9530. if (CC.Prob < TopCaseProb)
  9531. continue;
  9532. TopCaseProb = CC.Prob;
  9533. PeeledCaseIndex = Index;
  9534. SwitchPeeled = true;
  9535. }
  9536. if (!SwitchPeeled)
  9537. return SwitchMBB;
  9538. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9539. << TopCaseProb << "\n");
  9540. // Record the MBB for the peeled switch statement.
  9541. MachineFunction::iterator BBI(SwitchMBB);
  9542. ++BBI;
  9543. MachineBasicBlock *PeeledSwitchMBB =
  9544. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9545. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9546. ExportFromCurrentBlock(SI.getCondition());
  9547. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9548. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9549. nullptr, nullptr, TopCaseProb.getCompl()};
  9550. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9551. Clusters.erase(PeeledCaseIt);
  9552. for (CaseCluster &CC : Clusters) {
  9553. LLVM_DEBUG(
  9554. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9555. << CC.Prob << "\n");
  9556. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9557. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9558. }
  9559. PeeledCaseProb = TopCaseProb;
  9560. return PeeledSwitchMBB;
  9561. }
  9562. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9563. // Extract cases from the switch.
  9564. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9565. CaseClusterVector Clusters;
  9566. Clusters.reserve(SI.getNumCases());
  9567. for (auto I : SI.cases()) {
  9568. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9569. const ConstantInt *CaseVal = I.getCaseValue();
  9570. BranchProbability Prob =
  9571. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9572. : BranchProbability(1, SI.getNumCases() + 1);
  9573. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9574. }
  9575. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9576. // Cluster adjacent cases with the same destination. We do this at all
  9577. // optimization levels because it's cheap to do and will make codegen faster
  9578. // if there are many clusters.
  9579. sortAndRangeify(Clusters);
  9580. // The branch probablity of the peeled case.
  9581. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9582. MachineBasicBlock *PeeledSwitchMBB =
  9583. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9584. // If there is only the default destination, jump there directly.
  9585. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9586. if (Clusters.empty()) {
  9587. assert(PeeledSwitchMBB == SwitchMBB);
  9588. SwitchMBB->addSuccessor(DefaultMBB);
  9589. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9590. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9591. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9592. }
  9593. return;
  9594. }
  9595. findJumpTables(Clusters, &SI, DefaultMBB);
  9596. findBitTestClusters(Clusters, &SI);
  9597. LLVM_DEBUG({
  9598. dbgs() << "Case clusters: ";
  9599. for (const CaseCluster &C : Clusters) {
  9600. if (C.Kind == CC_JumpTable)
  9601. dbgs() << "JT:";
  9602. if (C.Kind == CC_BitTests)
  9603. dbgs() << "BT:";
  9604. C.Low->getValue().print(dbgs(), true);
  9605. if (C.Low != C.High) {
  9606. dbgs() << '-';
  9607. C.High->getValue().print(dbgs(), true);
  9608. }
  9609. dbgs() << ' ';
  9610. }
  9611. dbgs() << '\n';
  9612. });
  9613. assert(!Clusters.empty());
  9614. SwitchWorkList WorkList;
  9615. CaseClusterIt First = Clusters.begin();
  9616. CaseClusterIt Last = Clusters.end() - 1;
  9617. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9618. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9619. // DefaultMBB is not replaced.
  9620. if (PeeledCaseProb != BranchProbability::getZero() &&
  9621. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9622. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9623. WorkList.push_back(
  9624. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9625. while (!WorkList.empty()) {
  9626. SwitchWorkListItem W = WorkList.back();
  9627. WorkList.pop_back();
  9628. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9629. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9630. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9631. // For optimized builds, lower large range as a balanced binary tree.
  9632. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9633. continue;
  9634. }
  9635. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9636. }
  9637. }