SelectionDAG.cpp 411 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203
  1. //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
  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 the SelectionDAG class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/CodeGen/SelectionDAG.h"
  13. #include "SDNodeDbgValue.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/APSInt.h"
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/BitVector.h"
  19. #include "llvm/ADT/FoldingSet.h"
  20. #include "llvm/ADT/None.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/Triple.h"
  25. #include "llvm/ADT/Twine.h"
  26. #include "llvm/Analysis/BlockFrequencyInfo.h"
  27. #include "llvm/Analysis/MemoryLocation.h"
  28. #include "llvm/Analysis/ProfileSummaryInfo.h"
  29. #include "llvm/Analysis/ValueTracking.h"
  30. #include "llvm/CodeGen/Analysis.h"
  31. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  32. #include "llvm/CodeGen/ISDOpcodes.h"
  33. #include "llvm/CodeGen/MachineBasicBlock.h"
  34. #include "llvm/CodeGen/MachineConstantPool.h"
  35. #include "llvm/CodeGen/MachineFrameInfo.h"
  36. #include "llvm/CodeGen/MachineFunction.h"
  37. #include "llvm/CodeGen/MachineMemOperand.h"
  38. #include "llvm/CodeGen/RuntimeLibcalls.h"
  39. #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
  40. #include "llvm/CodeGen/SelectionDAGNodes.h"
  41. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  42. #include "llvm/CodeGen/TargetFrameLowering.h"
  43. #include "llvm/CodeGen/TargetLowering.h"
  44. #include "llvm/CodeGen/TargetRegisterInfo.h"
  45. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  46. #include "llvm/CodeGen/ValueTypes.h"
  47. #include "llvm/IR/Constant.h"
  48. #include "llvm/IR/Constants.h"
  49. #include "llvm/IR/DataLayout.h"
  50. #include "llvm/IR/DebugInfoMetadata.h"
  51. #include "llvm/IR/DebugLoc.h"
  52. #include "llvm/IR/DerivedTypes.h"
  53. #include "llvm/IR/Function.h"
  54. #include "llvm/IR/GlobalValue.h"
  55. #include "llvm/IR/Metadata.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/IR/Value.h"
  58. #include "llvm/Support/Casting.h"
  59. #include "llvm/Support/CodeGen.h"
  60. #include "llvm/Support/Compiler.h"
  61. #include "llvm/Support/Debug.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Support/KnownBits.h"
  64. #include "llvm/Support/MachineValueType.h"
  65. #include "llvm/Support/ManagedStatic.h"
  66. #include "llvm/Support/MathExtras.h"
  67. #include "llvm/Support/Mutex.h"
  68. #include "llvm/Support/raw_ostream.h"
  69. #include "llvm/Target/TargetMachine.h"
  70. #include "llvm/Target/TargetOptions.h"
  71. #include "llvm/Transforms/Utils/SizeOpts.h"
  72. #include <algorithm>
  73. #include <cassert>
  74. #include <cstdint>
  75. #include <cstdlib>
  76. #include <limits>
  77. #include <set>
  78. #include <string>
  79. #include <utility>
  80. #include <vector>
  81. using namespace llvm;
  82. /// makeVTList - Return an instance of the SDVTList struct initialized with the
  83. /// specified members.
  84. static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
  85. SDVTList Res = {VTs, NumVTs};
  86. return Res;
  87. }
  88. // Default null implementations of the callbacks.
  89. void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
  90. void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
  91. void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
  92. void SelectionDAG::DAGNodeDeletedListener::anchor() {}
  93. #define DEBUG_TYPE "selectiondag"
  94. static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
  95. cl::Hidden, cl::init(true),
  96. cl::desc("Gang up loads and stores generated by inlining of memcpy"));
  97. static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
  98. cl::desc("Number limit for gluing ld/st of memcpy."),
  99. cl::Hidden, cl::init(0));
  100. static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
  101. LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
  102. }
  103. //===----------------------------------------------------------------------===//
  104. // ConstantFPSDNode Class
  105. //===----------------------------------------------------------------------===//
  106. /// isExactlyValue - We don't rely on operator== working on double values, as
  107. /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
  108. /// As such, this method can be used to do an exact bit-for-bit comparison of
  109. /// two floating point values.
  110. bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
  111. return getValueAPF().bitwiseIsEqual(V);
  112. }
  113. bool ConstantFPSDNode::isValueValidForType(EVT VT,
  114. const APFloat& Val) {
  115. assert(VT.isFloatingPoint() && "Can only convert between FP types");
  116. // convert modifies in place, so make a copy.
  117. APFloat Val2 = APFloat(Val);
  118. bool losesInfo;
  119. (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
  120. APFloat::rmNearestTiesToEven,
  121. &losesInfo);
  122. return !losesInfo;
  123. }
  124. //===----------------------------------------------------------------------===//
  125. // ISD Namespace
  126. //===----------------------------------------------------------------------===//
  127. bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
  128. if (N->getOpcode() == ISD::SPLAT_VECTOR) {
  129. unsigned EltSize =
  130. N->getValueType(0).getVectorElementType().getSizeInBits();
  131. if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
  132. SplatVal = Op0->getAPIntValue().truncOrSelf(EltSize);
  133. return true;
  134. }
  135. if (auto *Op0 = dyn_cast<ConstantFPSDNode>(N->getOperand(0))) {
  136. SplatVal = Op0->getValueAPF().bitcastToAPInt().truncOrSelf(EltSize);
  137. return true;
  138. }
  139. }
  140. auto *BV = dyn_cast<BuildVectorSDNode>(N);
  141. if (!BV)
  142. return false;
  143. APInt SplatUndef;
  144. unsigned SplatBitSize;
  145. bool HasUndefs;
  146. unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
  147. return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
  148. EltSize) &&
  149. EltSize == SplatBitSize;
  150. }
  151. // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
  152. // specializations of the more general isConstantSplatVector()?
  153. bool ISD::isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly) {
  154. // Look through a bit convert.
  155. while (N->getOpcode() == ISD::BITCAST)
  156. N = N->getOperand(0).getNode();
  157. if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
  158. APInt SplatVal;
  159. return isConstantSplatVector(N, SplatVal) && SplatVal.isAllOnes();
  160. }
  161. if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
  162. unsigned i = 0, e = N->getNumOperands();
  163. // Skip over all of the undef values.
  164. while (i != e && N->getOperand(i).isUndef())
  165. ++i;
  166. // Do not accept an all-undef vector.
  167. if (i == e) return false;
  168. // Do not accept build_vectors that aren't all constants or which have non-~0
  169. // elements. We have to be a bit careful here, as the type of the constant
  170. // may not be the same as the type of the vector elements due to type
  171. // legalization (the elements are promoted to a legal type for the target and
  172. // a vector of a type may be legal when the base element type is not).
  173. // We only want to check enough bits to cover the vector elements, because
  174. // we care if the resultant vector is all ones, not whether the individual
  175. // constants are.
  176. SDValue NotZero = N->getOperand(i);
  177. unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
  178. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
  179. if (CN->getAPIntValue().countTrailingOnes() < EltSize)
  180. return false;
  181. } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
  182. if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
  183. return false;
  184. } else
  185. return false;
  186. // Okay, we have at least one ~0 value, check to see if the rest match or are
  187. // undefs. Even with the above element type twiddling, this should be OK, as
  188. // the same type legalization should have applied to all the elements.
  189. for (++i; i != e; ++i)
  190. if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
  191. return false;
  192. return true;
  193. }
  194. bool ISD::isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly) {
  195. // Look through a bit convert.
  196. while (N->getOpcode() == ISD::BITCAST)
  197. N = N->getOperand(0).getNode();
  198. if (!BuildVectorOnly && N->getOpcode() == ISD::SPLAT_VECTOR) {
  199. APInt SplatVal;
  200. return isConstantSplatVector(N, SplatVal) && SplatVal.isZero();
  201. }
  202. if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
  203. bool IsAllUndef = true;
  204. for (const SDValue &Op : N->op_values()) {
  205. if (Op.isUndef())
  206. continue;
  207. IsAllUndef = false;
  208. // Do not accept build_vectors that aren't all constants or which have non-0
  209. // elements. We have to be a bit careful here, as the type of the constant
  210. // may not be the same as the type of the vector elements due to type
  211. // legalization (the elements are promoted to a legal type for the target
  212. // and a vector of a type may be legal when the base element type is not).
  213. // We only want to check enough bits to cover the vector elements, because
  214. // we care if the resultant vector is all zeros, not whether the individual
  215. // constants are.
  216. unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
  217. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
  218. if (CN->getAPIntValue().countTrailingZeros() < EltSize)
  219. return false;
  220. } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
  221. if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
  222. return false;
  223. } else
  224. return false;
  225. }
  226. // Do not accept an all-undef vector.
  227. if (IsAllUndef)
  228. return false;
  229. return true;
  230. }
  231. bool ISD::isBuildVectorAllOnes(const SDNode *N) {
  232. return isConstantSplatVectorAllOnes(N, /*BuildVectorOnly*/ true);
  233. }
  234. bool ISD::isBuildVectorAllZeros(const SDNode *N) {
  235. return isConstantSplatVectorAllZeros(N, /*BuildVectorOnly*/ true);
  236. }
  237. bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
  238. if (N->getOpcode() != ISD::BUILD_VECTOR)
  239. return false;
  240. for (const SDValue &Op : N->op_values()) {
  241. if (Op.isUndef())
  242. continue;
  243. if (!isa<ConstantSDNode>(Op))
  244. return false;
  245. }
  246. return true;
  247. }
  248. bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
  249. if (N->getOpcode() != ISD::BUILD_VECTOR)
  250. return false;
  251. for (const SDValue &Op : N->op_values()) {
  252. if (Op.isUndef())
  253. continue;
  254. if (!isa<ConstantFPSDNode>(Op))
  255. return false;
  256. }
  257. return true;
  258. }
  259. bool ISD::allOperandsUndef(const SDNode *N) {
  260. // Return false if the node has no operands.
  261. // This is "logically inconsistent" with the definition of "all" but
  262. // is probably the desired behavior.
  263. if (N->getNumOperands() == 0)
  264. return false;
  265. return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
  266. }
  267. bool ISD::matchUnaryPredicate(SDValue Op,
  268. std::function<bool(ConstantSDNode *)> Match,
  269. bool AllowUndefs) {
  270. // FIXME: Add support for scalar UNDEF cases?
  271. if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
  272. return Match(Cst);
  273. // FIXME: Add support for vector UNDEF cases?
  274. if (ISD::BUILD_VECTOR != Op.getOpcode() &&
  275. ISD::SPLAT_VECTOR != Op.getOpcode())
  276. return false;
  277. EVT SVT = Op.getValueType().getScalarType();
  278. for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
  279. if (AllowUndefs && Op.getOperand(i).isUndef()) {
  280. if (!Match(nullptr))
  281. return false;
  282. continue;
  283. }
  284. auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
  285. if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
  286. return false;
  287. }
  288. return true;
  289. }
  290. bool ISD::matchBinaryPredicate(
  291. SDValue LHS, SDValue RHS,
  292. std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
  293. bool AllowUndefs, bool AllowTypeMismatch) {
  294. if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
  295. return false;
  296. // TODO: Add support for scalar UNDEF cases?
  297. if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
  298. if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
  299. return Match(LHSCst, RHSCst);
  300. // TODO: Add support for vector UNDEF cases?
  301. if (LHS.getOpcode() != RHS.getOpcode() ||
  302. (LHS.getOpcode() != ISD::BUILD_VECTOR &&
  303. LHS.getOpcode() != ISD::SPLAT_VECTOR))
  304. return false;
  305. EVT SVT = LHS.getValueType().getScalarType();
  306. for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
  307. SDValue LHSOp = LHS.getOperand(i);
  308. SDValue RHSOp = RHS.getOperand(i);
  309. bool LHSUndef = AllowUndefs && LHSOp.isUndef();
  310. bool RHSUndef = AllowUndefs && RHSOp.isUndef();
  311. auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
  312. auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
  313. if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
  314. return false;
  315. if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
  316. LHSOp.getValueType() != RHSOp.getValueType()))
  317. return false;
  318. if (!Match(LHSCst, RHSCst))
  319. return false;
  320. }
  321. return true;
  322. }
  323. ISD::NodeType ISD::getVecReduceBaseOpcode(unsigned VecReduceOpcode) {
  324. switch (VecReduceOpcode) {
  325. default:
  326. llvm_unreachable("Expected VECREDUCE opcode");
  327. case ISD::VECREDUCE_FADD:
  328. case ISD::VECREDUCE_SEQ_FADD:
  329. case ISD::VP_REDUCE_FADD:
  330. case ISD::VP_REDUCE_SEQ_FADD:
  331. return ISD::FADD;
  332. case ISD::VECREDUCE_FMUL:
  333. case ISD::VECREDUCE_SEQ_FMUL:
  334. case ISD::VP_REDUCE_FMUL:
  335. case ISD::VP_REDUCE_SEQ_FMUL:
  336. return ISD::FMUL;
  337. case ISD::VECREDUCE_ADD:
  338. case ISD::VP_REDUCE_ADD:
  339. return ISD::ADD;
  340. case ISD::VECREDUCE_MUL:
  341. case ISD::VP_REDUCE_MUL:
  342. return ISD::MUL;
  343. case ISD::VECREDUCE_AND:
  344. case ISD::VP_REDUCE_AND:
  345. return ISD::AND;
  346. case ISD::VECREDUCE_OR:
  347. case ISD::VP_REDUCE_OR:
  348. return ISD::OR;
  349. case ISD::VECREDUCE_XOR:
  350. case ISD::VP_REDUCE_XOR:
  351. return ISD::XOR;
  352. case ISD::VECREDUCE_SMAX:
  353. case ISD::VP_REDUCE_SMAX:
  354. return ISD::SMAX;
  355. case ISD::VECREDUCE_SMIN:
  356. case ISD::VP_REDUCE_SMIN:
  357. return ISD::SMIN;
  358. case ISD::VECREDUCE_UMAX:
  359. case ISD::VP_REDUCE_UMAX:
  360. return ISD::UMAX;
  361. case ISD::VECREDUCE_UMIN:
  362. case ISD::VP_REDUCE_UMIN:
  363. return ISD::UMIN;
  364. case ISD::VECREDUCE_FMAX:
  365. case ISD::VP_REDUCE_FMAX:
  366. return ISD::FMAXNUM;
  367. case ISD::VECREDUCE_FMIN:
  368. case ISD::VP_REDUCE_FMIN:
  369. return ISD::FMINNUM;
  370. }
  371. }
  372. bool ISD::isVPOpcode(unsigned Opcode) {
  373. switch (Opcode) {
  374. default:
  375. return false;
  376. #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) \
  377. case ISD::VPSD: \
  378. return true;
  379. #include "llvm/IR/VPIntrinsics.def"
  380. }
  381. }
  382. bool ISD::isVPBinaryOp(unsigned Opcode) {
  383. switch (Opcode) {
  384. default:
  385. break;
  386. #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
  387. #define VP_PROPERTY_BINARYOP return true;
  388. #define END_REGISTER_VP_SDNODE(VPSD) break;
  389. #include "llvm/IR/VPIntrinsics.def"
  390. }
  391. return false;
  392. }
  393. bool ISD::isVPReduction(unsigned Opcode) {
  394. switch (Opcode) {
  395. default:
  396. break;
  397. #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) case ISD::VPSD:
  398. #define VP_PROPERTY_REDUCTION(STARTPOS, ...) return true;
  399. #define END_REGISTER_VP_SDNODE(VPSD) break;
  400. #include "llvm/IR/VPIntrinsics.def"
  401. }
  402. return false;
  403. }
  404. /// The operand position of the vector mask.
  405. Optional<unsigned> ISD::getVPMaskIdx(unsigned Opcode) {
  406. switch (Opcode) {
  407. default:
  408. return None;
  409. #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, ...) \
  410. case ISD::VPSD: \
  411. return MASKPOS;
  412. #include "llvm/IR/VPIntrinsics.def"
  413. }
  414. }
  415. /// The operand position of the explicit vector length parameter.
  416. Optional<unsigned> ISD::getVPExplicitVectorLengthIdx(unsigned Opcode) {
  417. switch (Opcode) {
  418. default:
  419. return None;
  420. #define BEGIN_REGISTER_VP_SDNODE(VPSD, LEGALPOS, TDNAME, MASKPOS, EVLPOS) \
  421. case ISD::VPSD: \
  422. return EVLPOS;
  423. #include "llvm/IR/VPIntrinsics.def"
  424. }
  425. }
  426. ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
  427. switch (ExtType) {
  428. case ISD::EXTLOAD:
  429. return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
  430. case ISD::SEXTLOAD:
  431. return ISD::SIGN_EXTEND;
  432. case ISD::ZEXTLOAD:
  433. return ISD::ZERO_EXTEND;
  434. default:
  435. break;
  436. }
  437. llvm_unreachable("Invalid LoadExtType");
  438. }
  439. ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
  440. // To perform this operation, we just need to swap the L and G bits of the
  441. // operation.
  442. unsigned OldL = (Operation >> 2) & 1;
  443. unsigned OldG = (Operation >> 1) & 1;
  444. return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
  445. (OldL << 1) | // New G bit
  446. (OldG << 2)); // New L bit.
  447. }
  448. static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
  449. unsigned Operation = Op;
  450. if (isIntegerLike)
  451. Operation ^= 7; // Flip L, G, E bits, but not U.
  452. else
  453. Operation ^= 15; // Flip all of the condition bits.
  454. if (Operation > ISD::SETTRUE2)
  455. Operation &= ~8; // Don't let N and U bits get set.
  456. return ISD::CondCode(Operation);
  457. }
  458. ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
  459. return getSetCCInverseImpl(Op, Type.isInteger());
  460. }
  461. ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
  462. bool isIntegerLike) {
  463. return getSetCCInverseImpl(Op, isIntegerLike);
  464. }
  465. /// For an integer comparison, return 1 if the comparison is a signed operation
  466. /// and 2 if the result is an unsigned comparison. Return zero if the operation
  467. /// does not depend on the sign of the input (setne and seteq).
  468. static int isSignedOp(ISD::CondCode Opcode) {
  469. switch (Opcode) {
  470. default: llvm_unreachable("Illegal integer setcc operation!");
  471. case ISD::SETEQ:
  472. case ISD::SETNE: return 0;
  473. case ISD::SETLT:
  474. case ISD::SETLE:
  475. case ISD::SETGT:
  476. case ISD::SETGE: return 1;
  477. case ISD::SETULT:
  478. case ISD::SETULE:
  479. case ISD::SETUGT:
  480. case ISD::SETUGE: return 2;
  481. }
  482. }
  483. ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
  484. EVT Type) {
  485. bool IsInteger = Type.isInteger();
  486. if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
  487. // Cannot fold a signed integer setcc with an unsigned integer setcc.
  488. return ISD::SETCC_INVALID;
  489. unsigned Op = Op1 | Op2; // Combine all of the condition bits.
  490. // If the N and U bits get set, then the resultant comparison DOES suddenly
  491. // care about orderedness, and it is true when ordered.
  492. if (Op > ISD::SETTRUE2)
  493. Op &= ~16; // Clear the U bit if the N bit is set.
  494. // Canonicalize illegal integer setcc's.
  495. if (IsInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
  496. Op = ISD::SETNE;
  497. return ISD::CondCode(Op);
  498. }
  499. ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
  500. EVT Type) {
  501. bool IsInteger = Type.isInteger();
  502. if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
  503. // Cannot fold a signed setcc with an unsigned setcc.
  504. return ISD::SETCC_INVALID;
  505. // Combine all of the condition bits.
  506. ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
  507. // Canonicalize illegal integer setcc's.
  508. if (IsInteger) {
  509. switch (Result) {
  510. default: break;
  511. case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
  512. case ISD::SETOEQ: // SETEQ & SETU[LG]E
  513. case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
  514. case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
  515. case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
  516. }
  517. }
  518. return Result;
  519. }
  520. //===----------------------------------------------------------------------===//
  521. // SDNode Profile Support
  522. //===----------------------------------------------------------------------===//
  523. /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
  524. static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
  525. ID.AddInteger(OpC);
  526. }
  527. /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
  528. /// solely with their pointer.
  529. static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
  530. ID.AddPointer(VTList.VTs);
  531. }
  532. /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
  533. static void AddNodeIDOperands(FoldingSetNodeID &ID,
  534. ArrayRef<SDValue> Ops) {
  535. for (auto& Op : Ops) {
  536. ID.AddPointer(Op.getNode());
  537. ID.AddInteger(Op.getResNo());
  538. }
  539. }
  540. /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
  541. static void AddNodeIDOperands(FoldingSetNodeID &ID,
  542. ArrayRef<SDUse> Ops) {
  543. for (auto& Op : Ops) {
  544. ID.AddPointer(Op.getNode());
  545. ID.AddInteger(Op.getResNo());
  546. }
  547. }
  548. static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
  549. SDVTList VTList, ArrayRef<SDValue> OpList) {
  550. AddNodeIDOpcode(ID, OpC);
  551. AddNodeIDValueTypes(ID, VTList);
  552. AddNodeIDOperands(ID, OpList);
  553. }
  554. /// If this is an SDNode with special info, add this info to the NodeID data.
  555. static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
  556. switch (N->getOpcode()) {
  557. case ISD::TargetExternalSymbol:
  558. case ISD::ExternalSymbol:
  559. case ISD::MCSymbol:
  560. llvm_unreachable("Should only be used on nodes with operands");
  561. default: break; // Normal nodes don't need extra info.
  562. case ISD::TargetConstant:
  563. case ISD::Constant: {
  564. const ConstantSDNode *C = cast<ConstantSDNode>(N);
  565. ID.AddPointer(C->getConstantIntValue());
  566. ID.AddBoolean(C->isOpaque());
  567. break;
  568. }
  569. case ISD::TargetConstantFP:
  570. case ISD::ConstantFP:
  571. ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
  572. break;
  573. case ISD::TargetGlobalAddress:
  574. case ISD::GlobalAddress:
  575. case ISD::TargetGlobalTLSAddress:
  576. case ISD::GlobalTLSAddress: {
  577. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
  578. ID.AddPointer(GA->getGlobal());
  579. ID.AddInteger(GA->getOffset());
  580. ID.AddInteger(GA->getTargetFlags());
  581. break;
  582. }
  583. case ISD::BasicBlock:
  584. ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
  585. break;
  586. case ISD::Register:
  587. ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
  588. break;
  589. case ISD::RegisterMask:
  590. ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
  591. break;
  592. case ISD::SRCVALUE:
  593. ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
  594. break;
  595. case ISD::FrameIndex:
  596. case ISD::TargetFrameIndex:
  597. ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
  598. break;
  599. case ISD::LIFETIME_START:
  600. case ISD::LIFETIME_END:
  601. if (cast<LifetimeSDNode>(N)->hasOffset()) {
  602. ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
  603. ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
  604. }
  605. break;
  606. case ISD::PSEUDO_PROBE:
  607. ID.AddInteger(cast<PseudoProbeSDNode>(N)->getGuid());
  608. ID.AddInteger(cast<PseudoProbeSDNode>(N)->getIndex());
  609. ID.AddInteger(cast<PseudoProbeSDNode>(N)->getAttributes());
  610. break;
  611. case ISD::JumpTable:
  612. case ISD::TargetJumpTable:
  613. ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
  614. ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
  615. break;
  616. case ISD::ConstantPool:
  617. case ISD::TargetConstantPool: {
  618. const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
  619. ID.AddInteger(CP->getAlign().value());
  620. ID.AddInteger(CP->getOffset());
  621. if (CP->isMachineConstantPoolEntry())
  622. CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
  623. else
  624. ID.AddPointer(CP->getConstVal());
  625. ID.AddInteger(CP->getTargetFlags());
  626. break;
  627. }
  628. case ISD::TargetIndex: {
  629. const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
  630. ID.AddInteger(TI->getIndex());
  631. ID.AddInteger(TI->getOffset());
  632. ID.AddInteger(TI->getTargetFlags());
  633. break;
  634. }
  635. case ISD::LOAD: {
  636. const LoadSDNode *LD = cast<LoadSDNode>(N);
  637. ID.AddInteger(LD->getMemoryVT().getRawBits());
  638. ID.AddInteger(LD->getRawSubclassData());
  639. ID.AddInteger(LD->getPointerInfo().getAddrSpace());
  640. break;
  641. }
  642. case ISD::STORE: {
  643. const StoreSDNode *ST = cast<StoreSDNode>(N);
  644. ID.AddInteger(ST->getMemoryVT().getRawBits());
  645. ID.AddInteger(ST->getRawSubclassData());
  646. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  647. break;
  648. }
  649. case ISD::VP_LOAD: {
  650. const VPLoadSDNode *ELD = cast<VPLoadSDNode>(N);
  651. ID.AddInteger(ELD->getMemoryVT().getRawBits());
  652. ID.AddInteger(ELD->getRawSubclassData());
  653. ID.AddInteger(ELD->getPointerInfo().getAddrSpace());
  654. break;
  655. }
  656. case ISD::VP_STORE: {
  657. const VPStoreSDNode *EST = cast<VPStoreSDNode>(N);
  658. ID.AddInteger(EST->getMemoryVT().getRawBits());
  659. ID.AddInteger(EST->getRawSubclassData());
  660. ID.AddInteger(EST->getPointerInfo().getAddrSpace());
  661. break;
  662. }
  663. case ISD::VP_GATHER: {
  664. const VPGatherSDNode *EG = cast<VPGatherSDNode>(N);
  665. ID.AddInteger(EG->getMemoryVT().getRawBits());
  666. ID.AddInteger(EG->getRawSubclassData());
  667. ID.AddInteger(EG->getPointerInfo().getAddrSpace());
  668. break;
  669. }
  670. case ISD::VP_SCATTER: {
  671. const VPScatterSDNode *ES = cast<VPScatterSDNode>(N);
  672. ID.AddInteger(ES->getMemoryVT().getRawBits());
  673. ID.AddInteger(ES->getRawSubclassData());
  674. ID.AddInteger(ES->getPointerInfo().getAddrSpace());
  675. break;
  676. }
  677. case ISD::MLOAD: {
  678. const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
  679. ID.AddInteger(MLD->getMemoryVT().getRawBits());
  680. ID.AddInteger(MLD->getRawSubclassData());
  681. ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
  682. break;
  683. }
  684. case ISD::MSTORE: {
  685. const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
  686. ID.AddInteger(MST->getMemoryVT().getRawBits());
  687. ID.AddInteger(MST->getRawSubclassData());
  688. ID.AddInteger(MST->getPointerInfo().getAddrSpace());
  689. break;
  690. }
  691. case ISD::MGATHER: {
  692. const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
  693. ID.AddInteger(MG->getMemoryVT().getRawBits());
  694. ID.AddInteger(MG->getRawSubclassData());
  695. ID.AddInteger(MG->getPointerInfo().getAddrSpace());
  696. break;
  697. }
  698. case ISD::MSCATTER: {
  699. const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
  700. ID.AddInteger(MS->getMemoryVT().getRawBits());
  701. ID.AddInteger(MS->getRawSubclassData());
  702. ID.AddInteger(MS->getPointerInfo().getAddrSpace());
  703. break;
  704. }
  705. case ISD::ATOMIC_CMP_SWAP:
  706. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  707. case ISD::ATOMIC_SWAP:
  708. case ISD::ATOMIC_LOAD_ADD:
  709. case ISD::ATOMIC_LOAD_SUB:
  710. case ISD::ATOMIC_LOAD_AND:
  711. case ISD::ATOMIC_LOAD_CLR:
  712. case ISD::ATOMIC_LOAD_OR:
  713. case ISD::ATOMIC_LOAD_XOR:
  714. case ISD::ATOMIC_LOAD_NAND:
  715. case ISD::ATOMIC_LOAD_MIN:
  716. case ISD::ATOMIC_LOAD_MAX:
  717. case ISD::ATOMIC_LOAD_UMIN:
  718. case ISD::ATOMIC_LOAD_UMAX:
  719. case ISD::ATOMIC_LOAD:
  720. case ISD::ATOMIC_STORE: {
  721. const AtomicSDNode *AT = cast<AtomicSDNode>(N);
  722. ID.AddInteger(AT->getMemoryVT().getRawBits());
  723. ID.AddInteger(AT->getRawSubclassData());
  724. ID.AddInteger(AT->getPointerInfo().getAddrSpace());
  725. break;
  726. }
  727. case ISD::PREFETCH: {
  728. const MemSDNode *PF = cast<MemSDNode>(N);
  729. ID.AddInteger(PF->getPointerInfo().getAddrSpace());
  730. break;
  731. }
  732. case ISD::VECTOR_SHUFFLE: {
  733. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  734. for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
  735. i != e; ++i)
  736. ID.AddInteger(SVN->getMaskElt(i));
  737. break;
  738. }
  739. case ISD::TargetBlockAddress:
  740. case ISD::BlockAddress: {
  741. const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
  742. ID.AddPointer(BA->getBlockAddress());
  743. ID.AddInteger(BA->getOffset());
  744. ID.AddInteger(BA->getTargetFlags());
  745. break;
  746. }
  747. } // end switch (N->getOpcode())
  748. // Target specific memory nodes could also have address spaces to check.
  749. if (N->isTargetMemoryOpcode())
  750. ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
  751. }
  752. /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
  753. /// data.
  754. static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
  755. AddNodeIDOpcode(ID, N->getOpcode());
  756. // Add the return value info.
  757. AddNodeIDValueTypes(ID, N->getVTList());
  758. // Add the operand info.
  759. AddNodeIDOperands(ID, N->ops());
  760. // Handle SDNode leafs with special info.
  761. AddNodeIDCustom(ID, N);
  762. }
  763. //===----------------------------------------------------------------------===//
  764. // SelectionDAG Class
  765. //===----------------------------------------------------------------------===//
  766. /// doNotCSE - Return true if CSE should not be performed for this node.
  767. static bool doNotCSE(SDNode *N) {
  768. if (N->getValueType(0) == MVT::Glue)
  769. return true; // Never CSE anything that produces a flag.
  770. switch (N->getOpcode()) {
  771. default: break;
  772. case ISD::HANDLENODE:
  773. case ISD::EH_LABEL:
  774. return true; // Never CSE these nodes.
  775. }
  776. // Check that remaining values produced are not flags.
  777. for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
  778. if (N->getValueType(i) == MVT::Glue)
  779. return true; // Never CSE anything that produces a flag.
  780. return false;
  781. }
  782. /// RemoveDeadNodes - This method deletes all unreachable nodes in the
  783. /// SelectionDAG.
  784. void SelectionDAG::RemoveDeadNodes() {
  785. // Create a dummy node (which is not added to allnodes), that adds a reference
  786. // to the root node, preventing it from being deleted.
  787. HandleSDNode Dummy(getRoot());
  788. SmallVector<SDNode*, 128> DeadNodes;
  789. // Add all obviously-dead nodes to the DeadNodes worklist.
  790. for (SDNode &Node : allnodes())
  791. if (Node.use_empty())
  792. DeadNodes.push_back(&Node);
  793. RemoveDeadNodes(DeadNodes);
  794. // If the root changed (e.g. it was a dead load, update the root).
  795. setRoot(Dummy.getValue());
  796. }
  797. /// RemoveDeadNodes - This method deletes the unreachable nodes in the
  798. /// given list, and any nodes that become unreachable as a result.
  799. void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
  800. // Process the worklist, deleting the nodes and adding their uses to the
  801. // worklist.
  802. while (!DeadNodes.empty()) {
  803. SDNode *N = DeadNodes.pop_back_val();
  804. // Skip to next node if we've already managed to delete the node. This could
  805. // happen if replacing a node causes a node previously added to the node to
  806. // be deleted.
  807. if (N->getOpcode() == ISD::DELETED_NODE)
  808. continue;
  809. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  810. DUL->NodeDeleted(N, nullptr);
  811. // Take the node out of the appropriate CSE map.
  812. RemoveNodeFromCSEMaps(N);
  813. // Next, brutally remove the operand list. This is safe to do, as there are
  814. // no cycles in the graph.
  815. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  816. SDUse &Use = *I++;
  817. SDNode *Operand = Use.getNode();
  818. Use.set(SDValue());
  819. // Now that we removed this operand, see if there are no uses of it left.
  820. if (Operand->use_empty())
  821. DeadNodes.push_back(Operand);
  822. }
  823. DeallocateNode(N);
  824. }
  825. }
  826. void SelectionDAG::RemoveDeadNode(SDNode *N){
  827. SmallVector<SDNode*, 16> DeadNodes(1, N);
  828. // Create a dummy node that adds a reference to the root node, preventing
  829. // it from being deleted. (This matters if the root is an operand of the
  830. // dead node.)
  831. HandleSDNode Dummy(getRoot());
  832. RemoveDeadNodes(DeadNodes);
  833. }
  834. void SelectionDAG::DeleteNode(SDNode *N) {
  835. // First take this out of the appropriate CSE map.
  836. RemoveNodeFromCSEMaps(N);
  837. // Finally, remove uses due to operands of this node, remove from the
  838. // AllNodes list, and delete the node.
  839. DeleteNodeNotInCSEMaps(N);
  840. }
  841. void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
  842. assert(N->getIterator() != AllNodes.begin() &&
  843. "Cannot delete the entry node!");
  844. assert(N->use_empty() && "Cannot delete a node that is not dead!");
  845. // Drop all of the operands and decrement used node's use counts.
  846. N->DropOperands();
  847. DeallocateNode(N);
  848. }
  849. void SDDbgInfo::add(SDDbgValue *V, bool isParameter) {
  850. assert(!(V->isVariadic() && isParameter));
  851. if (isParameter)
  852. ByvalParmDbgValues.push_back(V);
  853. else
  854. DbgValues.push_back(V);
  855. for (const SDNode *Node : V->getSDNodes())
  856. if (Node)
  857. DbgValMap[Node].push_back(V);
  858. }
  859. void SDDbgInfo::erase(const SDNode *Node) {
  860. DbgValMapType::iterator I = DbgValMap.find(Node);
  861. if (I == DbgValMap.end())
  862. return;
  863. for (auto &Val: I->second)
  864. Val->setIsInvalidated();
  865. DbgValMap.erase(I);
  866. }
  867. void SelectionDAG::DeallocateNode(SDNode *N) {
  868. // If we have operands, deallocate them.
  869. removeOperands(N);
  870. NodeAllocator.Deallocate(AllNodes.remove(N));
  871. // Set the opcode to DELETED_NODE to help catch bugs when node
  872. // memory is reallocated.
  873. // FIXME: There are places in SDag that have grown a dependency on the opcode
  874. // value in the released node.
  875. __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
  876. N->NodeType = ISD::DELETED_NODE;
  877. // If any of the SDDbgValue nodes refer to this SDNode, invalidate
  878. // them and forget about that node.
  879. DbgInfo->erase(N);
  880. }
  881. #ifndef NDEBUG
  882. /// VerifySDNode - Check the given SDNode. Aborts if it is invalid.
  883. static void VerifySDNode(SDNode *N) {
  884. switch (N->getOpcode()) {
  885. default:
  886. break;
  887. case ISD::BUILD_PAIR: {
  888. EVT VT = N->getValueType(0);
  889. assert(N->getNumValues() == 1 && "Too many results!");
  890. assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
  891. "Wrong return type!");
  892. assert(N->getNumOperands() == 2 && "Wrong number of operands!");
  893. assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
  894. "Mismatched operand types!");
  895. assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
  896. "Wrong operand type!");
  897. assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
  898. "Wrong return type size");
  899. break;
  900. }
  901. case ISD::BUILD_VECTOR: {
  902. assert(N->getNumValues() == 1 && "Too many results!");
  903. assert(N->getValueType(0).isVector() && "Wrong return type!");
  904. assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
  905. "Wrong number of operands!");
  906. EVT EltVT = N->getValueType(0).getVectorElementType();
  907. for (const SDUse &Op : N->ops()) {
  908. assert((Op.getValueType() == EltVT ||
  909. (EltVT.isInteger() && Op.getValueType().isInteger() &&
  910. EltVT.bitsLE(Op.getValueType()))) &&
  911. "Wrong operand type!");
  912. assert(Op.getValueType() == N->getOperand(0).getValueType() &&
  913. "Operands must all have the same type");
  914. }
  915. break;
  916. }
  917. }
  918. }
  919. #endif // NDEBUG
  920. /// Insert a newly allocated node into the DAG.
  921. ///
  922. /// Handles insertion into the all nodes list and CSE map, as well as
  923. /// verification and other common operations when a new node is allocated.
  924. void SelectionDAG::InsertNode(SDNode *N) {
  925. AllNodes.push_back(N);
  926. #ifndef NDEBUG
  927. N->PersistentId = NextPersistentId++;
  928. VerifySDNode(N);
  929. #endif
  930. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  931. DUL->NodeInserted(N);
  932. }
  933. /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
  934. /// correspond to it. This is useful when we're about to delete or repurpose
  935. /// the node. We don't want future request for structurally identical nodes
  936. /// to return N anymore.
  937. bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
  938. bool Erased = false;
  939. switch (N->getOpcode()) {
  940. case ISD::HANDLENODE: return false; // noop.
  941. case ISD::CONDCODE:
  942. assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
  943. "Cond code doesn't exist!");
  944. Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
  945. CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
  946. break;
  947. case ISD::ExternalSymbol:
  948. Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
  949. break;
  950. case ISD::TargetExternalSymbol: {
  951. ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
  952. Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
  953. ESN->getSymbol(), ESN->getTargetFlags()));
  954. break;
  955. }
  956. case ISD::MCSymbol: {
  957. auto *MCSN = cast<MCSymbolSDNode>(N);
  958. Erased = MCSymbols.erase(MCSN->getMCSymbol());
  959. break;
  960. }
  961. case ISD::VALUETYPE: {
  962. EVT VT = cast<VTSDNode>(N)->getVT();
  963. if (VT.isExtended()) {
  964. Erased = ExtendedValueTypeNodes.erase(VT);
  965. } else {
  966. Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
  967. ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
  968. }
  969. break;
  970. }
  971. default:
  972. // Remove it from the CSE Map.
  973. assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
  974. assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
  975. Erased = CSEMap.RemoveNode(N);
  976. break;
  977. }
  978. #ifndef NDEBUG
  979. // Verify that the node was actually in one of the CSE maps, unless it has a
  980. // flag result (which cannot be CSE'd) or is one of the special cases that are
  981. // not subject to CSE.
  982. if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
  983. !N->isMachineOpcode() && !doNotCSE(N)) {
  984. N->dump(this);
  985. dbgs() << "\n";
  986. llvm_unreachable("Node is not in map!");
  987. }
  988. #endif
  989. return Erased;
  990. }
  991. /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
  992. /// maps and modified in place. Add it back to the CSE maps, unless an identical
  993. /// node already exists, in which case transfer all its users to the existing
  994. /// node. This transfer can potentially trigger recursive merging.
  995. void
  996. SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
  997. // For node types that aren't CSE'd, just act as if no identical node
  998. // already exists.
  999. if (!doNotCSE(N)) {
  1000. SDNode *Existing = CSEMap.GetOrInsertNode(N);
  1001. if (Existing != N) {
  1002. // If there was already an existing matching node, use ReplaceAllUsesWith
  1003. // to replace the dead one with the existing one. This can cause
  1004. // recursive merging of other unrelated nodes down the line.
  1005. ReplaceAllUsesWith(N, Existing);
  1006. // N is now dead. Inform the listeners and delete it.
  1007. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  1008. DUL->NodeDeleted(N, Existing);
  1009. DeleteNodeNotInCSEMaps(N);
  1010. return;
  1011. }
  1012. }
  1013. // If the node doesn't already exist, we updated it. Inform listeners.
  1014. for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
  1015. DUL->NodeUpdated(N);
  1016. }
  1017. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  1018. /// were replaced with those specified. If this node is never memoized,
  1019. /// return null, otherwise return a pointer to the slot it would take. If a
  1020. /// node already exists with these operands, the slot will be non-null.
  1021. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
  1022. void *&InsertPos) {
  1023. if (doNotCSE(N))
  1024. return nullptr;
  1025. SDValue Ops[] = { Op };
  1026. FoldingSetNodeID ID;
  1027. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  1028. AddNodeIDCustom(ID, N);
  1029. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  1030. if (Node)
  1031. Node->intersectFlagsWith(N->getFlags());
  1032. return Node;
  1033. }
  1034. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  1035. /// were replaced with those specified. If this node is never memoized,
  1036. /// return null, otherwise return a pointer to the slot it would take. If a
  1037. /// node already exists with these operands, the slot will be non-null.
  1038. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
  1039. SDValue Op1, SDValue Op2,
  1040. void *&InsertPos) {
  1041. if (doNotCSE(N))
  1042. return nullptr;
  1043. SDValue Ops[] = { Op1, Op2 };
  1044. FoldingSetNodeID ID;
  1045. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  1046. AddNodeIDCustom(ID, N);
  1047. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  1048. if (Node)
  1049. Node->intersectFlagsWith(N->getFlags());
  1050. return Node;
  1051. }
  1052. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  1053. /// were replaced with those specified. If this node is never memoized,
  1054. /// return null, otherwise return a pointer to the slot it would take. If a
  1055. /// node already exists with these operands, the slot will be non-null.
  1056. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
  1057. void *&InsertPos) {
  1058. if (doNotCSE(N))
  1059. return nullptr;
  1060. FoldingSetNodeID ID;
  1061. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
  1062. AddNodeIDCustom(ID, N);
  1063. SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
  1064. if (Node)
  1065. Node->intersectFlagsWith(N->getFlags());
  1066. return Node;
  1067. }
  1068. Align SelectionDAG::getEVTAlign(EVT VT) const {
  1069. Type *Ty = VT == MVT::iPTR ?
  1070. PointerType::get(Type::getInt8Ty(*getContext()), 0) :
  1071. VT.getTypeForEVT(*getContext());
  1072. return getDataLayout().getABITypeAlign(Ty);
  1073. }
  1074. // EntryNode could meaningfully have debug info if we can find it...
  1075. SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
  1076. : TM(tm), OptLevel(OL),
  1077. EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
  1078. Root(getEntryNode()) {
  1079. InsertNode(&EntryNode);
  1080. DbgInfo = new SDDbgInfo();
  1081. }
  1082. void SelectionDAG::init(MachineFunction &NewMF,
  1083. OptimizationRemarkEmitter &NewORE,
  1084. Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
  1085. LegacyDivergenceAnalysis * Divergence,
  1086. ProfileSummaryInfo *PSIin,
  1087. BlockFrequencyInfo *BFIin) {
  1088. MF = &NewMF;
  1089. SDAGISelPass = PassPtr;
  1090. ORE = &NewORE;
  1091. TLI = getSubtarget().getTargetLowering();
  1092. TSI = getSubtarget().getSelectionDAGInfo();
  1093. LibInfo = LibraryInfo;
  1094. Context = &MF->getFunction().getContext();
  1095. DA = Divergence;
  1096. PSI = PSIin;
  1097. BFI = BFIin;
  1098. }
  1099. SelectionDAG::~SelectionDAG() {
  1100. assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
  1101. allnodes_clear();
  1102. OperandRecycler.clear(OperandAllocator);
  1103. delete DbgInfo;
  1104. }
  1105. bool SelectionDAG::shouldOptForSize() const {
  1106. return MF->getFunction().hasOptSize() ||
  1107. llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
  1108. }
  1109. void SelectionDAG::allnodes_clear() {
  1110. assert(&*AllNodes.begin() == &EntryNode);
  1111. AllNodes.remove(AllNodes.begin());
  1112. while (!AllNodes.empty())
  1113. DeallocateNode(&AllNodes.front());
  1114. #ifndef NDEBUG
  1115. NextPersistentId = 0;
  1116. #endif
  1117. }
  1118. SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
  1119. void *&InsertPos) {
  1120. SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  1121. if (N) {
  1122. switch (N->getOpcode()) {
  1123. default: break;
  1124. case ISD::Constant:
  1125. case ISD::ConstantFP:
  1126. llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
  1127. "debug location. Use another overload.");
  1128. }
  1129. }
  1130. return N;
  1131. }
  1132. SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
  1133. const SDLoc &DL, void *&InsertPos) {
  1134. SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  1135. if (N) {
  1136. switch (N->getOpcode()) {
  1137. case ISD::Constant:
  1138. case ISD::ConstantFP:
  1139. // Erase debug location from the node if the node is used at several
  1140. // different places. Do not propagate one location to all uses as it
  1141. // will cause a worse single stepping debugging experience.
  1142. if (N->getDebugLoc() != DL.getDebugLoc())
  1143. N->setDebugLoc(DebugLoc());
  1144. break;
  1145. default:
  1146. // When the node's point of use is located earlier in the instruction
  1147. // sequence than its prior point of use, update its debug info to the
  1148. // earlier location.
  1149. if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
  1150. N->setDebugLoc(DL.getDebugLoc());
  1151. break;
  1152. }
  1153. }
  1154. return N;
  1155. }
  1156. void SelectionDAG::clear() {
  1157. allnodes_clear();
  1158. OperandRecycler.clear(OperandAllocator);
  1159. OperandAllocator.Reset();
  1160. CSEMap.clear();
  1161. ExtendedValueTypeNodes.clear();
  1162. ExternalSymbols.clear();
  1163. TargetExternalSymbols.clear();
  1164. MCSymbols.clear();
  1165. SDCallSiteDbgInfo.clear();
  1166. std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
  1167. static_cast<CondCodeSDNode*>(nullptr));
  1168. std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
  1169. static_cast<SDNode*>(nullptr));
  1170. EntryNode.UseList = nullptr;
  1171. InsertNode(&EntryNode);
  1172. Root = getEntryNode();
  1173. DbgInfo->clear();
  1174. }
  1175. SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
  1176. return VT.bitsGT(Op.getValueType())
  1177. ? getNode(ISD::FP_EXTEND, DL, VT, Op)
  1178. : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
  1179. }
  1180. std::pair<SDValue, SDValue>
  1181. SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
  1182. const SDLoc &DL, EVT VT) {
  1183. assert(!VT.bitsEq(Op.getValueType()) &&
  1184. "Strict no-op FP extend/round not allowed.");
  1185. SDValue Res =
  1186. VT.bitsGT(Op.getValueType())
  1187. ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
  1188. : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
  1189. {Chain, Op, getIntPtrConstant(0, DL)});
  1190. return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
  1191. }
  1192. SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1193. return VT.bitsGT(Op.getValueType()) ?
  1194. getNode(ISD::ANY_EXTEND, DL, VT, Op) :
  1195. getNode(ISD::TRUNCATE, DL, VT, Op);
  1196. }
  1197. SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1198. return VT.bitsGT(Op.getValueType()) ?
  1199. getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
  1200. getNode(ISD::TRUNCATE, DL, VT, Op);
  1201. }
  1202. SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1203. return VT.bitsGT(Op.getValueType()) ?
  1204. getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
  1205. getNode(ISD::TRUNCATE, DL, VT, Op);
  1206. }
  1207. SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
  1208. EVT OpVT) {
  1209. if (VT.bitsLE(Op.getValueType()))
  1210. return getNode(ISD::TRUNCATE, SL, VT, Op);
  1211. TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
  1212. return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
  1213. }
  1214. SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
  1215. EVT OpVT = Op.getValueType();
  1216. assert(VT.isInteger() && OpVT.isInteger() &&
  1217. "Cannot getZeroExtendInReg FP types");
  1218. assert(VT.isVector() == OpVT.isVector() &&
  1219. "getZeroExtendInReg type should be vector iff the operand "
  1220. "type is vector!");
  1221. assert((!VT.isVector() ||
  1222. VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
  1223. "Vector element counts must match in getZeroExtendInReg");
  1224. assert(VT.bitsLE(OpVT) && "Not extending!");
  1225. if (OpVT == VT)
  1226. return Op;
  1227. APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
  1228. VT.getScalarSizeInBits());
  1229. return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
  1230. }
  1231. SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1232. // Only unsigned pointer semantics are supported right now. In the future this
  1233. // might delegate to TLI to check pointer signedness.
  1234. return getZExtOrTrunc(Op, DL, VT);
  1235. }
  1236. SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
  1237. // Only unsigned pointer semantics are supported right now. In the future this
  1238. // might delegate to TLI to check pointer signedness.
  1239. return getZeroExtendInReg(Op, DL, VT);
  1240. }
  1241. /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
  1242. SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
  1243. return getNode(ISD::XOR, DL, VT, Val, getAllOnesConstant(DL, VT));
  1244. }
  1245. SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
  1246. SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
  1247. return getNode(ISD::XOR, DL, VT, Val, TrueValue);
  1248. }
  1249. SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
  1250. EVT OpVT) {
  1251. if (!V)
  1252. return getConstant(0, DL, VT);
  1253. switch (TLI->getBooleanContents(OpVT)) {
  1254. case TargetLowering::ZeroOrOneBooleanContent:
  1255. case TargetLowering::UndefinedBooleanContent:
  1256. return getConstant(1, DL, VT);
  1257. case TargetLowering::ZeroOrNegativeOneBooleanContent:
  1258. return getAllOnesConstant(DL, VT);
  1259. }
  1260. llvm_unreachable("Unexpected boolean content enum!");
  1261. }
  1262. SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
  1263. bool isT, bool isO) {
  1264. EVT EltVT = VT.getScalarType();
  1265. assert((EltVT.getSizeInBits() >= 64 ||
  1266. (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
  1267. "getConstant with a uint64_t value that doesn't fit in the type!");
  1268. return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
  1269. }
  1270. SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
  1271. bool isT, bool isO) {
  1272. return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
  1273. }
  1274. SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
  1275. EVT VT, bool isT, bool isO) {
  1276. assert(VT.isInteger() && "Cannot create FP integer constant!");
  1277. EVT EltVT = VT.getScalarType();
  1278. const ConstantInt *Elt = &Val;
  1279. // In some cases the vector type is legal but the element type is illegal and
  1280. // needs to be promoted, for example v8i8 on ARM. In this case, promote the
  1281. // inserted value (the type does not need to match the vector element type).
  1282. // Any extra bits introduced will be truncated away.
  1283. if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
  1284. TargetLowering::TypePromoteInteger) {
  1285. EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
  1286. APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
  1287. Elt = ConstantInt::get(*getContext(), NewVal);
  1288. }
  1289. // In other cases the element type is illegal and needs to be expanded, for
  1290. // example v2i64 on MIPS32. In this case, find the nearest legal type, split
  1291. // the value into n parts and use a vector type with n-times the elements.
  1292. // Then bitcast to the type requested.
  1293. // Legalizing constants too early makes the DAGCombiner's job harder so we
  1294. // only legalize if the DAG tells us we must produce legal types.
  1295. else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
  1296. TLI->getTypeAction(*getContext(), EltVT) ==
  1297. TargetLowering::TypeExpandInteger) {
  1298. const APInt &NewVal = Elt->getValue();
  1299. EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
  1300. unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
  1301. // For scalable vectors, try to use a SPLAT_VECTOR_PARTS node.
  1302. if (VT.isScalableVector()) {
  1303. assert(EltVT.getSizeInBits() % ViaEltSizeInBits == 0 &&
  1304. "Can only handle an even split!");
  1305. unsigned Parts = EltVT.getSizeInBits() / ViaEltSizeInBits;
  1306. SmallVector<SDValue, 2> ScalarParts;
  1307. for (unsigned i = 0; i != Parts; ++i)
  1308. ScalarParts.push_back(getConstant(
  1309. NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
  1310. ViaEltVT, isT, isO));
  1311. return getNode(ISD::SPLAT_VECTOR_PARTS, DL, VT, ScalarParts);
  1312. }
  1313. unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
  1314. EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
  1315. // Check the temporary vector is the correct size. If this fails then
  1316. // getTypeToTransformTo() probably returned a type whose size (in bits)
  1317. // isn't a power-of-2 factor of the requested type size.
  1318. assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
  1319. SmallVector<SDValue, 2> EltParts;
  1320. for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i)
  1321. EltParts.push_back(getConstant(
  1322. NewVal.extractBits(ViaEltSizeInBits, i * ViaEltSizeInBits), DL,
  1323. ViaEltVT, isT, isO));
  1324. // EltParts is currently in little endian order. If we actually want
  1325. // big-endian order then reverse it now.
  1326. if (getDataLayout().isBigEndian())
  1327. std::reverse(EltParts.begin(), EltParts.end());
  1328. // The elements must be reversed when the element order is different
  1329. // to the endianness of the elements (because the BITCAST is itself a
  1330. // vector shuffle in this situation). However, we do not need any code to
  1331. // perform this reversal because getConstant() is producing a vector
  1332. // splat.
  1333. // This situation occurs in MIPS MSA.
  1334. SmallVector<SDValue, 8> Ops;
  1335. for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
  1336. llvm::append_range(Ops, EltParts);
  1337. SDValue V =
  1338. getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
  1339. return V;
  1340. }
  1341. assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
  1342. "APInt size does not match type size!");
  1343. unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
  1344. FoldingSetNodeID ID;
  1345. AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
  1346. ID.AddPointer(Elt);
  1347. ID.AddBoolean(isO);
  1348. void *IP = nullptr;
  1349. SDNode *N = nullptr;
  1350. if ((N = FindNodeOrInsertPos(ID, DL, IP)))
  1351. if (!VT.isVector())
  1352. return SDValue(N, 0);
  1353. if (!N) {
  1354. N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
  1355. CSEMap.InsertNode(N, IP);
  1356. InsertNode(N);
  1357. NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
  1358. }
  1359. SDValue Result(N, 0);
  1360. if (VT.isScalableVector())
  1361. Result = getSplatVector(VT, DL, Result);
  1362. else if (VT.isVector())
  1363. Result = getSplatBuildVector(VT, DL, Result);
  1364. return Result;
  1365. }
  1366. SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
  1367. bool isTarget) {
  1368. return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
  1369. }
  1370. SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
  1371. const SDLoc &DL, bool LegalTypes) {
  1372. assert(VT.isInteger() && "Shift amount is not an integer type!");
  1373. EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
  1374. return getConstant(Val, DL, ShiftVT);
  1375. }
  1376. SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
  1377. bool isTarget) {
  1378. return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
  1379. }
  1380. SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
  1381. bool isTarget) {
  1382. return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
  1383. }
  1384. SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
  1385. EVT VT, bool isTarget) {
  1386. assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
  1387. EVT EltVT = VT.getScalarType();
  1388. // Do the map lookup using the actual bit pattern for the floating point
  1389. // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
  1390. // we don't have issues with SNANs.
  1391. unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
  1392. FoldingSetNodeID ID;
  1393. AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
  1394. ID.AddPointer(&V);
  1395. void *IP = nullptr;
  1396. SDNode *N = nullptr;
  1397. if ((N = FindNodeOrInsertPos(ID, DL, IP)))
  1398. if (!VT.isVector())
  1399. return SDValue(N, 0);
  1400. if (!N) {
  1401. N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
  1402. CSEMap.InsertNode(N, IP);
  1403. InsertNode(N);
  1404. }
  1405. SDValue Result(N, 0);
  1406. if (VT.isScalableVector())
  1407. Result = getSplatVector(VT, DL, Result);
  1408. else if (VT.isVector())
  1409. Result = getSplatBuildVector(VT, DL, Result);
  1410. NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
  1411. return Result;
  1412. }
  1413. SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
  1414. bool isTarget) {
  1415. EVT EltVT = VT.getScalarType();
  1416. if (EltVT == MVT::f32)
  1417. return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
  1418. if (EltVT == MVT::f64)
  1419. return getConstantFP(APFloat(Val), DL, VT, isTarget);
  1420. if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
  1421. EltVT == MVT::f16 || EltVT == MVT::bf16) {
  1422. bool Ignored;
  1423. APFloat APF = APFloat(Val);
  1424. APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
  1425. &Ignored);
  1426. return getConstantFP(APF, DL, VT, isTarget);
  1427. }
  1428. llvm_unreachable("Unsupported type in getConstantFP");
  1429. }
  1430. SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
  1431. EVT VT, int64_t Offset, bool isTargetGA,
  1432. unsigned TargetFlags) {
  1433. assert((TargetFlags == 0 || isTargetGA) &&
  1434. "Cannot set target flags on target-independent globals");
  1435. // Truncate (with sign-extension) the offset value to the pointer size.
  1436. unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
  1437. if (BitWidth < 64)
  1438. Offset = SignExtend64(Offset, BitWidth);
  1439. unsigned Opc;
  1440. if (GV->isThreadLocal())
  1441. Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
  1442. else
  1443. Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
  1444. FoldingSetNodeID ID;
  1445. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1446. ID.AddPointer(GV);
  1447. ID.AddInteger(Offset);
  1448. ID.AddInteger(TargetFlags);
  1449. void *IP = nullptr;
  1450. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  1451. return SDValue(E, 0);
  1452. auto *N = newSDNode<GlobalAddressSDNode>(
  1453. Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
  1454. CSEMap.InsertNode(N, IP);
  1455. InsertNode(N);
  1456. return SDValue(N, 0);
  1457. }
  1458. SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
  1459. unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
  1460. FoldingSetNodeID ID;
  1461. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1462. ID.AddInteger(FI);
  1463. void *IP = nullptr;
  1464. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1465. return SDValue(E, 0);
  1466. auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
  1467. CSEMap.InsertNode(N, IP);
  1468. InsertNode(N);
  1469. return SDValue(N, 0);
  1470. }
  1471. SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
  1472. unsigned TargetFlags) {
  1473. assert((TargetFlags == 0 || isTarget) &&
  1474. "Cannot set target flags on target-independent jump tables");
  1475. unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
  1476. FoldingSetNodeID ID;
  1477. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1478. ID.AddInteger(JTI);
  1479. ID.AddInteger(TargetFlags);
  1480. void *IP = nullptr;
  1481. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1482. return SDValue(E, 0);
  1483. auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
  1484. CSEMap.InsertNode(N, IP);
  1485. InsertNode(N);
  1486. return SDValue(N, 0);
  1487. }
  1488. SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
  1489. MaybeAlign Alignment, int Offset,
  1490. bool isTarget, unsigned TargetFlags) {
  1491. assert((TargetFlags == 0 || isTarget) &&
  1492. "Cannot set target flags on target-independent globals");
  1493. if (!Alignment)
  1494. Alignment = shouldOptForSize()
  1495. ? getDataLayout().getABITypeAlign(C->getType())
  1496. : getDataLayout().getPrefTypeAlign(C->getType());
  1497. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  1498. FoldingSetNodeID ID;
  1499. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1500. ID.AddInteger(Alignment->value());
  1501. ID.AddInteger(Offset);
  1502. ID.AddPointer(C);
  1503. ID.AddInteger(TargetFlags);
  1504. void *IP = nullptr;
  1505. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1506. return SDValue(E, 0);
  1507. auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
  1508. TargetFlags);
  1509. CSEMap.InsertNode(N, IP);
  1510. InsertNode(N);
  1511. SDValue V = SDValue(N, 0);
  1512. NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
  1513. return V;
  1514. }
  1515. SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
  1516. MaybeAlign Alignment, int Offset,
  1517. bool isTarget, unsigned TargetFlags) {
  1518. assert((TargetFlags == 0 || isTarget) &&
  1519. "Cannot set target flags on target-independent globals");
  1520. if (!Alignment)
  1521. Alignment = getDataLayout().getPrefTypeAlign(C->getType());
  1522. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  1523. FoldingSetNodeID ID;
  1524. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1525. ID.AddInteger(Alignment->value());
  1526. ID.AddInteger(Offset);
  1527. C->addSelectionDAGCSEId(ID);
  1528. ID.AddInteger(TargetFlags);
  1529. void *IP = nullptr;
  1530. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1531. return SDValue(E, 0);
  1532. auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
  1533. TargetFlags);
  1534. CSEMap.InsertNode(N, IP);
  1535. InsertNode(N);
  1536. return SDValue(N, 0);
  1537. }
  1538. SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
  1539. unsigned TargetFlags) {
  1540. FoldingSetNodeID ID;
  1541. AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
  1542. ID.AddInteger(Index);
  1543. ID.AddInteger(Offset);
  1544. ID.AddInteger(TargetFlags);
  1545. void *IP = nullptr;
  1546. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1547. return SDValue(E, 0);
  1548. auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
  1549. CSEMap.InsertNode(N, IP);
  1550. InsertNode(N);
  1551. return SDValue(N, 0);
  1552. }
  1553. SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
  1554. FoldingSetNodeID ID;
  1555. AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
  1556. ID.AddPointer(MBB);
  1557. void *IP = nullptr;
  1558. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1559. return SDValue(E, 0);
  1560. auto *N = newSDNode<BasicBlockSDNode>(MBB);
  1561. CSEMap.InsertNode(N, IP);
  1562. InsertNode(N);
  1563. return SDValue(N, 0);
  1564. }
  1565. SDValue SelectionDAG::getValueType(EVT VT) {
  1566. if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
  1567. ValueTypeNodes.size())
  1568. ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
  1569. SDNode *&N = VT.isExtended() ?
  1570. ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
  1571. if (N) return SDValue(N, 0);
  1572. N = newSDNode<VTSDNode>(VT);
  1573. InsertNode(N);
  1574. return SDValue(N, 0);
  1575. }
  1576. SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
  1577. SDNode *&N = ExternalSymbols[Sym];
  1578. if (N) return SDValue(N, 0);
  1579. N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
  1580. InsertNode(N);
  1581. return SDValue(N, 0);
  1582. }
  1583. SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
  1584. SDNode *&N = MCSymbols[Sym];
  1585. if (N)
  1586. return SDValue(N, 0);
  1587. N = newSDNode<MCSymbolSDNode>(Sym, VT);
  1588. InsertNode(N);
  1589. return SDValue(N, 0);
  1590. }
  1591. SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
  1592. unsigned TargetFlags) {
  1593. SDNode *&N =
  1594. TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
  1595. if (N) return SDValue(N, 0);
  1596. N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
  1597. InsertNode(N);
  1598. return SDValue(N, 0);
  1599. }
  1600. SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
  1601. if ((unsigned)Cond >= CondCodeNodes.size())
  1602. CondCodeNodes.resize(Cond+1);
  1603. if (!CondCodeNodes[Cond]) {
  1604. auto *N = newSDNode<CondCodeSDNode>(Cond);
  1605. CondCodeNodes[Cond] = N;
  1606. InsertNode(N);
  1607. }
  1608. return SDValue(CondCodeNodes[Cond], 0);
  1609. }
  1610. SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT) {
  1611. APInt One(ResVT.getScalarSizeInBits(), 1);
  1612. return getStepVector(DL, ResVT, One);
  1613. }
  1614. SDValue SelectionDAG::getStepVector(const SDLoc &DL, EVT ResVT, APInt StepVal) {
  1615. assert(ResVT.getScalarSizeInBits() == StepVal.getBitWidth());
  1616. if (ResVT.isScalableVector())
  1617. return getNode(
  1618. ISD::STEP_VECTOR, DL, ResVT,
  1619. getTargetConstant(StepVal, DL, ResVT.getVectorElementType()));
  1620. SmallVector<SDValue, 16> OpsStepConstants;
  1621. for (uint64_t i = 0; i < ResVT.getVectorNumElements(); i++)
  1622. OpsStepConstants.push_back(
  1623. getConstant(StepVal * i, DL, ResVT.getVectorElementType()));
  1624. return getBuildVector(ResVT, DL, OpsStepConstants);
  1625. }
  1626. /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
  1627. /// point at N1 to point at N2 and indices that point at N2 to point at N1.
  1628. static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
  1629. std::swap(N1, N2);
  1630. ShuffleVectorSDNode::commuteMask(M);
  1631. }
  1632. SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
  1633. SDValue N2, ArrayRef<int> Mask) {
  1634. assert(VT.getVectorNumElements() == Mask.size() &&
  1635. "Must have the same number of vector elements as mask elements!");
  1636. assert(VT == N1.getValueType() && VT == N2.getValueType() &&
  1637. "Invalid VECTOR_SHUFFLE");
  1638. // Canonicalize shuffle undef, undef -> undef
  1639. if (N1.isUndef() && N2.isUndef())
  1640. return getUNDEF(VT);
  1641. // Validate that all indices in Mask are within the range of the elements
  1642. // input to the shuffle.
  1643. int NElts = Mask.size();
  1644. assert(llvm::all_of(Mask,
  1645. [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
  1646. "Index out of range");
  1647. // Copy the mask so we can do any needed cleanup.
  1648. SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
  1649. // Canonicalize shuffle v, v -> v, undef
  1650. if (N1 == N2) {
  1651. N2 = getUNDEF(VT);
  1652. for (int i = 0; i != NElts; ++i)
  1653. if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
  1654. }
  1655. // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
  1656. if (N1.isUndef())
  1657. commuteShuffle(N1, N2, MaskVec);
  1658. if (TLI->hasVectorBlend()) {
  1659. // If shuffling a splat, try to blend the splat instead. We do this here so
  1660. // that even when this arises during lowering we don't have to re-handle it.
  1661. auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
  1662. BitVector UndefElements;
  1663. SDValue Splat = BV->getSplatValue(&UndefElements);
  1664. if (!Splat)
  1665. return;
  1666. for (int i = 0; i < NElts; ++i) {
  1667. if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
  1668. continue;
  1669. // If this input comes from undef, mark it as such.
  1670. if (UndefElements[MaskVec[i] - Offset]) {
  1671. MaskVec[i] = -1;
  1672. continue;
  1673. }
  1674. // If we can blend a non-undef lane, use that instead.
  1675. if (!UndefElements[i])
  1676. MaskVec[i] = i + Offset;
  1677. }
  1678. };
  1679. if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
  1680. BlendSplat(N1BV, 0);
  1681. if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
  1682. BlendSplat(N2BV, NElts);
  1683. }
  1684. // Canonicalize all index into lhs, -> shuffle lhs, undef
  1685. // Canonicalize all index into rhs, -> shuffle rhs, undef
  1686. bool AllLHS = true, AllRHS = true;
  1687. bool N2Undef = N2.isUndef();
  1688. for (int i = 0; i != NElts; ++i) {
  1689. if (MaskVec[i] >= NElts) {
  1690. if (N2Undef)
  1691. MaskVec[i] = -1;
  1692. else
  1693. AllLHS = false;
  1694. } else if (MaskVec[i] >= 0) {
  1695. AllRHS = false;
  1696. }
  1697. }
  1698. if (AllLHS && AllRHS)
  1699. return getUNDEF(VT);
  1700. if (AllLHS && !N2Undef)
  1701. N2 = getUNDEF(VT);
  1702. if (AllRHS) {
  1703. N1 = getUNDEF(VT);
  1704. commuteShuffle(N1, N2, MaskVec);
  1705. }
  1706. // Reset our undef status after accounting for the mask.
  1707. N2Undef = N2.isUndef();
  1708. // Re-check whether both sides ended up undef.
  1709. if (N1.isUndef() && N2Undef)
  1710. return getUNDEF(VT);
  1711. // If Identity shuffle return that node.
  1712. bool Identity = true, AllSame = true;
  1713. for (int i = 0; i != NElts; ++i) {
  1714. if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
  1715. if (MaskVec[i] != MaskVec[0]) AllSame = false;
  1716. }
  1717. if (Identity && NElts)
  1718. return N1;
  1719. // Shuffling a constant splat doesn't change the result.
  1720. if (N2Undef) {
  1721. SDValue V = N1;
  1722. // Look through any bitcasts. We check that these don't change the number
  1723. // (and size) of elements and just changes their types.
  1724. while (V.getOpcode() == ISD::BITCAST)
  1725. V = V->getOperand(0);
  1726. // A splat should always show up as a build vector node.
  1727. if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
  1728. BitVector UndefElements;
  1729. SDValue Splat = BV->getSplatValue(&UndefElements);
  1730. // If this is a splat of an undef, shuffling it is also undef.
  1731. if (Splat && Splat.isUndef())
  1732. return getUNDEF(VT);
  1733. bool SameNumElts =
  1734. V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
  1735. // We only have a splat which can skip shuffles if there is a splatted
  1736. // value and no undef lanes rearranged by the shuffle.
  1737. if (Splat && UndefElements.none()) {
  1738. // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
  1739. // number of elements match or the value splatted is a zero constant.
  1740. if (SameNumElts)
  1741. return N1;
  1742. if (auto *C = dyn_cast<ConstantSDNode>(Splat))
  1743. if (C->isZero())
  1744. return N1;
  1745. }
  1746. // If the shuffle itself creates a splat, build the vector directly.
  1747. if (AllSame && SameNumElts) {
  1748. EVT BuildVT = BV->getValueType(0);
  1749. const SDValue &Splatted = BV->getOperand(MaskVec[0]);
  1750. SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
  1751. // We may have jumped through bitcasts, so the type of the
  1752. // BUILD_VECTOR may not match the type of the shuffle.
  1753. if (BuildVT != VT)
  1754. NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
  1755. return NewBV;
  1756. }
  1757. }
  1758. }
  1759. FoldingSetNodeID ID;
  1760. SDValue Ops[2] = { N1, N2 };
  1761. AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
  1762. for (int i = 0; i != NElts; ++i)
  1763. ID.AddInteger(MaskVec[i]);
  1764. void* IP = nullptr;
  1765. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  1766. return SDValue(E, 0);
  1767. // Allocate the mask array for the node out of the BumpPtrAllocator, since
  1768. // SDNode doesn't have access to it. This memory will be "leaked" when
  1769. // the node is deallocated, but recovered when the NodeAllocator is released.
  1770. int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
  1771. llvm::copy(MaskVec, MaskAlloc);
  1772. auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
  1773. dl.getDebugLoc(), MaskAlloc);
  1774. createOperands(N, Ops);
  1775. CSEMap.InsertNode(N, IP);
  1776. InsertNode(N);
  1777. SDValue V = SDValue(N, 0);
  1778. NewSDValueDbgMsg(V, "Creating new node: ", this);
  1779. return V;
  1780. }
  1781. SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
  1782. EVT VT = SV.getValueType(0);
  1783. SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
  1784. ShuffleVectorSDNode::commuteMask(MaskVec);
  1785. SDValue Op0 = SV.getOperand(0);
  1786. SDValue Op1 = SV.getOperand(1);
  1787. return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
  1788. }
  1789. SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
  1790. FoldingSetNodeID ID;
  1791. AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
  1792. ID.AddInteger(RegNo);
  1793. void *IP = nullptr;
  1794. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1795. return SDValue(E, 0);
  1796. auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
  1797. N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
  1798. CSEMap.InsertNode(N, IP);
  1799. InsertNode(N);
  1800. return SDValue(N, 0);
  1801. }
  1802. SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
  1803. FoldingSetNodeID ID;
  1804. AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
  1805. ID.AddPointer(RegMask);
  1806. void *IP = nullptr;
  1807. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1808. return SDValue(E, 0);
  1809. auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
  1810. CSEMap.InsertNode(N, IP);
  1811. InsertNode(N);
  1812. return SDValue(N, 0);
  1813. }
  1814. SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
  1815. MCSymbol *Label) {
  1816. return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
  1817. }
  1818. SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
  1819. SDValue Root, MCSymbol *Label) {
  1820. FoldingSetNodeID ID;
  1821. SDValue Ops[] = { Root };
  1822. AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
  1823. ID.AddPointer(Label);
  1824. void *IP = nullptr;
  1825. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1826. return SDValue(E, 0);
  1827. auto *N =
  1828. newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
  1829. createOperands(N, Ops);
  1830. CSEMap.InsertNode(N, IP);
  1831. InsertNode(N);
  1832. return SDValue(N, 0);
  1833. }
  1834. SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
  1835. int64_t Offset, bool isTarget,
  1836. unsigned TargetFlags) {
  1837. unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
  1838. FoldingSetNodeID ID;
  1839. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1840. ID.AddPointer(BA);
  1841. ID.AddInteger(Offset);
  1842. ID.AddInteger(TargetFlags);
  1843. void *IP = nullptr;
  1844. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1845. return SDValue(E, 0);
  1846. auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
  1847. CSEMap.InsertNode(N, IP);
  1848. InsertNode(N);
  1849. return SDValue(N, 0);
  1850. }
  1851. SDValue SelectionDAG::getSrcValue(const Value *V) {
  1852. FoldingSetNodeID ID;
  1853. AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
  1854. ID.AddPointer(V);
  1855. void *IP = nullptr;
  1856. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1857. return SDValue(E, 0);
  1858. auto *N = newSDNode<SrcValueSDNode>(V);
  1859. CSEMap.InsertNode(N, IP);
  1860. InsertNode(N);
  1861. return SDValue(N, 0);
  1862. }
  1863. SDValue SelectionDAG::getMDNode(const MDNode *MD) {
  1864. FoldingSetNodeID ID;
  1865. AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
  1866. ID.AddPointer(MD);
  1867. void *IP = nullptr;
  1868. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1869. return SDValue(E, 0);
  1870. auto *N = newSDNode<MDNodeSDNode>(MD);
  1871. CSEMap.InsertNode(N, IP);
  1872. InsertNode(N);
  1873. return SDValue(N, 0);
  1874. }
  1875. SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
  1876. if (VT == V.getValueType())
  1877. return V;
  1878. return getNode(ISD::BITCAST, SDLoc(V), VT, V);
  1879. }
  1880. SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
  1881. unsigned SrcAS, unsigned DestAS) {
  1882. SDValue Ops[] = {Ptr};
  1883. FoldingSetNodeID ID;
  1884. AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
  1885. ID.AddInteger(SrcAS);
  1886. ID.AddInteger(DestAS);
  1887. void *IP = nullptr;
  1888. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  1889. return SDValue(E, 0);
  1890. auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  1891. VT, SrcAS, DestAS);
  1892. createOperands(N, Ops);
  1893. CSEMap.InsertNode(N, IP);
  1894. InsertNode(N);
  1895. return SDValue(N, 0);
  1896. }
  1897. SDValue SelectionDAG::getFreeze(SDValue V) {
  1898. return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
  1899. }
  1900. /// getShiftAmountOperand - Return the specified value casted to
  1901. /// the target's desired shift amount type.
  1902. SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
  1903. EVT OpTy = Op.getValueType();
  1904. EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
  1905. if (OpTy == ShTy || OpTy.isVector()) return Op;
  1906. return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
  1907. }
  1908. SDValue SelectionDAG::expandVAArg(SDNode *Node) {
  1909. SDLoc dl(Node);
  1910. const TargetLowering &TLI = getTargetLoweringInfo();
  1911. const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
  1912. EVT VT = Node->getValueType(0);
  1913. SDValue Tmp1 = Node->getOperand(0);
  1914. SDValue Tmp2 = Node->getOperand(1);
  1915. const MaybeAlign MA(Node->getConstantOperandVal(3));
  1916. SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
  1917. Tmp2, MachinePointerInfo(V));
  1918. SDValue VAList = VAListLoad;
  1919. if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
  1920. VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  1921. getConstant(MA->value() - 1, dl, VAList.getValueType()));
  1922. VAList =
  1923. getNode(ISD::AND, dl, VAList.getValueType(), VAList,
  1924. getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
  1925. }
  1926. // Increment the pointer, VAList, to the next vaarg
  1927. Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  1928. getConstant(getDataLayout().getTypeAllocSize(
  1929. VT.getTypeForEVT(*getContext())),
  1930. dl, VAList.getValueType()));
  1931. // Store the incremented VAList to the legalized pointer
  1932. Tmp1 =
  1933. getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
  1934. // Load the actual argument out of the pointer VAList
  1935. return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
  1936. }
  1937. SDValue SelectionDAG::expandVACopy(SDNode *Node) {
  1938. SDLoc dl(Node);
  1939. const TargetLowering &TLI = getTargetLoweringInfo();
  1940. // This defaults to loading a pointer from the input and storing it to the
  1941. // output, returning the chain.
  1942. const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
  1943. const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
  1944. SDValue Tmp1 =
  1945. getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
  1946. Node->getOperand(2), MachinePointerInfo(VS));
  1947. return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
  1948. MachinePointerInfo(VD));
  1949. }
  1950. Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
  1951. const DataLayout &DL = getDataLayout();
  1952. Type *Ty = VT.getTypeForEVT(*getContext());
  1953. Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
  1954. if (TLI->isTypeLegal(VT) || !VT.isVector())
  1955. return RedAlign;
  1956. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  1957. const Align StackAlign = TFI->getStackAlign();
  1958. // See if we can choose a smaller ABI alignment in cases where it's an
  1959. // illegal vector type that will get broken down.
  1960. if (RedAlign > StackAlign) {
  1961. EVT IntermediateVT;
  1962. MVT RegisterVT;
  1963. unsigned NumIntermediates;
  1964. TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
  1965. NumIntermediates, RegisterVT);
  1966. Ty = IntermediateVT.getTypeForEVT(*getContext());
  1967. Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
  1968. if (RedAlign2 < RedAlign)
  1969. RedAlign = RedAlign2;
  1970. }
  1971. return RedAlign;
  1972. }
  1973. SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
  1974. MachineFrameInfo &MFI = MF->getFrameInfo();
  1975. const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
  1976. int StackID = 0;
  1977. if (Bytes.isScalable())
  1978. StackID = TFI->getStackIDForScalableVectors();
  1979. // The stack id gives an indication of whether the object is scalable or
  1980. // not, so it's safe to pass in the minimum size here.
  1981. int FrameIdx = MFI.CreateStackObject(Bytes.getKnownMinSize(), Alignment,
  1982. false, nullptr, StackID);
  1983. return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
  1984. }
  1985. SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
  1986. Type *Ty = VT.getTypeForEVT(*getContext());
  1987. Align StackAlign =
  1988. std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
  1989. return CreateStackTemporary(VT.getStoreSize(), StackAlign);
  1990. }
  1991. SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
  1992. TypeSize VT1Size = VT1.getStoreSize();
  1993. TypeSize VT2Size = VT2.getStoreSize();
  1994. assert(VT1Size.isScalable() == VT2Size.isScalable() &&
  1995. "Don't know how to choose the maximum size when creating a stack "
  1996. "temporary");
  1997. TypeSize Bytes =
  1998. VT1Size.getKnownMinSize() > VT2Size.getKnownMinSize() ? VT1Size : VT2Size;
  1999. Type *Ty1 = VT1.getTypeForEVT(*getContext());
  2000. Type *Ty2 = VT2.getTypeForEVT(*getContext());
  2001. const DataLayout &DL = getDataLayout();
  2002. Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
  2003. return CreateStackTemporary(Bytes, Align);
  2004. }
  2005. SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
  2006. ISD::CondCode Cond, const SDLoc &dl) {
  2007. EVT OpVT = N1.getValueType();
  2008. // These setcc operations always fold.
  2009. switch (Cond) {
  2010. default: break;
  2011. case ISD::SETFALSE:
  2012. case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
  2013. case ISD::SETTRUE:
  2014. case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
  2015. case ISD::SETOEQ:
  2016. case ISD::SETOGT:
  2017. case ISD::SETOGE:
  2018. case ISD::SETOLT:
  2019. case ISD::SETOLE:
  2020. case ISD::SETONE:
  2021. case ISD::SETO:
  2022. case ISD::SETUO:
  2023. case ISD::SETUEQ:
  2024. case ISD::SETUNE:
  2025. assert(!OpVT.isInteger() && "Illegal setcc for integer!");
  2026. break;
  2027. }
  2028. if (OpVT.isInteger()) {
  2029. // For EQ and NE, we can always pick a value for the undef to make the
  2030. // predicate pass or fail, so we can return undef.
  2031. // Matches behavior in llvm::ConstantFoldCompareInstruction.
  2032. // icmp eq/ne X, undef -> undef.
  2033. if ((N1.isUndef() || N2.isUndef()) &&
  2034. (Cond == ISD::SETEQ || Cond == ISD::SETNE))
  2035. return getUNDEF(VT);
  2036. // If both operands are undef, we can return undef for int comparison.
  2037. // icmp undef, undef -> undef.
  2038. if (N1.isUndef() && N2.isUndef())
  2039. return getUNDEF(VT);
  2040. // icmp X, X -> true/false
  2041. // icmp X, undef -> true/false because undef could be X.
  2042. if (N1 == N2)
  2043. return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
  2044. }
  2045. if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
  2046. const APInt &C2 = N2C->getAPIntValue();
  2047. if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
  2048. const APInt &C1 = N1C->getAPIntValue();
  2049. return getBoolConstant(ICmpInst::compare(C1, C2, getICmpCondCode(Cond)),
  2050. dl, VT, OpVT);
  2051. }
  2052. }
  2053. auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  2054. auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  2055. if (N1CFP && N2CFP) {
  2056. APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
  2057. switch (Cond) {
  2058. default: break;
  2059. case ISD::SETEQ: if (R==APFloat::cmpUnordered)
  2060. return getUNDEF(VT);
  2061. LLVM_FALLTHROUGH;
  2062. case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
  2063. OpVT);
  2064. case ISD::SETNE: if (R==APFloat::cmpUnordered)
  2065. return getUNDEF(VT);
  2066. LLVM_FALLTHROUGH;
  2067. case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  2068. R==APFloat::cmpLessThan, dl, VT,
  2069. OpVT);
  2070. case ISD::SETLT: if (R==APFloat::cmpUnordered)
  2071. return getUNDEF(VT);
  2072. LLVM_FALLTHROUGH;
  2073. case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
  2074. OpVT);
  2075. case ISD::SETGT: if (R==APFloat::cmpUnordered)
  2076. return getUNDEF(VT);
  2077. LLVM_FALLTHROUGH;
  2078. case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
  2079. VT, OpVT);
  2080. case ISD::SETLE: if (R==APFloat::cmpUnordered)
  2081. return getUNDEF(VT);
  2082. LLVM_FALLTHROUGH;
  2083. case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
  2084. R==APFloat::cmpEqual, dl, VT,
  2085. OpVT);
  2086. case ISD::SETGE: if (R==APFloat::cmpUnordered)
  2087. return getUNDEF(VT);
  2088. LLVM_FALLTHROUGH;
  2089. case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  2090. R==APFloat::cmpEqual, dl, VT, OpVT);
  2091. case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
  2092. OpVT);
  2093. case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
  2094. OpVT);
  2095. case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
  2096. R==APFloat::cmpEqual, dl, VT,
  2097. OpVT);
  2098. case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
  2099. OpVT);
  2100. case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
  2101. R==APFloat::cmpLessThan, dl, VT,
  2102. OpVT);
  2103. case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  2104. R==APFloat::cmpUnordered, dl, VT,
  2105. OpVT);
  2106. case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
  2107. VT, OpVT);
  2108. case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
  2109. OpVT);
  2110. }
  2111. } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
  2112. // Ensure that the constant occurs on the RHS.
  2113. ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
  2114. if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
  2115. return SDValue();
  2116. return getSetCC(dl, VT, N2, N1, SwappedCond);
  2117. } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
  2118. (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
  2119. // If an operand is known to be a nan (or undef that could be a nan), we can
  2120. // fold it.
  2121. // Choosing NaN for the undef will always make unordered comparison succeed
  2122. // and ordered comparison fails.
  2123. // Matches behavior in llvm::ConstantFoldCompareInstruction.
  2124. switch (ISD::getUnorderedFlavor(Cond)) {
  2125. default:
  2126. llvm_unreachable("Unknown flavor!");
  2127. case 0: // Known false.
  2128. return getBoolConstant(false, dl, VT, OpVT);
  2129. case 1: // Known true.
  2130. return getBoolConstant(true, dl, VT, OpVT);
  2131. case 2: // Undefined.
  2132. return getUNDEF(VT);
  2133. }
  2134. }
  2135. // Could not fold it.
  2136. return SDValue();
  2137. }
  2138. /// See if the specified operand can be simplified with the knowledge that only
  2139. /// the bits specified by DemandedBits are used.
  2140. /// TODO: really we should be making this into the DAG equivalent of
  2141. /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
  2142. SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
  2143. EVT VT = V.getValueType();
  2144. if (VT.isScalableVector())
  2145. return SDValue();
  2146. APInt DemandedElts = VT.isVector()
  2147. ? APInt::getAllOnes(VT.getVectorNumElements())
  2148. : APInt(1, 1);
  2149. return GetDemandedBits(V, DemandedBits, DemandedElts);
  2150. }
  2151. /// See if the specified operand can be simplified with the knowledge that only
  2152. /// the bits specified by DemandedBits are used in the elements specified by
  2153. /// DemandedElts.
  2154. /// TODO: really we should be making this into the DAG equivalent of
  2155. /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
  2156. SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
  2157. const APInt &DemandedElts) {
  2158. switch (V.getOpcode()) {
  2159. default:
  2160. return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
  2161. *this);
  2162. case ISD::Constant: {
  2163. const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
  2164. APInt NewVal = CVal & DemandedBits;
  2165. if (NewVal != CVal)
  2166. return getConstant(NewVal, SDLoc(V), V.getValueType());
  2167. break;
  2168. }
  2169. case ISD::SRL:
  2170. // Only look at single-use SRLs.
  2171. if (!V.getNode()->hasOneUse())
  2172. break;
  2173. if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
  2174. // See if we can recursively simplify the LHS.
  2175. unsigned Amt = RHSC->getZExtValue();
  2176. // Watch out for shift count overflow though.
  2177. if (Amt >= DemandedBits.getBitWidth())
  2178. break;
  2179. APInt SrcDemandedBits = DemandedBits << Amt;
  2180. if (SDValue SimplifyLHS =
  2181. GetDemandedBits(V.getOperand(0), SrcDemandedBits))
  2182. return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
  2183. V.getOperand(1));
  2184. }
  2185. break;
  2186. }
  2187. return SDValue();
  2188. }
  2189. /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
  2190. /// use this predicate to simplify operations downstream.
  2191. bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
  2192. unsigned BitWidth = Op.getScalarValueSizeInBits();
  2193. return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
  2194. }
  2195. /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
  2196. /// this predicate to simplify operations downstream. Mask is known to be zero
  2197. /// for bits that V cannot have.
  2198. bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
  2199. unsigned Depth) const {
  2200. return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
  2201. }
  2202. /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
  2203. /// DemandedElts. We use this predicate to simplify operations downstream.
  2204. /// Mask is known to be zero for bits that V cannot have.
  2205. bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
  2206. const APInt &DemandedElts,
  2207. unsigned Depth) const {
  2208. return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
  2209. }
  2210. /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
  2211. bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
  2212. unsigned Depth) const {
  2213. return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
  2214. }
  2215. /// isSplatValue - Return true if the vector V has the same value
  2216. /// across all DemandedElts. For scalable vectors it does not make
  2217. /// sense to specify which elements are demanded or undefined, therefore
  2218. /// they are simply ignored.
  2219. bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
  2220. APInt &UndefElts, unsigned Depth) const {
  2221. unsigned Opcode = V.getOpcode();
  2222. EVT VT = V.getValueType();
  2223. assert(VT.isVector() && "Vector type expected");
  2224. if (!VT.isScalableVector() && !DemandedElts)
  2225. return false; // No demanded elts, better to assume we don't know anything.
  2226. if (Depth >= MaxRecursionDepth)
  2227. return false; // Limit search depth.
  2228. // Deal with some common cases here that work for both fixed and scalable
  2229. // vector types.
  2230. switch (Opcode) {
  2231. case ISD::SPLAT_VECTOR:
  2232. UndefElts = V.getOperand(0).isUndef()
  2233. ? APInt::getAllOnes(DemandedElts.getBitWidth())
  2234. : APInt(DemandedElts.getBitWidth(), 0);
  2235. return true;
  2236. case ISD::ADD:
  2237. case ISD::SUB:
  2238. case ISD::AND:
  2239. case ISD::XOR:
  2240. case ISD::OR: {
  2241. APInt UndefLHS, UndefRHS;
  2242. SDValue LHS = V.getOperand(0);
  2243. SDValue RHS = V.getOperand(1);
  2244. if (isSplatValue(LHS, DemandedElts, UndefLHS, Depth + 1) &&
  2245. isSplatValue(RHS, DemandedElts, UndefRHS, Depth + 1)) {
  2246. UndefElts = UndefLHS | UndefRHS;
  2247. return true;
  2248. }
  2249. return false;
  2250. }
  2251. case ISD::ABS:
  2252. case ISD::TRUNCATE:
  2253. case ISD::SIGN_EXTEND:
  2254. case ISD::ZERO_EXTEND:
  2255. return isSplatValue(V.getOperand(0), DemandedElts, UndefElts, Depth + 1);
  2256. default:
  2257. if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
  2258. Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
  2259. return TLI->isSplatValueForTargetNode(V, DemandedElts, UndefElts, Depth);
  2260. break;
  2261. }
  2262. // We don't support other cases than those above for scalable vectors at
  2263. // the moment.
  2264. if (VT.isScalableVector())
  2265. return false;
  2266. unsigned NumElts = VT.getVectorNumElements();
  2267. assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
  2268. UndefElts = APInt::getZero(NumElts);
  2269. switch (Opcode) {
  2270. case ISD::BUILD_VECTOR: {
  2271. SDValue Scl;
  2272. for (unsigned i = 0; i != NumElts; ++i) {
  2273. SDValue Op = V.getOperand(i);
  2274. if (Op.isUndef()) {
  2275. UndefElts.setBit(i);
  2276. continue;
  2277. }
  2278. if (!DemandedElts[i])
  2279. continue;
  2280. if (Scl && Scl != Op)
  2281. return false;
  2282. Scl = Op;
  2283. }
  2284. return true;
  2285. }
  2286. case ISD::VECTOR_SHUFFLE: {
  2287. // Check if this is a shuffle node doing a splat.
  2288. // TODO: Do we need to handle shuffle(splat, undef, mask)?
  2289. int SplatIndex = -1;
  2290. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
  2291. for (int i = 0; i != (int)NumElts; ++i) {
  2292. int M = Mask[i];
  2293. if (M < 0) {
  2294. UndefElts.setBit(i);
  2295. continue;
  2296. }
  2297. if (!DemandedElts[i])
  2298. continue;
  2299. if (0 <= SplatIndex && SplatIndex != M)
  2300. return false;
  2301. SplatIndex = M;
  2302. }
  2303. return true;
  2304. }
  2305. case ISD::EXTRACT_SUBVECTOR: {
  2306. // Offset the demanded elts by the subvector index.
  2307. SDValue Src = V.getOperand(0);
  2308. // We don't support scalable vectors at the moment.
  2309. if (Src.getValueType().isScalableVector())
  2310. return false;
  2311. uint64_t Idx = V.getConstantOperandVal(1);
  2312. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2313. APInt UndefSrcElts;
  2314. APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  2315. if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
  2316. UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
  2317. return true;
  2318. }
  2319. break;
  2320. }
  2321. case ISD::ANY_EXTEND_VECTOR_INREG:
  2322. case ISD::SIGN_EXTEND_VECTOR_INREG:
  2323. case ISD::ZERO_EXTEND_VECTOR_INREG: {
  2324. // Widen the demanded elts by the src element count.
  2325. SDValue Src = V.getOperand(0);
  2326. // We don't support scalable vectors at the moment.
  2327. if (Src.getValueType().isScalableVector())
  2328. return false;
  2329. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2330. APInt UndefSrcElts;
  2331. APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
  2332. if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts, Depth + 1)) {
  2333. UndefElts = UndefSrcElts.truncOrSelf(NumElts);
  2334. return true;
  2335. }
  2336. break;
  2337. }
  2338. }
  2339. return false;
  2340. }
  2341. /// Helper wrapper to main isSplatValue function.
  2342. bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) const {
  2343. EVT VT = V.getValueType();
  2344. assert(VT.isVector() && "Vector type expected");
  2345. APInt UndefElts;
  2346. APInt DemandedElts;
  2347. // For now we don't support this with scalable vectors.
  2348. if (!VT.isScalableVector())
  2349. DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
  2350. return isSplatValue(V, DemandedElts, UndefElts) &&
  2351. (AllowUndefs || !UndefElts);
  2352. }
  2353. SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
  2354. V = peekThroughExtractSubvectors(V);
  2355. EVT VT = V.getValueType();
  2356. unsigned Opcode = V.getOpcode();
  2357. switch (Opcode) {
  2358. default: {
  2359. APInt UndefElts;
  2360. APInt DemandedElts;
  2361. if (!VT.isScalableVector())
  2362. DemandedElts = APInt::getAllOnes(VT.getVectorNumElements());
  2363. if (isSplatValue(V, DemandedElts, UndefElts)) {
  2364. if (VT.isScalableVector()) {
  2365. // DemandedElts and UndefElts are ignored for scalable vectors, since
  2366. // the only supported cases are SPLAT_VECTOR nodes.
  2367. SplatIdx = 0;
  2368. } else {
  2369. // Handle case where all demanded elements are UNDEF.
  2370. if (DemandedElts.isSubsetOf(UndefElts)) {
  2371. SplatIdx = 0;
  2372. return getUNDEF(VT);
  2373. }
  2374. SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
  2375. }
  2376. return V;
  2377. }
  2378. break;
  2379. }
  2380. case ISD::SPLAT_VECTOR:
  2381. SplatIdx = 0;
  2382. return V;
  2383. case ISD::VECTOR_SHUFFLE: {
  2384. if (VT.isScalableVector())
  2385. return SDValue();
  2386. // Check if this is a shuffle node doing a splat.
  2387. // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
  2388. // getTargetVShiftNode currently struggles without the splat source.
  2389. auto *SVN = cast<ShuffleVectorSDNode>(V);
  2390. if (!SVN->isSplat())
  2391. break;
  2392. int Idx = SVN->getSplatIndex();
  2393. int NumElts = V.getValueType().getVectorNumElements();
  2394. SplatIdx = Idx % NumElts;
  2395. return V.getOperand(Idx / NumElts);
  2396. }
  2397. }
  2398. return SDValue();
  2399. }
  2400. SDValue SelectionDAG::getSplatValue(SDValue V, bool LegalTypes) {
  2401. int SplatIdx;
  2402. if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx)) {
  2403. EVT SVT = SrcVector.getValueType().getScalarType();
  2404. EVT LegalSVT = SVT;
  2405. if (LegalTypes && !TLI->isTypeLegal(SVT)) {
  2406. if (!SVT.isInteger())
  2407. return SDValue();
  2408. LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
  2409. if (LegalSVT.bitsLT(SVT))
  2410. return SDValue();
  2411. }
  2412. return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V), LegalSVT, SrcVector,
  2413. getVectorIdxConstant(SplatIdx, SDLoc(V)));
  2414. }
  2415. return SDValue();
  2416. }
  2417. const APInt *
  2418. SelectionDAG::getValidShiftAmountConstant(SDValue V,
  2419. const APInt &DemandedElts) const {
  2420. assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
  2421. V.getOpcode() == ISD::SRA) &&
  2422. "Unknown shift node");
  2423. unsigned BitWidth = V.getScalarValueSizeInBits();
  2424. if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
  2425. // Shifting more than the bitwidth is not valid.
  2426. const APInt &ShAmt = SA->getAPIntValue();
  2427. if (ShAmt.ult(BitWidth))
  2428. return &ShAmt;
  2429. }
  2430. return nullptr;
  2431. }
  2432. const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
  2433. SDValue V, const APInt &DemandedElts) const {
  2434. assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
  2435. V.getOpcode() == ISD::SRA) &&
  2436. "Unknown shift node");
  2437. if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
  2438. return ValidAmt;
  2439. unsigned BitWidth = V.getScalarValueSizeInBits();
  2440. auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
  2441. if (!BV)
  2442. return nullptr;
  2443. const APInt *MinShAmt = nullptr;
  2444. for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
  2445. if (!DemandedElts[i])
  2446. continue;
  2447. auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
  2448. if (!SA)
  2449. return nullptr;
  2450. // Shifting more than the bitwidth is not valid.
  2451. const APInt &ShAmt = SA->getAPIntValue();
  2452. if (ShAmt.uge(BitWidth))
  2453. return nullptr;
  2454. if (MinShAmt && MinShAmt->ule(ShAmt))
  2455. continue;
  2456. MinShAmt = &ShAmt;
  2457. }
  2458. return MinShAmt;
  2459. }
  2460. const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
  2461. SDValue V, const APInt &DemandedElts) const {
  2462. assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
  2463. V.getOpcode() == ISD::SRA) &&
  2464. "Unknown shift node");
  2465. if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
  2466. return ValidAmt;
  2467. unsigned BitWidth = V.getScalarValueSizeInBits();
  2468. auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
  2469. if (!BV)
  2470. return nullptr;
  2471. const APInt *MaxShAmt = nullptr;
  2472. for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
  2473. if (!DemandedElts[i])
  2474. continue;
  2475. auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
  2476. if (!SA)
  2477. return nullptr;
  2478. // Shifting more than the bitwidth is not valid.
  2479. const APInt &ShAmt = SA->getAPIntValue();
  2480. if (ShAmt.uge(BitWidth))
  2481. return nullptr;
  2482. if (MaxShAmt && MaxShAmt->uge(ShAmt))
  2483. continue;
  2484. MaxShAmt = &ShAmt;
  2485. }
  2486. return MaxShAmt;
  2487. }
  2488. /// Determine which bits of Op are known to be either zero or one and return
  2489. /// them in Known. For vectors, the known bits are those that are shared by
  2490. /// every vector element.
  2491. KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
  2492. EVT VT = Op.getValueType();
  2493. // TOOD: Until we have a plan for how to represent demanded elements for
  2494. // scalable vectors, we can just bail out for now.
  2495. if (Op.getValueType().isScalableVector()) {
  2496. unsigned BitWidth = Op.getScalarValueSizeInBits();
  2497. return KnownBits(BitWidth);
  2498. }
  2499. APInt DemandedElts = VT.isVector()
  2500. ? APInt::getAllOnes(VT.getVectorNumElements())
  2501. : APInt(1, 1);
  2502. return computeKnownBits(Op, DemandedElts, Depth);
  2503. }
  2504. /// Determine which bits of Op are known to be either zero or one and return
  2505. /// them in Known. The DemandedElts argument allows us to only collect the known
  2506. /// bits that are shared by the requested vector elements.
  2507. KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
  2508. unsigned Depth) const {
  2509. unsigned BitWidth = Op.getScalarValueSizeInBits();
  2510. KnownBits Known(BitWidth); // Don't know anything.
  2511. // TOOD: Until we have a plan for how to represent demanded elements for
  2512. // scalable vectors, we can just bail out for now.
  2513. if (Op.getValueType().isScalableVector())
  2514. return Known;
  2515. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  2516. // We know all of the bits for a constant!
  2517. return KnownBits::makeConstant(C->getAPIntValue());
  2518. }
  2519. if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
  2520. // We know all of the bits for a constant fp!
  2521. return KnownBits::makeConstant(C->getValueAPF().bitcastToAPInt());
  2522. }
  2523. if (Depth >= MaxRecursionDepth)
  2524. return Known; // Limit search depth.
  2525. KnownBits Known2;
  2526. unsigned NumElts = DemandedElts.getBitWidth();
  2527. assert((!Op.getValueType().isVector() ||
  2528. NumElts == Op.getValueType().getVectorNumElements()) &&
  2529. "Unexpected vector size");
  2530. if (!DemandedElts)
  2531. return Known; // No demanded elts, better to assume we don't know anything.
  2532. unsigned Opcode = Op.getOpcode();
  2533. switch (Opcode) {
  2534. case ISD::BUILD_VECTOR:
  2535. // Collect the known bits that are shared by every demanded vector element.
  2536. Known.Zero.setAllBits(); Known.One.setAllBits();
  2537. for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
  2538. if (!DemandedElts[i])
  2539. continue;
  2540. SDValue SrcOp = Op.getOperand(i);
  2541. Known2 = computeKnownBits(SrcOp, Depth + 1);
  2542. // BUILD_VECTOR can implicitly truncate sources, we must handle this.
  2543. if (SrcOp.getValueSizeInBits() != BitWidth) {
  2544. assert(SrcOp.getValueSizeInBits() > BitWidth &&
  2545. "Expected BUILD_VECTOR implicit truncation");
  2546. Known2 = Known2.trunc(BitWidth);
  2547. }
  2548. // Known bits are the values that are shared by every demanded element.
  2549. Known = KnownBits::commonBits(Known, Known2);
  2550. // If we don't know any bits, early out.
  2551. if (Known.isUnknown())
  2552. break;
  2553. }
  2554. break;
  2555. case ISD::VECTOR_SHUFFLE: {
  2556. // Collect the known bits that are shared by every vector element referenced
  2557. // by the shuffle.
  2558. APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
  2559. Known.Zero.setAllBits(); Known.One.setAllBits();
  2560. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
  2561. assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
  2562. for (unsigned i = 0; i != NumElts; ++i) {
  2563. if (!DemandedElts[i])
  2564. continue;
  2565. int M = SVN->getMaskElt(i);
  2566. if (M < 0) {
  2567. // For UNDEF elements, we don't know anything about the common state of
  2568. // the shuffle result.
  2569. Known.resetAll();
  2570. DemandedLHS.clearAllBits();
  2571. DemandedRHS.clearAllBits();
  2572. break;
  2573. }
  2574. if ((unsigned)M < NumElts)
  2575. DemandedLHS.setBit((unsigned)M % NumElts);
  2576. else
  2577. DemandedRHS.setBit((unsigned)M % NumElts);
  2578. }
  2579. // Known bits are the values that are shared by every demanded element.
  2580. if (!!DemandedLHS) {
  2581. SDValue LHS = Op.getOperand(0);
  2582. Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
  2583. Known = KnownBits::commonBits(Known, Known2);
  2584. }
  2585. // If we don't know any bits, early out.
  2586. if (Known.isUnknown())
  2587. break;
  2588. if (!!DemandedRHS) {
  2589. SDValue RHS = Op.getOperand(1);
  2590. Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
  2591. Known = KnownBits::commonBits(Known, Known2);
  2592. }
  2593. break;
  2594. }
  2595. case ISD::CONCAT_VECTORS: {
  2596. // Split DemandedElts and test each of the demanded subvectors.
  2597. Known.Zero.setAllBits(); Known.One.setAllBits();
  2598. EVT SubVectorVT = Op.getOperand(0).getValueType();
  2599. unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
  2600. unsigned NumSubVectors = Op.getNumOperands();
  2601. for (unsigned i = 0; i != NumSubVectors; ++i) {
  2602. APInt DemandedSub =
  2603. DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
  2604. if (!!DemandedSub) {
  2605. SDValue Sub = Op.getOperand(i);
  2606. Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
  2607. Known = KnownBits::commonBits(Known, Known2);
  2608. }
  2609. // If we don't know any bits, early out.
  2610. if (Known.isUnknown())
  2611. break;
  2612. }
  2613. break;
  2614. }
  2615. case ISD::INSERT_SUBVECTOR: {
  2616. // Demand any elements from the subvector and the remainder from the src its
  2617. // inserted into.
  2618. SDValue Src = Op.getOperand(0);
  2619. SDValue Sub = Op.getOperand(1);
  2620. uint64_t Idx = Op.getConstantOperandVal(2);
  2621. unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
  2622. APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
  2623. APInt DemandedSrcElts = DemandedElts;
  2624. DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
  2625. Known.One.setAllBits();
  2626. Known.Zero.setAllBits();
  2627. if (!!DemandedSubElts) {
  2628. Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
  2629. if (Known.isUnknown())
  2630. break; // early-out.
  2631. }
  2632. if (!!DemandedSrcElts) {
  2633. Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
  2634. Known = KnownBits::commonBits(Known, Known2);
  2635. }
  2636. break;
  2637. }
  2638. case ISD::EXTRACT_SUBVECTOR: {
  2639. // Offset the demanded elts by the subvector index.
  2640. SDValue Src = Op.getOperand(0);
  2641. // Bail until we can represent demanded elements for scalable vectors.
  2642. if (Src.getValueType().isScalableVector())
  2643. break;
  2644. uint64_t Idx = Op.getConstantOperandVal(1);
  2645. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2646. APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  2647. Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
  2648. break;
  2649. }
  2650. case ISD::SCALAR_TO_VECTOR: {
  2651. // We know about scalar_to_vector as much as we know about it source,
  2652. // which becomes the first element of otherwise unknown vector.
  2653. if (DemandedElts != 1)
  2654. break;
  2655. SDValue N0 = Op.getOperand(0);
  2656. Known = computeKnownBits(N0, Depth + 1);
  2657. if (N0.getValueSizeInBits() != BitWidth)
  2658. Known = Known.trunc(BitWidth);
  2659. break;
  2660. }
  2661. case ISD::BITCAST: {
  2662. SDValue N0 = Op.getOperand(0);
  2663. EVT SubVT = N0.getValueType();
  2664. unsigned SubBitWidth = SubVT.getScalarSizeInBits();
  2665. // Ignore bitcasts from unsupported types.
  2666. if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
  2667. break;
  2668. // Fast handling of 'identity' bitcasts.
  2669. if (BitWidth == SubBitWidth) {
  2670. Known = computeKnownBits(N0, DemandedElts, Depth + 1);
  2671. break;
  2672. }
  2673. bool IsLE = getDataLayout().isLittleEndian();
  2674. // Bitcast 'small element' vector to 'large element' scalar/vector.
  2675. if ((BitWidth % SubBitWidth) == 0) {
  2676. assert(N0.getValueType().isVector() && "Expected bitcast from vector");
  2677. // Collect known bits for the (larger) output by collecting the known
  2678. // bits from each set of sub elements and shift these into place.
  2679. // We need to separately call computeKnownBits for each set of
  2680. // sub elements as the knownbits for each is likely to be different.
  2681. unsigned SubScale = BitWidth / SubBitWidth;
  2682. APInt SubDemandedElts(NumElts * SubScale, 0);
  2683. for (unsigned i = 0; i != NumElts; ++i)
  2684. if (DemandedElts[i])
  2685. SubDemandedElts.setBit(i * SubScale);
  2686. for (unsigned i = 0; i != SubScale; ++i) {
  2687. Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
  2688. Depth + 1);
  2689. unsigned Shifts = IsLE ? i : SubScale - 1 - i;
  2690. Known.insertBits(Known2, SubBitWidth * Shifts);
  2691. }
  2692. }
  2693. // Bitcast 'large element' scalar/vector to 'small element' vector.
  2694. if ((SubBitWidth % BitWidth) == 0) {
  2695. assert(Op.getValueType().isVector() && "Expected bitcast to vector");
  2696. // Collect known bits for the (smaller) output by collecting the known
  2697. // bits from the overlapping larger input elements and extracting the
  2698. // sub sections we actually care about.
  2699. unsigned SubScale = SubBitWidth / BitWidth;
  2700. APInt SubDemandedElts =
  2701. APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
  2702. Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
  2703. Known.Zero.setAllBits(); Known.One.setAllBits();
  2704. for (unsigned i = 0; i != NumElts; ++i)
  2705. if (DemandedElts[i]) {
  2706. unsigned Shifts = IsLE ? i : NumElts - 1 - i;
  2707. unsigned Offset = (Shifts % SubScale) * BitWidth;
  2708. Known = KnownBits::commonBits(Known,
  2709. Known2.extractBits(BitWidth, Offset));
  2710. // If we don't know any bits, early out.
  2711. if (Known.isUnknown())
  2712. break;
  2713. }
  2714. }
  2715. break;
  2716. }
  2717. case ISD::AND:
  2718. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2719. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2720. Known &= Known2;
  2721. break;
  2722. case ISD::OR:
  2723. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2724. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2725. Known |= Known2;
  2726. break;
  2727. case ISD::XOR:
  2728. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2729. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2730. Known ^= Known2;
  2731. break;
  2732. case ISD::MUL: {
  2733. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2734. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2735. bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
  2736. // TODO: SelfMultiply can be poison, but not undef.
  2737. SelfMultiply &= isGuaranteedNotToBeUndefOrPoison(
  2738. Op.getOperand(0), DemandedElts, false, Depth + 1);
  2739. Known = KnownBits::mul(Known, Known2, SelfMultiply);
  2740. break;
  2741. }
  2742. case ISD::MULHU: {
  2743. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2744. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2745. Known = KnownBits::mulhu(Known, Known2);
  2746. break;
  2747. }
  2748. case ISD::MULHS: {
  2749. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2750. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2751. Known = KnownBits::mulhs(Known, Known2);
  2752. break;
  2753. }
  2754. case ISD::UMUL_LOHI: {
  2755. assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
  2756. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2757. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2758. bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
  2759. if (Op.getResNo() == 0)
  2760. Known = KnownBits::mul(Known, Known2, SelfMultiply);
  2761. else
  2762. Known = KnownBits::mulhu(Known, Known2);
  2763. break;
  2764. }
  2765. case ISD::SMUL_LOHI: {
  2766. assert((Op.getResNo() == 0 || Op.getResNo() == 1) && "Unknown result");
  2767. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2768. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2769. bool SelfMultiply = Op.getOperand(0) == Op.getOperand(1);
  2770. if (Op.getResNo() == 0)
  2771. Known = KnownBits::mul(Known, Known2, SelfMultiply);
  2772. else
  2773. Known = KnownBits::mulhs(Known, Known2);
  2774. break;
  2775. }
  2776. case ISD::UDIV: {
  2777. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2778. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2779. Known = KnownBits::udiv(Known, Known2);
  2780. break;
  2781. }
  2782. case ISD::SELECT:
  2783. case ISD::VSELECT:
  2784. Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
  2785. // If we don't know any bits, early out.
  2786. if (Known.isUnknown())
  2787. break;
  2788. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
  2789. // Only known if known in both the LHS and RHS.
  2790. Known = KnownBits::commonBits(Known, Known2);
  2791. break;
  2792. case ISD::SELECT_CC:
  2793. Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
  2794. // If we don't know any bits, early out.
  2795. if (Known.isUnknown())
  2796. break;
  2797. Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
  2798. // Only known if known in both the LHS and RHS.
  2799. Known = KnownBits::commonBits(Known, Known2);
  2800. break;
  2801. case ISD::SMULO:
  2802. case ISD::UMULO:
  2803. if (Op.getResNo() != 1)
  2804. break;
  2805. // The boolean result conforms to getBooleanContents.
  2806. // If we know the result of a setcc has the top bits zero, use this info.
  2807. // We know that we have an integer-based boolean since these operations
  2808. // are only available for integer.
  2809. if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
  2810. TargetLowering::ZeroOrOneBooleanContent &&
  2811. BitWidth > 1)
  2812. Known.Zero.setBitsFrom(1);
  2813. break;
  2814. case ISD::SETCC:
  2815. case ISD::STRICT_FSETCC:
  2816. case ISD::STRICT_FSETCCS: {
  2817. unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
  2818. // If we know the result of a setcc has the top bits zero, use this info.
  2819. if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
  2820. TargetLowering::ZeroOrOneBooleanContent &&
  2821. BitWidth > 1)
  2822. Known.Zero.setBitsFrom(1);
  2823. break;
  2824. }
  2825. case ISD::SHL:
  2826. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2827. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2828. Known = KnownBits::shl(Known, Known2);
  2829. // Minimum shift low bits are known zero.
  2830. if (const APInt *ShMinAmt =
  2831. getValidMinimumShiftAmountConstant(Op, DemandedElts))
  2832. Known.Zero.setLowBits(ShMinAmt->getZExtValue());
  2833. break;
  2834. case ISD::SRL:
  2835. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2836. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2837. Known = KnownBits::lshr(Known, Known2);
  2838. // Minimum shift high bits are known zero.
  2839. if (const APInt *ShMinAmt =
  2840. getValidMinimumShiftAmountConstant(Op, DemandedElts))
  2841. Known.Zero.setHighBits(ShMinAmt->getZExtValue());
  2842. break;
  2843. case ISD::SRA:
  2844. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2845. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2846. Known = KnownBits::ashr(Known, Known2);
  2847. // TODO: Add minimum shift high known sign bits.
  2848. break;
  2849. case ISD::FSHL:
  2850. case ISD::FSHR:
  2851. if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
  2852. unsigned Amt = C->getAPIntValue().urem(BitWidth);
  2853. // For fshl, 0-shift returns the 1st arg.
  2854. // For fshr, 0-shift returns the 2nd arg.
  2855. if (Amt == 0) {
  2856. Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
  2857. DemandedElts, Depth + 1);
  2858. break;
  2859. }
  2860. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  2861. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  2862. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2863. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2864. if (Opcode == ISD::FSHL) {
  2865. Known.One <<= Amt;
  2866. Known.Zero <<= Amt;
  2867. Known2.One.lshrInPlace(BitWidth - Amt);
  2868. Known2.Zero.lshrInPlace(BitWidth - Amt);
  2869. } else {
  2870. Known.One <<= BitWidth - Amt;
  2871. Known.Zero <<= BitWidth - Amt;
  2872. Known2.One.lshrInPlace(Amt);
  2873. Known2.Zero.lshrInPlace(Amt);
  2874. }
  2875. Known.One |= Known2.One;
  2876. Known.Zero |= Known2.Zero;
  2877. }
  2878. break;
  2879. case ISD::SIGN_EXTEND_INREG: {
  2880. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2881. EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  2882. Known = Known.sextInReg(EVT.getScalarSizeInBits());
  2883. break;
  2884. }
  2885. case ISD::CTTZ:
  2886. case ISD::CTTZ_ZERO_UNDEF: {
  2887. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2888. // If we have a known 1, its position is our upper bound.
  2889. unsigned PossibleTZ = Known2.countMaxTrailingZeros();
  2890. unsigned LowBits = Log2_32(PossibleTZ) + 1;
  2891. Known.Zero.setBitsFrom(LowBits);
  2892. break;
  2893. }
  2894. case ISD::CTLZ:
  2895. case ISD::CTLZ_ZERO_UNDEF: {
  2896. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2897. // If we have a known 1, its position is our upper bound.
  2898. unsigned PossibleLZ = Known2.countMaxLeadingZeros();
  2899. unsigned LowBits = Log2_32(PossibleLZ) + 1;
  2900. Known.Zero.setBitsFrom(LowBits);
  2901. break;
  2902. }
  2903. case ISD::CTPOP: {
  2904. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2905. // If we know some of the bits are zero, they can't be one.
  2906. unsigned PossibleOnes = Known2.countMaxPopulation();
  2907. Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
  2908. break;
  2909. }
  2910. case ISD::PARITY: {
  2911. // Parity returns 0 everywhere but the LSB.
  2912. Known.Zero.setBitsFrom(1);
  2913. break;
  2914. }
  2915. case ISD::LOAD: {
  2916. LoadSDNode *LD = cast<LoadSDNode>(Op);
  2917. const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
  2918. if (ISD::isNON_EXTLoad(LD) && Cst) {
  2919. // Determine any common known bits from the loaded constant pool value.
  2920. Type *CstTy = Cst->getType();
  2921. if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
  2922. // If its a vector splat, then we can (quickly) reuse the scalar path.
  2923. // NOTE: We assume all elements match and none are UNDEF.
  2924. if (CstTy->isVectorTy()) {
  2925. if (const Constant *Splat = Cst->getSplatValue()) {
  2926. Cst = Splat;
  2927. CstTy = Cst->getType();
  2928. }
  2929. }
  2930. // TODO - do we need to handle different bitwidths?
  2931. if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
  2932. // Iterate across all vector elements finding common known bits.
  2933. Known.One.setAllBits();
  2934. Known.Zero.setAllBits();
  2935. for (unsigned i = 0; i != NumElts; ++i) {
  2936. if (!DemandedElts[i])
  2937. continue;
  2938. if (Constant *Elt = Cst->getAggregateElement(i)) {
  2939. if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
  2940. const APInt &Value = CInt->getValue();
  2941. Known.One &= Value;
  2942. Known.Zero &= ~Value;
  2943. continue;
  2944. }
  2945. if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
  2946. APInt Value = CFP->getValueAPF().bitcastToAPInt();
  2947. Known.One &= Value;
  2948. Known.Zero &= ~Value;
  2949. continue;
  2950. }
  2951. }
  2952. Known.One.clearAllBits();
  2953. Known.Zero.clearAllBits();
  2954. break;
  2955. }
  2956. } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
  2957. if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
  2958. Known = KnownBits::makeConstant(CInt->getValue());
  2959. } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
  2960. Known =
  2961. KnownBits::makeConstant(CFP->getValueAPF().bitcastToAPInt());
  2962. }
  2963. }
  2964. }
  2965. } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
  2966. // If this is a ZEXTLoad and we are looking at the loaded value.
  2967. EVT VT = LD->getMemoryVT();
  2968. unsigned MemBits = VT.getScalarSizeInBits();
  2969. Known.Zero.setBitsFrom(MemBits);
  2970. } else if (const MDNode *Ranges = LD->getRanges()) {
  2971. if (LD->getExtensionType() == ISD::NON_EXTLOAD)
  2972. computeKnownBitsFromRangeMetadata(*Ranges, Known);
  2973. }
  2974. break;
  2975. }
  2976. case ISD::ZERO_EXTEND_VECTOR_INREG: {
  2977. EVT InVT = Op.getOperand(0).getValueType();
  2978. APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
  2979. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  2980. Known = Known.zext(BitWidth);
  2981. break;
  2982. }
  2983. case ISD::ZERO_EXTEND: {
  2984. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2985. Known = Known.zext(BitWidth);
  2986. break;
  2987. }
  2988. case ISD::SIGN_EXTEND_VECTOR_INREG: {
  2989. EVT InVT = Op.getOperand(0).getValueType();
  2990. APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
  2991. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  2992. // If the sign bit is known to be zero or one, then sext will extend
  2993. // it to the top bits, else it will just zext.
  2994. Known = Known.sext(BitWidth);
  2995. break;
  2996. }
  2997. case ISD::SIGN_EXTEND: {
  2998. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2999. // If the sign bit is known to be zero or one, then sext will extend
  3000. // it to the top bits, else it will just zext.
  3001. Known = Known.sext(BitWidth);
  3002. break;
  3003. }
  3004. case ISD::ANY_EXTEND_VECTOR_INREG: {
  3005. EVT InVT = Op.getOperand(0).getValueType();
  3006. APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
  3007. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  3008. Known = Known.anyext(BitWidth);
  3009. break;
  3010. }
  3011. case ISD::ANY_EXTEND: {
  3012. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3013. Known = Known.anyext(BitWidth);
  3014. break;
  3015. }
  3016. case ISD::TRUNCATE: {
  3017. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3018. Known = Known.trunc(BitWidth);
  3019. break;
  3020. }
  3021. case ISD::AssertZext: {
  3022. EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  3023. APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
  3024. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  3025. Known.Zero |= (~InMask);
  3026. Known.One &= (~Known.Zero);
  3027. break;
  3028. }
  3029. case ISD::AssertAlign: {
  3030. unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
  3031. assert(LogOfAlign != 0);
  3032. // TODO: Should use maximum with source
  3033. // If a node is guaranteed to be aligned, set low zero bits accordingly as
  3034. // well as clearing one bits.
  3035. Known.Zero.setLowBits(LogOfAlign);
  3036. Known.One.clearLowBits(LogOfAlign);
  3037. break;
  3038. }
  3039. case ISD::FGETSIGN:
  3040. // All bits are zero except the low bit.
  3041. Known.Zero.setBitsFrom(1);
  3042. break;
  3043. case ISD::USUBO:
  3044. case ISD::SSUBO:
  3045. if (Op.getResNo() == 1) {
  3046. // If we know the result of a setcc has the top bits zero, use this info.
  3047. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  3048. TargetLowering::ZeroOrOneBooleanContent &&
  3049. BitWidth > 1)
  3050. Known.Zero.setBitsFrom(1);
  3051. break;
  3052. }
  3053. LLVM_FALLTHROUGH;
  3054. case ISD::SUB:
  3055. case ISD::SUBC: {
  3056. assert(Op.getResNo() == 0 &&
  3057. "We only compute knownbits for the difference here.");
  3058. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3059. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3060. Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
  3061. Known, Known2);
  3062. break;
  3063. }
  3064. case ISD::UADDO:
  3065. case ISD::SADDO:
  3066. case ISD::ADDCARRY:
  3067. if (Op.getResNo() == 1) {
  3068. // If we know the result of a setcc has the top bits zero, use this info.
  3069. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  3070. TargetLowering::ZeroOrOneBooleanContent &&
  3071. BitWidth > 1)
  3072. Known.Zero.setBitsFrom(1);
  3073. break;
  3074. }
  3075. LLVM_FALLTHROUGH;
  3076. case ISD::ADD:
  3077. case ISD::ADDC:
  3078. case ISD::ADDE: {
  3079. assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
  3080. // With ADDE and ADDCARRY, a carry bit may be added in.
  3081. KnownBits Carry(1);
  3082. if (Opcode == ISD::ADDE)
  3083. // Can't track carry from glue, set carry to unknown.
  3084. Carry.resetAll();
  3085. else if (Opcode == ISD::ADDCARRY)
  3086. // TODO: Compute known bits for the carry operand. Not sure if it is worth
  3087. // the trouble (how often will we find a known carry bit). And I haven't
  3088. // tested this very much yet, but something like this might work:
  3089. // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
  3090. // Carry = Carry.zextOrTrunc(1, false);
  3091. Carry.resetAll();
  3092. else
  3093. Carry.setAllZero();
  3094. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3095. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3096. Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
  3097. break;
  3098. }
  3099. case ISD::SREM: {
  3100. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3101. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3102. Known = KnownBits::srem(Known, Known2);
  3103. break;
  3104. }
  3105. case ISD::UREM: {
  3106. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3107. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3108. Known = KnownBits::urem(Known, Known2);
  3109. break;
  3110. }
  3111. case ISD::EXTRACT_ELEMENT: {
  3112. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  3113. const unsigned Index = Op.getConstantOperandVal(1);
  3114. const unsigned EltBitWidth = Op.getValueSizeInBits();
  3115. // Remove low part of known bits mask
  3116. Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
  3117. Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
  3118. // Remove high part of known bit mask
  3119. Known = Known.trunc(EltBitWidth);
  3120. break;
  3121. }
  3122. case ISD::EXTRACT_VECTOR_ELT: {
  3123. SDValue InVec = Op.getOperand(0);
  3124. SDValue EltNo = Op.getOperand(1);
  3125. EVT VecVT = InVec.getValueType();
  3126. // computeKnownBits not yet implemented for scalable vectors.
  3127. if (VecVT.isScalableVector())
  3128. break;
  3129. const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
  3130. const unsigned NumSrcElts = VecVT.getVectorNumElements();
  3131. // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
  3132. // anything about the extended bits.
  3133. if (BitWidth > EltBitWidth)
  3134. Known = Known.trunc(EltBitWidth);
  3135. // If we know the element index, just demand that vector element, else for
  3136. // an unknown element index, ignore DemandedElts and demand them all.
  3137. APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
  3138. auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3139. if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
  3140. DemandedSrcElts =
  3141. APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
  3142. Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
  3143. if (BitWidth > EltBitWidth)
  3144. Known = Known.anyext(BitWidth);
  3145. break;
  3146. }
  3147. case ISD::INSERT_VECTOR_ELT: {
  3148. // If we know the element index, split the demand between the
  3149. // source vector and the inserted element, otherwise assume we need
  3150. // the original demanded vector elements and the value.
  3151. SDValue InVec = Op.getOperand(0);
  3152. SDValue InVal = Op.getOperand(1);
  3153. SDValue EltNo = Op.getOperand(2);
  3154. bool DemandedVal = true;
  3155. APInt DemandedVecElts = DemandedElts;
  3156. auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3157. if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
  3158. unsigned EltIdx = CEltNo->getZExtValue();
  3159. DemandedVal = !!DemandedElts[EltIdx];
  3160. DemandedVecElts.clearBit(EltIdx);
  3161. }
  3162. Known.One.setAllBits();
  3163. Known.Zero.setAllBits();
  3164. if (DemandedVal) {
  3165. Known2 = computeKnownBits(InVal, Depth + 1);
  3166. Known = KnownBits::commonBits(Known, Known2.zextOrTrunc(BitWidth));
  3167. }
  3168. if (!!DemandedVecElts) {
  3169. Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
  3170. Known = KnownBits::commonBits(Known, Known2);
  3171. }
  3172. break;
  3173. }
  3174. case ISD::BITREVERSE: {
  3175. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3176. Known = Known2.reverseBits();
  3177. break;
  3178. }
  3179. case ISD::BSWAP: {
  3180. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3181. Known = Known2.byteSwap();
  3182. break;
  3183. }
  3184. case ISD::ABS: {
  3185. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3186. Known = Known2.abs();
  3187. break;
  3188. }
  3189. case ISD::USUBSAT: {
  3190. // The result of usubsat will never be larger than the LHS.
  3191. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3192. Known.Zero.setHighBits(Known2.countMinLeadingZeros());
  3193. break;
  3194. }
  3195. case ISD::UMIN: {
  3196. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3197. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3198. Known = KnownBits::umin(Known, Known2);
  3199. break;
  3200. }
  3201. case ISD::UMAX: {
  3202. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3203. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3204. Known = KnownBits::umax(Known, Known2);
  3205. break;
  3206. }
  3207. case ISD::SMIN:
  3208. case ISD::SMAX: {
  3209. // If we have a clamp pattern, we know that the number of sign bits will be
  3210. // the minimum of the clamp min/max range.
  3211. bool IsMax = (Opcode == ISD::SMAX);
  3212. ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
  3213. if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
  3214. if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
  3215. CstHigh =
  3216. isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
  3217. if (CstLow && CstHigh) {
  3218. if (!IsMax)
  3219. std::swap(CstLow, CstHigh);
  3220. const APInt &ValueLow = CstLow->getAPIntValue();
  3221. const APInt &ValueHigh = CstHigh->getAPIntValue();
  3222. if (ValueLow.sle(ValueHigh)) {
  3223. unsigned LowSignBits = ValueLow.getNumSignBits();
  3224. unsigned HighSignBits = ValueHigh.getNumSignBits();
  3225. unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
  3226. if (ValueLow.isNegative() && ValueHigh.isNegative()) {
  3227. Known.One.setHighBits(MinSignBits);
  3228. break;
  3229. }
  3230. if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
  3231. Known.Zero.setHighBits(MinSignBits);
  3232. break;
  3233. }
  3234. }
  3235. }
  3236. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3237. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3238. if (IsMax)
  3239. Known = KnownBits::smax(Known, Known2);
  3240. else
  3241. Known = KnownBits::smin(Known, Known2);
  3242. break;
  3243. }
  3244. case ISD::FP_TO_UINT_SAT: {
  3245. // FP_TO_UINT_SAT produces an unsigned value that fits in the saturating VT.
  3246. EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  3247. Known.Zero |= APInt::getBitsSetFrom(BitWidth, VT.getScalarSizeInBits());
  3248. break;
  3249. }
  3250. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  3251. if (Op.getResNo() == 1) {
  3252. // The boolean result conforms to getBooleanContents.
  3253. // If we know the result of a setcc has the top bits zero, use this info.
  3254. // We know that we have an integer-based boolean since these operations
  3255. // are only available for integer.
  3256. if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
  3257. TargetLowering::ZeroOrOneBooleanContent &&
  3258. BitWidth > 1)
  3259. Known.Zero.setBitsFrom(1);
  3260. break;
  3261. }
  3262. LLVM_FALLTHROUGH;
  3263. case ISD::ATOMIC_CMP_SWAP:
  3264. case ISD::ATOMIC_SWAP:
  3265. case ISD::ATOMIC_LOAD_ADD:
  3266. case ISD::ATOMIC_LOAD_SUB:
  3267. case ISD::ATOMIC_LOAD_AND:
  3268. case ISD::ATOMIC_LOAD_CLR:
  3269. case ISD::ATOMIC_LOAD_OR:
  3270. case ISD::ATOMIC_LOAD_XOR:
  3271. case ISD::ATOMIC_LOAD_NAND:
  3272. case ISD::ATOMIC_LOAD_MIN:
  3273. case ISD::ATOMIC_LOAD_MAX:
  3274. case ISD::ATOMIC_LOAD_UMIN:
  3275. case ISD::ATOMIC_LOAD_UMAX:
  3276. case ISD::ATOMIC_LOAD: {
  3277. unsigned MemBits =
  3278. cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
  3279. // If we are looking at the loaded value.
  3280. if (Op.getResNo() == 0) {
  3281. if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
  3282. Known.Zero.setBitsFrom(MemBits);
  3283. }
  3284. break;
  3285. }
  3286. case ISD::FrameIndex:
  3287. case ISD::TargetFrameIndex:
  3288. TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
  3289. Known, getMachineFunction());
  3290. break;
  3291. default:
  3292. if (Opcode < ISD::BUILTIN_OP_END)
  3293. break;
  3294. LLVM_FALLTHROUGH;
  3295. case ISD::INTRINSIC_WO_CHAIN:
  3296. case ISD::INTRINSIC_W_CHAIN:
  3297. case ISD::INTRINSIC_VOID:
  3298. // Allow the target to implement this method for its nodes.
  3299. TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
  3300. break;
  3301. }
  3302. assert(!Known.hasConflict() && "Bits known to be one AND zero?");
  3303. return Known;
  3304. }
  3305. SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
  3306. SDValue N1) const {
  3307. // X + 0 never overflow
  3308. if (isNullConstant(N1))
  3309. return OFK_Never;
  3310. KnownBits N1Known = computeKnownBits(N1);
  3311. if (N1Known.Zero.getBoolValue()) {
  3312. KnownBits N0Known = computeKnownBits(N0);
  3313. bool overflow;
  3314. (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
  3315. if (!overflow)
  3316. return OFK_Never;
  3317. }
  3318. // mulhi + 1 never overflow
  3319. if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
  3320. (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
  3321. return OFK_Never;
  3322. if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
  3323. KnownBits N0Known = computeKnownBits(N0);
  3324. if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
  3325. return OFK_Never;
  3326. }
  3327. return OFK_Sometime;
  3328. }
  3329. bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
  3330. EVT OpVT = Val.getValueType();
  3331. unsigned BitWidth = OpVT.getScalarSizeInBits();
  3332. // Is the constant a known power of 2?
  3333. if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
  3334. return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
  3335. // A left-shift of a constant one will have exactly one bit set because
  3336. // shifting the bit off the end is undefined.
  3337. if (Val.getOpcode() == ISD::SHL) {
  3338. auto *C = isConstOrConstSplat(Val.getOperand(0));
  3339. if (C && C->getAPIntValue() == 1)
  3340. return true;
  3341. }
  3342. // Similarly, a logical right-shift of a constant sign-bit will have exactly
  3343. // one bit set.
  3344. if (Val.getOpcode() == ISD::SRL) {
  3345. auto *C = isConstOrConstSplat(Val.getOperand(0));
  3346. if (C && C->getAPIntValue().isSignMask())
  3347. return true;
  3348. }
  3349. // Are all operands of a build vector constant powers of two?
  3350. if (Val.getOpcode() == ISD::BUILD_VECTOR)
  3351. if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
  3352. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
  3353. return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
  3354. return false;
  3355. }))
  3356. return true;
  3357. // Is the operand of a splat vector a constant power of two?
  3358. if (Val.getOpcode() == ISD::SPLAT_VECTOR)
  3359. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val->getOperand(0)))
  3360. if (C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2())
  3361. return true;
  3362. // More could be done here, though the above checks are enough
  3363. // to handle some common cases.
  3364. // Fall back to computeKnownBits to catch other known cases.
  3365. KnownBits Known = computeKnownBits(Val);
  3366. return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
  3367. }
  3368. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
  3369. EVT VT = Op.getValueType();
  3370. // TODO: Assume we don't know anything for now.
  3371. if (VT.isScalableVector())
  3372. return 1;
  3373. APInt DemandedElts = VT.isVector()
  3374. ? APInt::getAllOnes(VT.getVectorNumElements())
  3375. : APInt(1, 1);
  3376. return ComputeNumSignBits(Op, DemandedElts, Depth);
  3377. }
  3378. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
  3379. unsigned Depth) const {
  3380. EVT VT = Op.getValueType();
  3381. assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
  3382. unsigned VTBits = VT.getScalarSizeInBits();
  3383. unsigned NumElts = DemandedElts.getBitWidth();
  3384. unsigned Tmp, Tmp2;
  3385. unsigned FirstAnswer = 1;
  3386. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  3387. const APInt &Val = C->getAPIntValue();
  3388. return Val.getNumSignBits();
  3389. }
  3390. if (Depth >= MaxRecursionDepth)
  3391. return 1; // Limit search depth.
  3392. if (!DemandedElts || VT.isScalableVector())
  3393. return 1; // No demanded elts, better to assume we don't know anything.
  3394. unsigned Opcode = Op.getOpcode();
  3395. switch (Opcode) {
  3396. default: break;
  3397. case ISD::AssertSext:
  3398. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  3399. return VTBits-Tmp+1;
  3400. case ISD::AssertZext:
  3401. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  3402. return VTBits-Tmp;
  3403. case ISD::BUILD_VECTOR:
  3404. Tmp = VTBits;
  3405. for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
  3406. if (!DemandedElts[i])
  3407. continue;
  3408. SDValue SrcOp = Op.getOperand(i);
  3409. Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
  3410. // BUILD_VECTOR can implicitly truncate sources, we must handle this.
  3411. if (SrcOp.getValueSizeInBits() != VTBits) {
  3412. assert(SrcOp.getValueSizeInBits() > VTBits &&
  3413. "Expected BUILD_VECTOR implicit truncation");
  3414. unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
  3415. Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
  3416. }
  3417. Tmp = std::min(Tmp, Tmp2);
  3418. }
  3419. return Tmp;
  3420. case ISD::VECTOR_SHUFFLE: {
  3421. // Collect the minimum number of sign bits that are shared by every vector
  3422. // element referenced by the shuffle.
  3423. APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
  3424. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
  3425. assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
  3426. for (unsigned i = 0; i != NumElts; ++i) {
  3427. int M = SVN->getMaskElt(i);
  3428. if (!DemandedElts[i])
  3429. continue;
  3430. // For UNDEF elements, we don't know anything about the common state of
  3431. // the shuffle result.
  3432. if (M < 0)
  3433. return 1;
  3434. if ((unsigned)M < NumElts)
  3435. DemandedLHS.setBit((unsigned)M % NumElts);
  3436. else
  3437. DemandedRHS.setBit((unsigned)M % NumElts);
  3438. }
  3439. Tmp = std::numeric_limits<unsigned>::max();
  3440. if (!!DemandedLHS)
  3441. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
  3442. if (!!DemandedRHS) {
  3443. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
  3444. Tmp = std::min(Tmp, Tmp2);
  3445. }
  3446. // If we don't know anything, early out and try computeKnownBits fall-back.
  3447. if (Tmp == 1)
  3448. break;
  3449. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3450. return Tmp;
  3451. }
  3452. case ISD::BITCAST: {
  3453. SDValue N0 = Op.getOperand(0);
  3454. EVT SrcVT = N0.getValueType();
  3455. unsigned SrcBits = SrcVT.getScalarSizeInBits();
  3456. // Ignore bitcasts from unsupported types..
  3457. if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
  3458. break;
  3459. // Fast handling of 'identity' bitcasts.
  3460. if (VTBits == SrcBits)
  3461. return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
  3462. bool IsLE = getDataLayout().isLittleEndian();
  3463. // Bitcast 'large element' scalar/vector to 'small element' vector.
  3464. if ((SrcBits % VTBits) == 0) {
  3465. assert(VT.isVector() && "Expected bitcast to vector");
  3466. unsigned Scale = SrcBits / VTBits;
  3467. APInt SrcDemandedElts =
  3468. APIntOps::ScaleBitMask(DemandedElts, NumElts / Scale);
  3469. // Fast case - sign splat can be simply split across the small elements.
  3470. Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
  3471. if (Tmp == SrcBits)
  3472. return VTBits;
  3473. // Slow case - determine how far the sign extends into each sub-element.
  3474. Tmp2 = VTBits;
  3475. for (unsigned i = 0; i != NumElts; ++i)
  3476. if (DemandedElts[i]) {
  3477. unsigned SubOffset = i % Scale;
  3478. SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
  3479. SubOffset = SubOffset * VTBits;
  3480. if (Tmp <= SubOffset)
  3481. return 1;
  3482. Tmp2 = std::min(Tmp2, Tmp - SubOffset);
  3483. }
  3484. return Tmp2;
  3485. }
  3486. break;
  3487. }
  3488. case ISD::FP_TO_SINT_SAT:
  3489. // FP_TO_SINT_SAT produces a signed value that fits in the saturating VT.
  3490. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
  3491. return VTBits - Tmp + 1;
  3492. case ISD::SIGN_EXTEND:
  3493. Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
  3494. return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
  3495. case ISD::SIGN_EXTEND_INREG:
  3496. // Max of the input and what this extends.
  3497. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
  3498. Tmp = VTBits-Tmp+1;
  3499. Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3500. return std::max(Tmp, Tmp2);
  3501. case ISD::SIGN_EXTEND_VECTOR_INREG: {
  3502. SDValue Src = Op.getOperand(0);
  3503. EVT SrcVT = Src.getValueType();
  3504. APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
  3505. Tmp = VTBits - SrcVT.getScalarSizeInBits();
  3506. return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
  3507. }
  3508. case ISD::SRA:
  3509. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3510. // SRA X, C -> adds C sign bits.
  3511. if (const APInt *ShAmt =
  3512. getValidMinimumShiftAmountConstant(Op, DemandedElts))
  3513. Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
  3514. return Tmp;
  3515. case ISD::SHL:
  3516. if (const APInt *ShAmt =
  3517. getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
  3518. // shl destroys sign bits, ensure it doesn't shift out all sign bits.
  3519. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3520. if (ShAmt->ult(Tmp))
  3521. return Tmp - ShAmt->getZExtValue();
  3522. }
  3523. break;
  3524. case ISD::AND:
  3525. case ISD::OR:
  3526. case ISD::XOR: // NOT is handled here.
  3527. // Logical binary ops preserve the number of sign bits at the worst.
  3528. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3529. if (Tmp != 1) {
  3530. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
  3531. FirstAnswer = std::min(Tmp, Tmp2);
  3532. // We computed what we know about the sign bits as our first
  3533. // answer. Now proceed to the generic code that uses
  3534. // computeKnownBits, and pick whichever answer is better.
  3535. }
  3536. break;
  3537. case ISD::SELECT:
  3538. case ISD::VSELECT:
  3539. Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
  3540. if (Tmp == 1) return 1; // Early out.
  3541. Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
  3542. return std::min(Tmp, Tmp2);
  3543. case ISD::SELECT_CC:
  3544. Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
  3545. if (Tmp == 1) return 1; // Early out.
  3546. Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
  3547. return std::min(Tmp, Tmp2);
  3548. case ISD::SMIN:
  3549. case ISD::SMAX: {
  3550. // If we have a clamp pattern, we know that the number of sign bits will be
  3551. // the minimum of the clamp min/max range.
  3552. bool IsMax = (Opcode == ISD::SMAX);
  3553. ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
  3554. if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
  3555. if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
  3556. CstHigh =
  3557. isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
  3558. if (CstLow && CstHigh) {
  3559. if (!IsMax)
  3560. std::swap(CstLow, CstHigh);
  3561. if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
  3562. Tmp = CstLow->getAPIntValue().getNumSignBits();
  3563. Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
  3564. return std::min(Tmp, Tmp2);
  3565. }
  3566. }
  3567. // Fallback - just get the minimum number of sign bits of the operands.
  3568. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3569. if (Tmp == 1)
  3570. return 1; // Early out.
  3571. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3572. return std::min(Tmp, Tmp2);
  3573. }
  3574. case ISD::UMIN:
  3575. case ISD::UMAX:
  3576. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3577. if (Tmp == 1)
  3578. return 1; // Early out.
  3579. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3580. return std::min(Tmp, Tmp2);
  3581. case ISD::SADDO:
  3582. case ISD::UADDO:
  3583. case ISD::SSUBO:
  3584. case ISD::USUBO:
  3585. case ISD::SMULO:
  3586. case ISD::UMULO:
  3587. if (Op.getResNo() != 1)
  3588. break;
  3589. // The boolean result conforms to getBooleanContents. Fall through.
  3590. // If setcc returns 0/-1, all bits are sign bits.
  3591. // We know that we have an integer-based boolean since these operations
  3592. // are only available for integer.
  3593. if (TLI->getBooleanContents(VT.isVector(), false) ==
  3594. TargetLowering::ZeroOrNegativeOneBooleanContent)
  3595. return VTBits;
  3596. break;
  3597. case ISD::SETCC:
  3598. case ISD::STRICT_FSETCC:
  3599. case ISD::STRICT_FSETCCS: {
  3600. unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
  3601. // If setcc returns 0/-1, all bits are sign bits.
  3602. if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
  3603. TargetLowering::ZeroOrNegativeOneBooleanContent)
  3604. return VTBits;
  3605. break;
  3606. }
  3607. case ISD::ROTL:
  3608. case ISD::ROTR:
  3609. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3610. // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
  3611. if (Tmp == VTBits)
  3612. return VTBits;
  3613. if (ConstantSDNode *C =
  3614. isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
  3615. unsigned RotAmt = C->getAPIntValue().urem(VTBits);
  3616. // Handle rotate right by N like a rotate left by 32-N.
  3617. if (Opcode == ISD::ROTR)
  3618. RotAmt = (VTBits - RotAmt) % VTBits;
  3619. // If we aren't rotating out all of the known-in sign bits, return the
  3620. // number that are left. This handles rotl(sext(x), 1) for example.
  3621. if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
  3622. }
  3623. break;
  3624. case ISD::ADD:
  3625. case ISD::ADDC:
  3626. // Add can have at most one carry bit. Thus we know that the output
  3627. // is, at worst, one more bit than the inputs.
  3628. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3629. if (Tmp == 1) return 1; // Early out.
  3630. // Special case decrementing a value (ADD X, -1):
  3631. if (ConstantSDNode *CRHS =
  3632. isConstOrConstSplat(Op.getOperand(1), DemandedElts))
  3633. if (CRHS->isAllOnes()) {
  3634. KnownBits Known =
  3635. computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3636. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  3637. // sign bits set.
  3638. if ((Known.Zero | 1).isAllOnes())
  3639. return VTBits;
  3640. // If we are subtracting one from a positive number, there is no carry
  3641. // out of the result.
  3642. if (Known.isNonNegative())
  3643. return Tmp;
  3644. }
  3645. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3646. if (Tmp2 == 1) return 1; // Early out.
  3647. return std::min(Tmp, Tmp2) - 1;
  3648. case ISD::SUB:
  3649. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3650. if (Tmp2 == 1) return 1; // Early out.
  3651. // Handle NEG.
  3652. if (ConstantSDNode *CLHS =
  3653. isConstOrConstSplat(Op.getOperand(0), DemandedElts))
  3654. if (CLHS->isZero()) {
  3655. KnownBits Known =
  3656. computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  3657. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  3658. // sign bits set.
  3659. if ((Known.Zero | 1).isAllOnes())
  3660. return VTBits;
  3661. // If the input is known to be positive (the sign bit is known clear),
  3662. // the output of the NEG has the same number of sign bits as the input.
  3663. if (Known.isNonNegative())
  3664. return Tmp2;
  3665. // Otherwise, we treat this like a SUB.
  3666. }
  3667. // Sub can have at most one carry bit. Thus we know that the output
  3668. // is, at worst, one more bit than the inputs.
  3669. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3670. if (Tmp == 1) return 1; // Early out.
  3671. return std::min(Tmp, Tmp2) - 1;
  3672. case ISD::MUL: {
  3673. // The output of the Mul can be at most twice the valid bits in the inputs.
  3674. unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3675. if (SignBitsOp0 == 1)
  3676. break;
  3677. unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
  3678. if (SignBitsOp1 == 1)
  3679. break;
  3680. unsigned OutValidBits =
  3681. (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
  3682. return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
  3683. }
  3684. case ISD::SREM:
  3685. // The sign bit is the LHS's sign bit, except when the result of the
  3686. // remainder is zero. The magnitude of the result should be less than or
  3687. // equal to the magnitude of the LHS. Therefore, the result should have
  3688. // at least as many sign bits as the left hand side.
  3689. return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  3690. case ISD::TRUNCATE: {
  3691. // Check if the sign bits of source go down as far as the truncated value.
  3692. unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
  3693. unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3694. if (NumSrcSignBits > (NumSrcBits - VTBits))
  3695. return NumSrcSignBits - (NumSrcBits - VTBits);
  3696. break;
  3697. }
  3698. case ISD::EXTRACT_ELEMENT: {
  3699. const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3700. const int BitWidth = Op.getValueSizeInBits();
  3701. const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
  3702. // Get reverse index (starting from 1), Op1 value indexes elements from
  3703. // little end. Sign starts at big end.
  3704. const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
  3705. // If the sign portion ends in our element the subtraction gives correct
  3706. // result. Otherwise it gives either negative or > bitwidth result
  3707. return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
  3708. }
  3709. case ISD::INSERT_VECTOR_ELT: {
  3710. // If we know the element index, split the demand between the
  3711. // source vector and the inserted element, otherwise assume we need
  3712. // the original demanded vector elements and the value.
  3713. SDValue InVec = Op.getOperand(0);
  3714. SDValue InVal = Op.getOperand(1);
  3715. SDValue EltNo = Op.getOperand(2);
  3716. bool DemandedVal = true;
  3717. APInt DemandedVecElts = DemandedElts;
  3718. auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3719. if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
  3720. unsigned EltIdx = CEltNo->getZExtValue();
  3721. DemandedVal = !!DemandedElts[EltIdx];
  3722. DemandedVecElts.clearBit(EltIdx);
  3723. }
  3724. Tmp = std::numeric_limits<unsigned>::max();
  3725. if (DemandedVal) {
  3726. // TODO - handle implicit truncation of inserted elements.
  3727. if (InVal.getScalarValueSizeInBits() != VTBits)
  3728. break;
  3729. Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
  3730. Tmp = std::min(Tmp, Tmp2);
  3731. }
  3732. if (!!DemandedVecElts) {
  3733. Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
  3734. Tmp = std::min(Tmp, Tmp2);
  3735. }
  3736. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3737. return Tmp;
  3738. }
  3739. case ISD::EXTRACT_VECTOR_ELT: {
  3740. SDValue InVec = Op.getOperand(0);
  3741. SDValue EltNo = Op.getOperand(1);
  3742. EVT VecVT = InVec.getValueType();
  3743. // ComputeNumSignBits not yet implemented for scalable vectors.
  3744. if (VecVT.isScalableVector())
  3745. break;
  3746. const unsigned BitWidth = Op.getValueSizeInBits();
  3747. const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
  3748. const unsigned NumSrcElts = VecVT.getVectorNumElements();
  3749. // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
  3750. // anything about sign bits. But if the sizes match we can derive knowledge
  3751. // about sign bits from the vector operand.
  3752. if (BitWidth != EltBitWidth)
  3753. break;
  3754. // If we know the element index, just demand that vector element, else for
  3755. // an unknown element index, ignore DemandedElts and demand them all.
  3756. APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
  3757. auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3758. if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
  3759. DemandedSrcElts =
  3760. APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
  3761. return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
  3762. }
  3763. case ISD::EXTRACT_SUBVECTOR: {
  3764. // Offset the demanded elts by the subvector index.
  3765. SDValue Src = Op.getOperand(0);
  3766. // Bail until we can represent demanded elements for scalable vectors.
  3767. if (Src.getValueType().isScalableVector())
  3768. break;
  3769. uint64_t Idx = Op.getConstantOperandVal(1);
  3770. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  3771. APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  3772. return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
  3773. }
  3774. case ISD::CONCAT_VECTORS: {
  3775. // Determine the minimum number of sign bits across all demanded
  3776. // elts of the input vectors. Early out if the result is already 1.
  3777. Tmp = std::numeric_limits<unsigned>::max();
  3778. EVT SubVectorVT = Op.getOperand(0).getValueType();
  3779. unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
  3780. unsigned NumSubVectors = Op.getNumOperands();
  3781. for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
  3782. APInt DemandedSub =
  3783. DemandedElts.extractBits(NumSubVectorElts, i * NumSubVectorElts);
  3784. if (!DemandedSub)
  3785. continue;
  3786. Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
  3787. Tmp = std::min(Tmp, Tmp2);
  3788. }
  3789. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3790. return Tmp;
  3791. }
  3792. case ISD::INSERT_SUBVECTOR: {
  3793. // Demand any elements from the subvector and the remainder from the src its
  3794. // inserted into.
  3795. SDValue Src = Op.getOperand(0);
  3796. SDValue Sub = Op.getOperand(1);
  3797. uint64_t Idx = Op.getConstantOperandVal(2);
  3798. unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
  3799. APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
  3800. APInt DemandedSrcElts = DemandedElts;
  3801. DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
  3802. Tmp = std::numeric_limits<unsigned>::max();
  3803. if (!!DemandedSubElts) {
  3804. Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
  3805. if (Tmp == 1)
  3806. return 1; // early-out
  3807. }
  3808. if (!!DemandedSrcElts) {
  3809. Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
  3810. Tmp = std::min(Tmp, Tmp2);
  3811. }
  3812. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3813. return Tmp;
  3814. }
  3815. case ISD::ATOMIC_CMP_SWAP:
  3816. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  3817. case ISD::ATOMIC_SWAP:
  3818. case ISD::ATOMIC_LOAD_ADD:
  3819. case ISD::ATOMIC_LOAD_SUB:
  3820. case ISD::ATOMIC_LOAD_AND:
  3821. case ISD::ATOMIC_LOAD_CLR:
  3822. case ISD::ATOMIC_LOAD_OR:
  3823. case ISD::ATOMIC_LOAD_XOR:
  3824. case ISD::ATOMIC_LOAD_NAND:
  3825. case ISD::ATOMIC_LOAD_MIN:
  3826. case ISD::ATOMIC_LOAD_MAX:
  3827. case ISD::ATOMIC_LOAD_UMIN:
  3828. case ISD::ATOMIC_LOAD_UMAX:
  3829. case ISD::ATOMIC_LOAD: {
  3830. Tmp = cast<AtomicSDNode>(Op)->getMemoryVT().getScalarSizeInBits();
  3831. // If we are looking at the loaded value.
  3832. if (Op.getResNo() == 0) {
  3833. if (Tmp == VTBits)
  3834. return 1; // early-out
  3835. if (TLI->getExtendForAtomicOps() == ISD::SIGN_EXTEND)
  3836. return VTBits - Tmp + 1;
  3837. if (TLI->getExtendForAtomicOps() == ISD::ZERO_EXTEND)
  3838. return VTBits - Tmp;
  3839. }
  3840. break;
  3841. }
  3842. }
  3843. // If we are looking at the loaded value of the SDNode.
  3844. if (Op.getResNo() == 0) {
  3845. // Handle LOADX separately here. EXTLOAD case will fallthrough.
  3846. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
  3847. unsigned ExtType = LD->getExtensionType();
  3848. switch (ExtType) {
  3849. default: break;
  3850. case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
  3851. Tmp = LD->getMemoryVT().getScalarSizeInBits();
  3852. return VTBits - Tmp + 1;
  3853. case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
  3854. Tmp = LD->getMemoryVT().getScalarSizeInBits();
  3855. return VTBits - Tmp;
  3856. case ISD::NON_EXTLOAD:
  3857. if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
  3858. // We only need to handle vectors - computeKnownBits should handle
  3859. // scalar cases.
  3860. Type *CstTy = Cst->getType();
  3861. if (CstTy->isVectorTy() &&
  3862. (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits() &&
  3863. VTBits == CstTy->getScalarSizeInBits()) {
  3864. Tmp = VTBits;
  3865. for (unsigned i = 0; i != NumElts; ++i) {
  3866. if (!DemandedElts[i])
  3867. continue;
  3868. if (Constant *Elt = Cst->getAggregateElement(i)) {
  3869. if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
  3870. const APInt &Value = CInt->getValue();
  3871. Tmp = std::min(Tmp, Value.getNumSignBits());
  3872. continue;
  3873. }
  3874. if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
  3875. APInt Value = CFP->getValueAPF().bitcastToAPInt();
  3876. Tmp = std::min(Tmp, Value.getNumSignBits());
  3877. continue;
  3878. }
  3879. }
  3880. // Unknown type. Conservatively assume no bits match sign bit.
  3881. return 1;
  3882. }
  3883. return Tmp;
  3884. }
  3885. }
  3886. break;
  3887. }
  3888. }
  3889. }
  3890. // Allow the target to implement this method for its nodes.
  3891. if (Opcode >= ISD::BUILTIN_OP_END ||
  3892. Opcode == ISD::INTRINSIC_WO_CHAIN ||
  3893. Opcode == ISD::INTRINSIC_W_CHAIN ||
  3894. Opcode == ISD::INTRINSIC_VOID) {
  3895. unsigned NumBits =
  3896. TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
  3897. if (NumBits > 1)
  3898. FirstAnswer = std::max(FirstAnswer, NumBits);
  3899. }
  3900. // Finally, if we can prove that the top bits of the result are 0's or 1's,
  3901. // use this information.
  3902. KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
  3903. return std::max(FirstAnswer, Known.countMinSignBits());
  3904. }
  3905. unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
  3906. unsigned Depth) const {
  3907. unsigned SignBits = ComputeNumSignBits(Op, Depth);
  3908. return Op.getScalarValueSizeInBits() - SignBits + 1;
  3909. }
  3910. unsigned SelectionDAG::ComputeMaxSignificantBits(SDValue Op,
  3911. const APInt &DemandedElts,
  3912. unsigned Depth) const {
  3913. unsigned SignBits = ComputeNumSignBits(Op, DemandedElts, Depth);
  3914. return Op.getScalarValueSizeInBits() - SignBits + 1;
  3915. }
  3916. bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op, bool PoisonOnly,
  3917. unsigned Depth) const {
  3918. // Early out for FREEZE.
  3919. if (Op.getOpcode() == ISD::FREEZE)
  3920. return true;
  3921. // TODO: Assume we don't know anything for now.
  3922. EVT VT = Op.getValueType();
  3923. if (VT.isScalableVector())
  3924. return false;
  3925. APInt DemandedElts = VT.isVector()
  3926. ? APInt::getAllOnes(VT.getVectorNumElements())
  3927. : APInt(1, 1);
  3928. return isGuaranteedNotToBeUndefOrPoison(Op, DemandedElts, PoisonOnly, Depth);
  3929. }
  3930. bool SelectionDAG::isGuaranteedNotToBeUndefOrPoison(SDValue Op,
  3931. const APInt &DemandedElts,
  3932. bool PoisonOnly,
  3933. unsigned Depth) const {
  3934. unsigned Opcode = Op.getOpcode();
  3935. // Early out for FREEZE.
  3936. if (Opcode == ISD::FREEZE)
  3937. return true;
  3938. if (Depth >= MaxRecursionDepth)
  3939. return false; // Limit search depth.
  3940. if (isIntOrFPConstant(Op))
  3941. return true;
  3942. switch (Opcode) {
  3943. case ISD::UNDEF:
  3944. return PoisonOnly;
  3945. case ISD::BUILD_VECTOR:
  3946. // NOTE: BUILD_VECTOR has implicit truncation of wider scalar elements -
  3947. // this shouldn't affect the result.
  3948. for (unsigned i = 0, e = Op.getNumOperands(); i < e; ++i) {
  3949. if (!DemandedElts[i])
  3950. continue;
  3951. if (!isGuaranteedNotToBeUndefOrPoison(Op.getOperand(i), PoisonOnly,
  3952. Depth + 1))
  3953. return false;
  3954. }
  3955. return true;
  3956. // TODO: Search for noundef attributes from library functions.
  3957. // TODO: Pointers dereferenced by ISD::LOAD/STORE ops are noundef.
  3958. default:
  3959. // Allow the target to implement this method for its nodes.
  3960. if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::INTRINSIC_WO_CHAIN ||
  3961. Opcode == ISD::INTRINSIC_W_CHAIN || Opcode == ISD::INTRINSIC_VOID)
  3962. return TLI->isGuaranteedNotToBeUndefOrPoisonForTargetNode(
  3963. Op, DemandedElts, *this, PoisonOnly, Depth);
  3964. break;
  3965. }
  3966. return false;
  3967. }
  3968. bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
  3969. if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
  3970. !isa<ConstantSDNode>(Op.getOperand(1)))
  3971. return false;
  3972. if (Op.getOpcode() == ISD::OR &&
  3973. !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
  3974. return false;
  3975. return true;
  3976. }
  3977. bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
  3978. // If we're told that NaNs won't happen, assume they won't.
  3979. if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
  3980. return true;
  3981. if (Depth >= MaxRecursionDepth)
  3982. return false; // Limit search depth.
  3983. // TODO: Handle vectors.
  3984. // If the value is a constant, we can obviously see if it is a NaN or not.
  3985. if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
  3986. return !C->getValueAPF().isNaN() ||
  3987. (SNaN && !C->getValueAPF().isSignaling());
  3988. }
  3989. unsigned Opcode = Op.getOpcode();
  3990. switch (Opcode) {
  3991. case ISD::FADD:
  3992. case ISD::FSUB:
  3993. case ISD::FMUL:
  3994. case ISD::FDIV:
  3995. case ISD::FREM:
  3996. case ISD::FSIN:
  3997. case ISD::FCOS: {
  3998. if (SNaN)
  3999. return true;
  4000. // TODO: Need isKnownNeverInfinity
  4001. return false;
  4002. }
  4003. case ISD::FCANONICALIZE:
  4004. case ISD::FEXP:
  4005. case ISD::FEXP2:
  4006. case ISD::FTRUNC:
  4007. case ISD::FFLOOR:
  4008. case ISD::FCEIL:
  4009. case ISD::FROUND:
  4010. case ISD::FROUNDEVEN:
  4011. case ISD::FRINT:
  4012. case ISD::FNEARBYINT: {
  4013. if (SNaN)
  4014. return true;
  4015. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  4016. }
  4017. case ISD::FABS:
  4018. case ISD::FNEG:
  4019. case ISD::FCOPYSIGN: {
  4020. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  4021. }
  4022. case ISD::SELECT:
  4023. return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
  4024. isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
  4025. case ISD::FP_EXTEND:
  4026. case ISD::FP_ROUND: {
  4027. if (SNaN)
  4028. return true;
  4029. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  4030. }
  4031. case ISD::SINT_TO_FP:
  4032. case ISD::UINT_TO_FP:
  4033. return true;
  4034. case ISD::FMA:
  4035. case ISD::FMAD: {
  4036. if (SNaN)
  4037. return true;
  4038. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
  4039. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
  4040. isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
  4041. }
  4042. case ISD::FSQRT: // Need is known positive
  4043. case ISD::FLOG:
  4044. case ISD::FLOG2:
  4045. case ISD::FLOG10:
  4046. case ISD::FPOWI:
  4047. case ISD::FPOW: {
  4048. if (SNaN)
  4049. return true;
  4050. // TODO: Refine on operand
  4051. return false;
  4052. }
  4053. case ISD::FMINNUM:
  4054. case ISD::FMAXNUM: {
  4055. // Only one needs to be known not-nan, since it will be returned if the
  4056. // other ends up being one.
  4057. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
  4058. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
  4059. }
  4060. case ISD::FMINNUM_IEEE:
  4061. case ISD::FMAXNUM_IEEE: {
  4062. if (SNaN)
  4063. return true;
  4064. // This can return a NaN if either operand is an sNaN, or if both operands
  4065. // are NaN.
  4066. return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
  4067. isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
  4068. (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
  4069. isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
  4070. }
  4071. case ISD::FMINIMUM:
  4072. case ISD::FMAXIMUM: {
  4073. // TODO: Does this quiet or return the origina NaN as-is?
  4074. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
  4075. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
  4076. }
  4077. case ISD::EXTRACT_VECTOR_ELT: {
  4078. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  4079. }
  4080. default:
  4081. if (Opcode >= ISD::BUILTIN_OP_END ||
  4082. Opcode == ISD::INTRINSIC_WO_CHAIN ||
  4083. Opcode == ISD::INTRINSIC_W_CHAIN ||
  4084. Opcode == ISD::INTRINSIC_VOID) {
  4085. return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
  4086. }
  4087. return false;
  4088. }
  4089. }
  4090. bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
  4091. assert(Op.getValueType().isFloatingPoint() &&
  4092. "Floating point type expected");
  4093. // If the value is a constant, we can obviously see if it is a zero or not.
  4094. // TODO: Add BuildVector support.
  4095. if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
  4096. return !C->isZero();
  4097. return false;
  4098. }
  4099. bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
  4100. assert(!Op.getValueType().isFloatingPoint() &&
  4101. "Floating point types unsupported - use isKnownNeverZeroFloat");
  4102. // If the value is a constant, we can obviously see if it is a zero or not.
  4103. if (ISD::matchUnaryPredicate(Op,
  4104. [](ConstantSDNode *C) { return !C->isZero(); }))
  4105. return true;
  4106. // TODO: Recognize more cases here.
  4107. switch (Op.getOpcode()) {
  4108. default: break;
  4109. case ISD::OR:
  4110. if (isKnownNeverZero(Op.getOperand(1)) ||
  4111. isKnownNeverZero(Op.getOperand(0)))
  4112. return true;
  4113. break;
  4114. }
  4115. return false;
  4116. }
  4117. bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
  4118. // Check the obvious case.
  4119. if (A == B) return true;
  4120. // For for negative and positive zero.
  4121. if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
  4122. if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
  4123. if (CA->isZero() && CB->isZero()) return true;
  4124. // Otherwise they may not be equal.
  4125. return false;
  4126. }
  4127. // FIXME: unify with llvm::haveNoCommonBitsSet.
  4128. bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
  4129. assert(A.getValueType() == B.getValueType() &&
  4130. "Values must have the same type");
  4131. // Match masked merge pattern (X & ~M) op (Y & M)
  4132. if (A->getOpcode() == ISD::AND && B->getOpcode() == ISD::AND) {
  4133. auto MatchNoCommonBitsPattern = [&](SDValue NotM, SDValue And) {
  4134. if (isBitwiseNot(NotM, true)) {
  4135. SDValue NotOperand = NotM->getOperand(0);
  4136. return NotOperand == And->getOperand(0) ||
  4137. NotOperand == And->getOperand(1);
  4138. }
  4139. return false;
  4140. };
  4141. if (MatchNoCommonBitsPattern(A->getOperand(0), B) ||
  4142. MatchNoCommonBitsPattern(A->getOperand(1), B) ||
  4143. MatchNoCommonBitsPattern(B->getOperand(0), A) ||
  4144. MatchNoCommonBitsPattern(B->getOperand(1), A))
  4145. return true;
  4146. }
  4147. return KnownBits::haveNoCommonBitsSet(computeKnownBits(A),
  4148. computeKnownBits(B));
  4149. }
  4150. static SDValue FoldSTEP_VECTOR(const SDLoc &DL, EVT VT, SDValue Step,
  4151. SelectionDAG &DAG) {
  4152. if (cast<ConstantSDNode>(Step)->isZero())
  4153. return DAG.getConstant(0, DL, VT);
  4154. return SDValue();
  4155. }
  4156. static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
  4157. ArrayRef<SDValue> Ops,
  4158. SelectionDAG &DAG) {
  4159. int NumOps = Ops.size();
  4160. assert(NumOps != 0 && "Can't build an empty vector!");
  4161. assert(!VT.isScalableVector() &&
  4162. "BUILD_VECTOR cannot be used with scalable types");
  4163. assert(VT.getVectorNumElements() == (unsigned)NumOps &&
  4164. "Incorrect element count in BUILD_VECTOR!");
  4165. // BUILD_VECTOR of UNDEFs is UNDEF.
  4166. if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
  4167. return DAG.getUNDEF(VT);
  4168. // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
  4169. SDValue IdentitySrc;
  4170. bool IsIdentity = true;
  4171. for (int i = 0; i != NumOps; ++i) {
  4172. if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  4173. Ops[i].getOperand(0).getValueType() != VT ||
  4174. (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
  4175. !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
  4176. cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
  4177. IsIdentity = false;
  4178. break;
  4179. }
  4180. IdentitySrc = Ops[i].getOperand(0);
  4181. }
  4182. if (IsIdentity)
  4183. return IdentitySrc;
  4184. return SDValue();
  4185. }
  4186. /// Try to simplify vector concatenation to an input value, undef, or build
  4187. /// vector.
  4188. static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
  4189. ArrayRef<SDValue> Ops,
  4190. SelectionDAG &DAG) {
  4191. assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
  4192. assert(llvm::all_of(Ops,
  4193. [Ops](SDValue Op) {
  4194. return Ops[0].getValueType() == Op.getValueType();
  4195. }) &&
  4196. "Concatenation of vectors with inconsistent value types!");
  4197. assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
  4198. VT.getVectorElementCount() &&
  4199. "Incorrect element count in vector concatenation!");
  4200. if (Ops.size() == 1)
  4201. return Ops[0];
  4202. // Concat of UNDEFs is UNDEF.
  4203. if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
  4204. return DAG.getUNDEF(VT);
  4205. // Scan the operands and look for extract operations from a single source
  4206. // that correspond to insertion at the same location via this concatenation:
  4207. // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
  4208. SDValue IdentitySrc;
  4209. bool IsIdentity = true;
  4210. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  4211. SDValue Op = Ops[i];
  4212. unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
  4213. if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
  4214. Op.getOperand(0).getValueType() != VT ||
  4215. (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
  4216. Op.getConstantOperandVal(1) != IdentityIndex) {
  4217. IsIdentity = false;
  4218. break;
  4219. }
  4220. assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
  4221. "Unexpected identity source vector for concat of extracts");
  4222. IdentitySrc = Op.getOperand(0);
  4223. }
  4224. if (IsIdentity) {
  4225. assert(IdentitySrc && "Failed to set source vector of extracts");
  4226. return IdentitySrc;
  4227. }
  4228. // The code below this point is only designed to work for fixed width
  4229. // vectors, so we bail out for now.
  4230. if (VT.isScalableVector())
  4231. return SDValue();
  4232. // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
  4233. // simplified to one big BUILD_VECTOR.
  4234. // FIXME: Add support for SCALAR_TO_VECTOR as well.
  4235. EVT SVT = VT.getScalarType();
  4236. SmallVector<SDValue, 16> Elts;
  4237. for (SDValue Op : Ops) {
  4238. EVT OpVT = Op.getValueType();
  4239. if (Op.isUndef())
  4240. Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
  4241. else if (Op.getOpcode() == ISD::BUILD_VECTOR)
  4242. Elts.append(Op->op_begin(), Op->op_end());
  4243. else
  4244. return SDValue();
  4245. }
  4246. // BUILD_VECTOR requires all inputs to be of the same type, find the
  4247. // maximum type and extend them all.
  4248. for (SDValue Op : Elts)
  4249. SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
  4250. if (SVT.bitsGT(VT.getScalarType())) {
  4251. for (SDValue &Op : Elts) {
  4252. if (Op.isUndef())
  4253. Op = DAG.getUNDEF(SVT);
  4254. else
  4255. Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
  4256. ? DAG.getZExtOrTrunc(Op, DL, SVT)
  4257. : DAG.getSExtOrTrunc(Op, DL, SVT);
  4258. }
  4259. }
  4260. SDValue V = DAG.getBuildVector(VT, DL, Elts);
  4261. NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
  4262. return V;
  4263. }
  4264. /// Gets or creates the specified node.
  4265. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
  4266. FoldingSetNodeID ID;
  4267. AddNodeIDNode(ID, Opcode, getVTList(VT), None);
  4268. void *IP = nullptr;
  4269. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  4270. return SDValue(E, 0);
  4271. auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
  4272. getVTList(VT));
  4273. CSEMap.InsertNode(N, IP);
  4274. InsertNode(N);
  4275. SDValue V = SDValue(N, 0);
  4276. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4277. return V;
  4278. }
  4279. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4280. SDValue Operand) {
  4281. SDNodeFlags Flags;
  4282. if (Inserter)
  4283. Flags = Inserter->getFlags();
  4284. return getNode(Opcode, DL, VT, Operand, Flags);
  4285. }
  4286. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4287. SDValue Operand, const SDNodeFlags Flags) {
  4288. assert(Operand.getOpcode() != ISD::DELETED_NODE &&
  4289. "Operand is DELETED_NODE!");
  4290. // Constant fold unary operations with an integer constant operand. Even
  4291. // opaque constant will be folded, because the folding of unary operations
  4292. // doesn't create new constants with different values. Nevertheless, the
  4293. // opaque flag is preserved during folding to prevent future folding with
  4294. // other constants.
  4295. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
  4296. const APInt &Val = C->getAPIntValue();
  4297. switch (Opcode) {
  4298. default: break;
  4299. case ISD::SIGN_EXTEND:
  4300. return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
  4301. C->isTargetOpcode(), C->isOpaque());
  4302. case ISD::TRUNCATE:
  4303. if (C->isOpaque())
  4304. break;
  4305. LLVM_FALLTHROUGH;
  4306. case ISD::ZERO_EXTEND:
  4307. return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
  4308. C->isTargetOpcode(), C->isOpaque());
  4309. case ISD::ANY_EXTEND:
  4310. // Some targets like RISCV prefer to sign extend some types.
  4311. if (TLI->isSExtCheaperThanZExt(Operand.getValueType(), VT))
  4312. return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
  4313. C->isTargetOpcode(), C->isOpaque());
  4314. return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
  4315. C->isTargetOpcode(), C->isOpaque());
  4316. case ISD::UINT_TO_FP:
  4317. case ISD::SINT_TO_FP: {
  4318. APFloat apf(EVTToAPFloatSemantics(VT),
  4319. APInt::getZero(VT.getSizeInBits()));
  4320. (void)apf.convertFromAPInt(Val,
  4321. Opcode==ISD::SINT_TO_FP,
  4322. APFloat::rmNearestTiesToEven);
  4323. return getConstantFP(apf, DL, VT);
  4324. }
  4325. case ISD::BITCAST:
  4326. if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
  4327. return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
  4328. if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
  4329. return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
  4330. if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
  4331. return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
  4332. if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
  4333. return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
  4334. break;
  4335. case ISD::ABS:
  4336. return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
  4337. C->isOpaque());
  4338. case ISD::BITREVERSE:
  4339. return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
  4340. C->isOpaque());
  4341. case ISD::BSWAP:
  4342. return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
  4343. C->isOpaque());
  4344. case ISD::CTPOP:
  4345. return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
  4346. C->isOpaque());
  4347. case ISD::CTLZ:
  4348. case ISD::CTLZ_ZERO_UNDEF:
  4349. return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
  4350. C->isOpaque());
  4351. case ISD::CTTZ:
  4352. case ISD::CTTZ_ZERO_UNDEF:
  4353. return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
  4354. C->isOpaque());
  4355. case ISD::FP16_TO_FP: {
  4356. bool Ignored;
  4357. APFloat FPV(APFloat::IEEEhalf(),
  4358. (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
  4359. // This can return overflow, underflow, or inexact; we don't care.
  4360. // FIXME need to be more flexible about rounding mode.
  4361. (void)FPV.convert(EVTToAPFloatSemantics(VT),
  4362. APFloat::rmNearestTiesToEven, &Ignored);
  4363. return getConstantFP(FPV, DL, VT);
  4364. }
  4365. case ISD::STEP_VECTOR: {
  4366. if (SDValue V = FoldSTEP_VECTOR(DL, VT, Operand, *this))
  4367. return V;
  4368. break;
  4369. }
  4370. }
  4371. }
  4372. // Constant fold unary operations with a floating point constant operand.
  4373. if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
  4374. APFloat V = C->getValueAPF(); // make copy
  4375. switch (Opcode) {
  4376. case ISD::FNEG:
  4377. V.changeSign();
  4378. return getConstantFP(V, DL, VT);
  4379. case ISD::FABS:
  4380. V.clearSign();
  4381. return getConstantFP(V, DL, VT);
  4382. case ISD::FCEIL: {
  4383. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
  4384. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  4385. return getConstantFP(V, DL, VT);
  4386. break;
  4387. }
  4388. case ISD::FTRUNC: {
  4389. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
  4390. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  4391. return getConstantFP(V, DL, VT);
  4392. break;
  4393. }
  4394. case ISD::FFLOOR: {
  4395. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
  4396. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  4397. return getConstantFP(V, DL, VT);
  4398. break;
  4399. }
  4400. case ISD::FP_EXTEND: {
  4401. bool ignored;
  4402. // This can return overflow, underflow, or inexact; we don't care.
  4403. // FIXME need to be more flexible about rounding mode.
  4404. (void)V.convert(EVTToAPFloatSemantics(VT),
  4405. APFloat::rmNearestTiesToEven, &ignored);
  4406. return getConstantFP(V, DL, VT);
  4407. }
  4408. case ISD::FP_TO_SINT:
  4409. case ISD::FP_TO_UINT: {
  4410. bool ignored;
  4411. APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
  4412. // FIXME need to be more flexible about rounding mode.
  4413. APFloat::opStatus s =
  4414. V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
  4415. if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
  4416. break;
  4417. return getConstant(IntVal, DL, VT);
  4418. }
  4419. case ISD::BITCAST:
  4420. if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
  4421. return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  4422. if (VT == MVT::i16 && C->getValueType(0) == MVT::bf16)
  4423. return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  4424. if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
  4425. return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  4426. if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
  4427. return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
  4428. break;
  4429. case ISD::FP_TO_FP16: {
  4430. bool Ignored;
  4431. // This can return overflow, underflow, or inexact; we don't care.
  4432. // FIXME need to be more flexible about rounding mode.
  4433. (void)V.convert(APFloat::IEEEhalf(),
  4434. APFloat::rmNearestTiesToEven, &Ignored);
  4435. return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
  4436. }
  4437. }
  4438. }
  4439. // Constant fold unary operations with a vector integer or float operand.
  4440. switch (Opcode) {
  4441. default:
  4442. // FIXME: Entirely reasonable to perform folding of other unary
  4443. // operations here as the need arises.
  4444. break;
  4445. case ISD::FNEG:
  4446. case ISD::FABS:
  4447. case ISD::FCEIL:
  4448. case ISD::FTRUNC:
  4449. case ISD::FFLOOR:
  4450. case ISD::FP_EXTEND:
  4451. case ISD::FP_TO_SINT:
  4452. case ISD::FP_TO_UINT:
  4453. case ISD::TRUNCATE:
  4454. case ISD::ANY_EXTEND:
  4455. case ISD::ZERO_EXTEND:
  4456. case ISD::SIGN_EXTEND:
  4457. case ISD::UINT_TO_FP:
  4458. case ISD::SINT_TO_FP:
  4459. case ISD::ABS:
  4460. case ISD::BITREVERSE:
  4461. case ISD::BSWAP:
  4462. case ISD::CTLZ:
  4463. case ISD::CTLZ_ZERO_UNDEF:
  4464. case ISD::CTTZ:
  4465. case ISD::CTTZ_ZERO_UNDEF:
  4466. case ISD::CTPOP: {
  4467. SDValue Ops = {Operand};
  4468. if (SDValue Fold = FoldConstantArithmetic(Opcode, DL, VT, Ops))
  4469. return Fold;
  4470. }
  4471. }
  4472. unsigned OpOpcode = Operand.getNode()->getOpcode();
  4473. switch (Opcode) {
  4474. case ISD::STEP_VECTOR:
  4475. assert(VT.isScalableVector() &&
  4476. "STEP_VECTOR can only be used with scalable types");
  4477. assert(OpOpcode == ISD::TargetConstant &&
  4478. VT.getVectorElementType() == Operand.getValueType() &&
  4479. "Unexpected step operand");
  4480. break;
  4481. case ISD::FREEZE:
  4482. assert(VT == Operand.getValueType() && "Unexpected VT!");
  4483. break;
  4484. case ISD::TokenFactor:
  4485. case ISD::MERGE_VALUES:
  4486. case ISD::CONCAT_VECTORS:
  4487. return Operand; // Factor, merge or concat of one node? No need.
  4488. case ISD::BUILD_VECTOR: {
  4489. // Attempt to simplify BUILD_VECTOR.
  4490. SDValue Ops[] = {Operand};
  4491. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  4492. return V;
  4493. break;
  4494. }
  4495. case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
  4496. case ISD::FP_EXTEND:
  4497. assert(VT.isFloatingPoint() &&
  4498. Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
  4499. if (Operand.getValueType() == VT) return Operand; // noop conversion.
  4500. assert((!VT.isVector() ||
  4501. VT.getVectorElementCount() ==
  4502. Operand.getValueType().getVectorElementCount()) &&
  4503. "Vector element count mismatch!");
  4504. assert(Operand.getValueType().bitsLT(VT) &&
  4505. "Invalid fpext node, dst < src!");
  4506. if (Operand.isUndef())
  4507. return getUNDEF(VT);
  4508. break;
  4509. case ISD::FP_TO_SINT:
  4510. case ISD::FP_TO_UINT:
  4511. if (Operand.isUndef())
  4512. return getUNDEF(VT);
  4513. break;
  4514. case ISD::SINT_TO_FP:
  4515. case ISD::UINT_TO_FP:
  4516. // [us]itofp(undef) = 0, because the result value is bounded.
  4517. if (Operand.isUndef())
  4518. return getConstantFP(0.0, DL, VT);
  4519. break;
  4520. case ISD::SIGN_EXTEND:
  4521. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  4522. "Invalid SIGN_EXTEND!");
  4523. assert(VT.isVector() == Operand.getValueType().isVector() &&
  4524. "SIGN_EXTEND result type type should be vector iff the operand "
  4525. "type is vector!");
  4526. if (Operand.getValueType() == VT) return Operand; // noop extension
  4527. assert((!VT.isVector() ||
  4528. VT.getVectorElementCount() ==
  4529. Operand.getValueType().getVectorElementCount()) &&
  4530. "Vector element count mismatch!");
  4531. assert(Operand.getValueType().bitsLT(VT) &&
  4532. "Invalid sext node, dst < src!");
  4533. if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
  4534. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  4535. if (OpOpcode == ISD::UNDEF)
  4536. // sext(undef) = 0, because the top bits will all be the same.
  4537. return getConstant(0, DL, VT);
  4538. break;
  4539. case ISD::ZERO_EXTEND:
  4540. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  4541. "Invalid ZERO_EXTEND!");
  4542. assert(VT.isVector() == Operand.getValueType().isVector() &&
  4543. "ZERO_EXTEND result type type should be vector iff the operand "
  4544. "type is vector!");
  4545. if (Operand.getValueType() == VT) return Operand; // noop extension
  4546. assert((!VT.isVector() ||
  4547. VT.getVectorElementCount() ==
  4548. Operand.getValueType().getVectorElementCount()) &&
  4549. "Vector element count mismatch!");
  4550. assert(Operand.getValueType().bitsLT(VT) &&
  4551. "Invalid zext node, dst < src!");
  4552. if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
  4553. return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
  4554. if (OpOpcode == ISD::UNDEF)
  4555. // zext(undef) = 0, because the top bits will be zero.
  4556. return getConstant(0, DL, VT);
  4557. break;
  4558. case ISD::ANY_EXTEND:
  4559. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  4560. "Invalid ANY_EXTEND!");
  4561. assert(VT.isVector() == Operand.getValueType().isVector() &&
  4562. "ANY_EXTEND result type type should be vector iff the operand "
  4563. "type is vector!");
  4564. if (Operand.getValueType() == VT) return Operand; // noop extension
  4565. assert((!VT.isVector() ||
  4566. VT.getVectorElementCount() ==
  4567. Operand.getValueType().getVectorElementCount()) &&
  4568. "Vector element count mismatch!");
  4569. assert(Operand.getValueType().bitsLT(VT) &&
  4570. "Invalid anyext node, dst < src!");
  4571. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  4572. OpOpcode == ISD::ANY_EXTEND)
  4573. // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
  4574. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  4575. if (OpOpcode == ISD::UNDEF)
  4576. return getUNDEF(VT);
  4577. // (ext (trunc x)) -> x
  4578. if (OpOpcode == ISD::TRUNCATE) {
  4579. SDValue OpOp = Operand.getOperand(0);
  4580. if (OpOp.getValueType() == VT) {
  4581. transferDbgValues(Operand, OpOp);
  4582. return OpOp;
  4583. }
  4584. }
  4585. break;
  4586. case ISD::TRUNCATE:
  4587. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  4588. "Invalid TRUNCATE!");
  4589. assert(VT.isVector() == Operand.getValueType().isVector() &&
  4590. "TRUNCATE result type type should be vector iff the operand "
  4591. "type is vector!");
  4592. if (Operand.getValueType() == VT) return Operand; // noop truncate
  4593. assert((!VT.isVector() ||
  4594. VT.getVectorElementCount() ==
  4595. Operand.getValueType().getVectorElementCount()) &&
  4596. "Vector element count mismatch!");
  4597. assert(Operand.getValueType().bitsGT(VT) &&
  4598. "Invalid truncate node, src < dst!");
  4599. if (OpOpcode == ISD::TRUNCATE)
  4600. return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
  4601. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  4602. OpOpcode == ISD::ANY_EXTEND) {
  4603. // If the source is smaller than the dest, we still need an extend.
  4604. if (Operand.getOperand(0).getValueType().getScalarType()
  4605. .bitsLT(VT.getScalarType()))
  4606. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  4607. if (Operand.getOperand(0).getValueType().bitsGT(VT))
  4608. return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
  4609. return Operand.getOperand(0);
  4610. }
  4611. if (OpOpcode == ISD::UNDEF)
  4612. return getUNDEF(VT);
  4613. if (OpOpcode == ISD::VSCALE && !NewNodesMustHaveLegalTypes)
  4614. return getVScale(DL, VT, Operand.getConstantOperandAPInt(0));
  4615. break;
  4616. case ISD::ANY_EXTEND_VECTOR_INREG:
  4617. case ISD::ZERO_EXTEND_VECTOR_INREG:
  4618. case ISD::SIGN_EXTEND_VECTOR_INREG:
  4619. assert(VT.isVector() && "This DAG node is restricted to vector types.");
  4620. assert(Operand.getValueType().bitsLE(VT) &&
  4621. "The input must be the same size or smaller than the result.");
  4622. assert(VT.getVectorMinNumElements() <
  4623. Operand.getValueType().getVectorMinNumElements() &&
  4624. "The destination vector type must have fewer lanes than the input.");
  4625. break;
  4626. case ISD::ABS:
  4627. assert(VT.isInteger() && VT == Operand.getValueType() &&
  4628. "Invalid ABS!");
  4629. if (OpOpcode == ISD::UNDEF)
  4630. return getUNDEF(VT);
  4631. break;
  4632. case ISD::BSWAP:
  4633. assert(VT.isInteger() && VT == Operand.getValueType() &&
  4634. "Invalid BSWAP!");
  4635. assert((VT.getScalarSizeInBits() % 16 == 0) &&
  4636. "BSWAP types must be a multiple of 16 bits!");
  4637. if (OpOpcode == ISD::UNDEF)
  4638. return getUNDEF(VT);
  4639. // bswap(bswap(X)) -> X.
  4640. if (OpOpcode == ISD::BSWAP)
  4641. return Operand.getOperand(0);
  4642. break;
  4643. case ISD::BITREVERSE:
  4644. assert(VT.isInteger() && VT == Operand.getValueType() &&
  4645. "Invalid BITREVERSE!");
  4646. if (OpOpcode == ISD::UNDEF)
  4647. return getUNDEF(VT);
  4648. break;
  4649. case ISD::BITCAST:
  4650. assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
  4651. "Cannot BITCAST between types of different sizes!");
  4652. if (VT == Operand.getValueType()) return Operand; // noop conversion.
  4653. if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
  4654. return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
  4655. if (OpOpcode == ISD::UNDEF)
  4656. return getUNDEF(VT);
  4657. break;
  4658. case ISD::SCALAR_TO_VECTOR:
  4659. assert(VT.isVector() && !Operand.getValueType().isVector() &&
  4660. (VT.getVectorElementType() == Operand.getValueType() ||
  4661. (VT.getVectorElementType().isInteger() &&
  4662. Operand.getValueType().isInteger() &&
  4663. VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
  4664. "Illegal SCALAR_TO_VECTOR node!");
  4665. if (OpOpcode == ISD::UNDEF)
  4666. return getUNDEF(VT);
  4667. // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
  4668. if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
  4669. isa<ConstantSDNode>(Operand.getOperand(1)) &&
  4670. Operand.getConstantOperandVal(1) == 0 &&
  4671. Operand.getOperand(0).getValueType() == VT)
  4672. return Operand.getOperand(0);
  4673. break;
  4674. case ISD::FNEG:
  4675. // Negation of an unknown bag of bits is still completely undefined.
  4676. if (OpOpcode == ISD::UNDEF)
  4677. return getUNDEF(VT);
  4678. if (OpOpcode == ISD::FNEG) // --X -> X
  4679. return Operand.getOperand(0);
  4680. break;
  4681. case ISD::FABS:
  4682. if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
  4683. return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
  4684. break;
  4685. case ISD::VSCALE:
  4686. assert(VT == Operand.getValueType() && "Unexpected VT!");
  4687. break;
  4688. case ISD::CTPOP:
  4689. if (Operand.getValueType().getScalarType() == MVT::i1)
  4690. return Operand;
  4691. break;
  4692. case ISD::CTLZ:
  4693. case ISD::CTTZ:
  4694. if (Operand.getValueType().getScalarType() == MVT::i1)
  4695. return getNOT(DL, Operand, Operand.getValueType());
  4696. break;
  4697. case ISD::VECREDUCE_SMIN:
  4698. case ISD::VECREDUCE_UMAX:
  4699. if (Operand.getValueType().getScalarType() == MVT::i1)
  4700. return getNode(ISD::VECREDUCE_OR, DL, VT, Operand);
  4701. break;
  4702. case ISD::VECREDUCE_SMAX:
  4703. case ISD::VECREDUCE_UMIN:
  4704. if (Operand.getValueType().getScalarType() == MVT::i1)
  4705. return getNode(ISD::VECREDUCE_AND, DL, VT, Operand);
  4706. break;
  4707. }
  4708. SDNode *N;
  4709. SDVTList VTs = getVTList(VT);
  4710. SDValue Ops[] = {Operand};
  4711. if (VT != MVT::Glue) { // Don't CSE flag producing nodes
  4712. FoldingSetNodeID ID;
  4713. AddNodeIDNode(ID, Opcode, VTs, Ops);
  4714. void *IP = nullptr;
  4715. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  4716. E->intersectFlagsWith(Flags);
  4717. return SDValue(E, 0);
  4718. }
  4719. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4720. N->setFlags(Flags);
  4721. createOperands(N, Ops);
  4722. CSEMap.InsertNode(N, IP);
  4723. } else {
  4724. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4725. createOperands(N, Ops);
  4726. }
  4727. InsertNode(N);
  4728. SDValue V = SDValue(N, 0);
  4729. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4730. return V;
  4731. }
  4732. static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
  4733. const APInt &C2) {
  4734. switch (Opcode) {
  4735. case ISD::ADD: return C1 + C2;
  4736. case ISD::SUB: return C1 - C2;
  4737. case ISD::MUL: return C1 * C2;
  4738. case ISD::AND: return C1 & C2;
  4739. case ISD::OR: return C1 | C2;
  4740. case ISD::XOR: return C1 ^ C2;
  4741. case ISD::SHL: return C1 << C2;
  4742. case ISD::SRL: return C1.lshr(C2);
  4743. case ISD::SRA: return C1.ashr(C2);
  4744. case ISD::ROTL: return C1.rotl(C2);
  4745. case ISD::ROTR: return C1.rotr(C2);
  4746. case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
  4747. case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
  4748. case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
  4749. case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
  4750. case ISD::SADDSAT: return C1.sadd_sat(C2);
  4751. case ISD::UADDSAT: return C1.uadd_sat(C2);
  4752. case ISD::SSUBSAT: return C1.ssub_sat(C2);
  4753. case ISD::USUBSAT: return C1.usub_sat(C2);
  4754. case ISD::SSHLSAT: return C1.sshl_sat(C2);
  4755. case ISD::USHLSAT: return C1.ushl_sat(C2);
  4756. case ISD::UDIV:
  4757. if (!C2.getBoolValue())
  4758. break;
  4759. return C1.udiv(C2);
  4760. case ISD::UREM:
  4761. if (!C2.getBoolValue())
  4762. break;
  4763. return C1.urem(C2);
  4764. case ISD::SDIV:
  4765. if (!C2.getBoolValue())
  4766. break;
  4767. return C1.sdiv(C2);
  4768. case ISD::SREM:
  4769. if (!C2.getBoolValue())
  4770. break;
  4771. return C1.srem(C2);
  4772. case ISD::MULHS: {
  4773. unsigned FullWidth = C1.getBitWidth() * 2;
  4774. APInt C1Ext = C1.sext(FullWidth);
  4775. APInt C2Ext = C2.sext(FullWidth);
  4776. return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
  4777. }
  4778. case ISD::MULHU: {
  4779. unsigned FullWidth = C1.getBitWidth() * 2;
  4780. APInt C1Ext = C1.zext(FullWidth);
  4781. APInt C2Ext = C2.zext(FullWidth);
  4782. return (C1Ext * C2Ext).extractBits(C1.getBitWidth(), C1.getBitWidth());
  4783. }
  4784. }
  4785. return llvm::None;
  4786. }
  4787. SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
  4788. const GlobalAddressSDNode *GA,
  4789. const SDNode *N2) {
  4790. if (GA->getOpcode() != ISD::GlobalAddress)
  4791. return SDValue();
  4792. if (!TLI->isOffsetFoldingLegal(GA))
  4793. return SDValue();
  4794. auto *C2 = dyn_cast<ConstantSDNode>(N2);
  4795. if (!C2)
  4796. return SDValue();
  4797. int64_t Offset = C2->getSExtValue();
  4798. switch (Opcode) {
  4799. case ISD::ADD: break;
  4800. case ISD::SUB: Offset = -uint64_t(Offset); break;
  4801. default: return SDValue();
  4802. }
  4803. return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
  4804. GA->getOffset() + uint64_t(Offset));
  4805. }
  4806. bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
  4807. switch (Opcode) {
  4808. case ISD::SDIV:
  4809. case ISD::UDIV:
  4810. case ISD::SREM:
  4811. case ISD::UREM: {
  4812. // If a divisor is zero/undef or any element of a divisor vector is
  4813. // zero/undef, the whole op is undef.
  4814. assert(Ops.size() == 2 && "Div/rem should have 2 operands");
  4815. SDValue Divisor = Ops[1];
  4816. if (Divisor.isUndef() || isNullConstant(Divisor))
  4817. return true;
  4818. return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
  4819. llvm::any_of(Divisor->op_values(),
  4820. [](SDValue V) { return V.isUndef() ||
  4821. isNullConstant(V); });
  4822. // TODO: Handle signed overflow.
  4823. }
  4824. // TODO: Handle oversized shifts.
  4825. default:
  4826. return false;
  4827. }
  4828. }
  4829. SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
  4830. EVT VT, ArrayRef<SDValue> Ops) {
  4831. // If the opcode is a target-specific ISD node, there's nothing we can
  4832. // do here and the operand rules may not line up with the below, so
  4833. // bail early.
  4834. // We can't create a scalar CONCAT_VECTORS so skip it. It will break
  4835. // for concats involving SPLAT_VECTOR. Concats of BUILD_VECTORS are handled by
  4836. // foldCONCAT_VECTORS in getNode before this is called.
  4837. if (Opcode >= ISD::BUILTIN_OP_END || Opcode == ISD::CONCAT_VECTORS)
  4838. return SDValue();
  4839. unsigned NumOps = Ops.size();
  4840. if (NumOps == 0)
  4841. return SDValue();
  4842. if (isUndef(Opcode, Ops))
  4843. return getUNDEF(VT);
  4844. // Handle binops special cases.
  4845. if (NumOps == 2) {
  4846. if (SDValue CFP = foldConstantFPMath(Opcode, DL, VT, Ops[0], Ops[1]))
  4847. return CFP;
  4848. if (auto *C1 = dyn_cast<ConstantSDNode>(Ops[0])) {
  4849. if (auto *C2 = dyn_cast<ConstantSDNode>(Ops[1])) {
  4850. if (C1->isOpaque() || C2->isOpaque())
  4851. return SDValue();
  4852. Optional<APInt> FoldAttempt =
  4853. FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
  4854. if (!FoldAttempt)
  4855. return SDValue();
  4856. SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
  4857. assert((!Folded || !VT.isVector()) &&
  4858. "Can't fold vectors ops with scalar operands");
  4859. return Folded;
  4860. }
  4861. }
  4862. // fold (add Sym, c) -> Sym+c
  4863. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[0]))
  4864. return FoldSymbolOffset(Opcode, VT, GA, Ops[1].getNode());
  4865. if (TLI->isCommutativeBinOp(Opcode))
  4866. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Ops[1]))
  4867. return FoldSymbolOffset(Opcode, VT, GA, Ops[0].getNode());
  4868. }
  4869. // This is for vector folding only from here on.
  4870. if (!VT.isVector())
  4871. return SDValue();
  4872. ElementCount NumElts = VT.getVectorElementCount();
  4873. // See if we can fold through bitcasted integer ops.
  4874. // TODO: Can we handle undef elements?
  4875. if (NumOps == 2 && VT.isFixedLengthVector() && VT.isInteger() &&
  4876. Ops[0].getValueType() == VT && Ops[1].getValueType() == VT &&
  4877. Ops[0].getOpcode() == ISD::BITCAST &&
  4878. Ops[1].getOpcode() == ISD::BITCAST) {
  4879. SDValue N1 = peekThroughBitcasts(Ops[0]);
  4880. SDValue N2 = peekThroughBitcasts(Ops[1]);
  4881. auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
  4882. auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
  4883. EVT BVVT = N1.getValueType();
  4884. if (BV1 && BV2 && BVVT.isInteger() && BVVT == N2.getValueType()) {
  4885. bool IsLE = getDataLayout().isLittleEndian();
  4886. unsigned EltBits = VT.getScalarSizeInBits();
  4887. SmallVector<APInt> RawBits1, RawBits2;
  4888. BitVector UndefElts1, UndefElts2;
  4889. if (BV1->getConstantRawBits(IsLE, EltBits, RawBits1, UndefElts1) &&
  4890. BV2->getConstantRawBits(IsLE, EltBits, RawBits2, UndefElts2) &&
  4891. UndefElts1.none() && UndefElts2.none()) {
  4892. SmallVector<APInt> RawBits;
  4893. for (unsigned I = 0, E = NumElts.getFixedValue(); I != E; ++I) {
  4894. Optional<APInt> Fold = FoldValue(Opcode, RawBits1[I], RawBits2[I]);
  4895. if (!Fold)
  4896. break;
  4897. RawBits.push_back(Fold.getValue());
  4898. }
  4899. if (RawBits.size() == NumElts.getFixedValue()) {
  4900. // We have constant folded, but we need to cast this again back to
  4901. // the original (possibly legalized) type.
  4902. SmallVector<APInt> DstBits;
  4903. BitVector DstUndefs;
  4904. BuildVectorSDNode::recastRawBits(IsLE, BVVT.getScalarSizeInBits(),
  4905. DstBits, RawBits, DstUndefs,
  4906. BitVector(RawBits.size(), false));
  4907. EVT BVEltVT = BV1->getOperand(0).getValueType();
  4908. unsigned BVEltBits = BVEltVT.getSizeInBits();
  4909. SmallVector<SDValue> Ops(DstBits.size(), getUNDEF(BVEltVT));
  4910. for (unsigned I = 0, E = DstBits.size(); I != E; ++I) {
  4911. if (DstUndefs[I])
  4912. continue;
  4913. Ops[I] = getConstant(DstBits[I].sextOrSelf(BVEltBits), DL, BVEltVT);
  4914. }
  4915. return getBitcast(VT, getBuildVector(BVVT, DL, Ops));
  4916. }
  4917. }
  4918. }
  4919. }
  4920. // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
  4921. // (shl step_vector(C0), C1) -> (step_vector(C0 << C1))
  4922. if ((Opcode == ISD::MUL || Opcode == ISD::SHL) &&
  4923. Ops[0].getOpcode() == ISD::STEP_VECTOR) {
  4924. APInt RHSVal;
  4925. if (ISD::isConstantSplatVector(Ops[1].getNode(), RHSVal)) {
  4926. APInt NewStep = Opcode == ISD::MUL
  4927. ? Ops[0].getConstantOperandAPInt(0) * RHSVal
  4928. : Ops[0].getConstantOperandAPInt(0) << RHSVal;
  4929. return getStepVector(DL, VT, NewStep);
  4930. }
  4931. }
  4932. auto IsScalarOrSameVectorSize = [NumElts](const SDValue &Op) {
  4933. return !Op.getValueType().isVector() ||
  4934. Op.getValueType().getVectorElementCount() == NumElts;
  4935. };
  4936. auto IsBuildVectorSplatVectorOrUndef = [](const SDValue &Op) {
  4937. return Op.isUndef() || Op.getOpcode() == ISD::CONDCODE ||
  4938. Op.getOpcode() == ISD::BUILD_VECTOR ||
  4939. Op.getOpcode() == ISD::SPLAT_VECTOR;
  4940. };
  4941. // All operands must be vector types with the same number of elements as
  4942. // the result type and must be either UNDEF or a build/splat vector
  4943. // or UNDEF scalars.
  4944. if (!llvm::all_of(Ops, IsBuildVectorSplatVectorOrUndef) ||
  4945. !llvm::all_of(Ops, IsScalarOrSameVectorSize))
  4946. return SDValue();
  4947. // If we are comparing vectors, then the result needs to be a i1 boolean
  4948. // that is then sign-extended back to the legal result type.
  4949. EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
  4950. // Find legal integer scalar type for constant promotion and
  4951. // ensure that its scalar size is at least as large as source.
  4952. EVT LegalSVT = VT.getScalarType();
  4953. if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
  4954. LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
  4955. if (LegalSVT.bitsLT(VT.getScalarType()))
  4956. return SDValue();
  4957. }
  4958. // For scalable vector types we know we're dealing with SPLAT_VECTORs. We
  4959. // only have one operand to check. For fixed-length vector types we may have
  4960. // a combination of BUILD_VECTOR and SPLAT_VECTOR.
  4961. unsigned NumVectorElts = NumElts.isScalable() ? 1 : NumElts.getFixedValue();
  4962. // Constant fold each scalar lane separately.
  4963. SmallVector<SDValue, 4> ScalarResults;
  4964. for (unsigned I = 0; I != NumVectorElts; I++) {
  4965. SmallVector<SDValue, 4> ScalarOps;
  4966. for (SDValue Op : Ops) {
  4967. EVT InSVT = Op.getValueType().getScalarType();
  4968. if (Op.getOpcode() != ISD::BUILD_VECTOR &&
  4969. Op.getOpcode() != ISD::SPLAT_VECTOR) {
  4970. if (Op.isUndef())
  4971. ScalarOps.push_back(getUNDEF(InSVT));
  4972. else
  4973. ScalarOps.push_back(Op);
  4974. continue;
  4975. }
  4976. SDValue ScalarOp =
  4977. Op.getOperand(Op.getOpcode() == ISD::SPLAT_VECTOR ? 0 : I);
  4978. EVT ScalarVT = ScalarOp.getValueType();
  4979. // Build vector (integer) scalar operands may need implicit
  4980. // truncation - do this before constant folding.
  4981. if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT)) {
  4982. // Don't create illegally-typed nodes unless they're constants or undef
  4983. // - if we fail to constant fold we can't guarantee the (dead) nodes
  4984. // we're creating will be cleaned up before being visited for
  4985. // legalization.
  4986. if (NewNodesMustHaveLegalTypes && !ScalarOp.isUndef() &&
  4987. !isa<ConstantSDNode>(ScalarOp) &&
  4988. TLI->getTypeAction(*getContext(), InSVT) !=
  4989. TargetLowering::TypeLegal)
  4990. return SDValue();
  4991. ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
  4992. }
  4993. ScalarOps.push_back(ScalarOp);
  4994. }
  4995. // Constant fold the scalar operands.
  4996. SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps);
  4997. // Legalize the (integer) scalar constant if necessary.
  4998. if (LegalSVT != SVT)
  4999. ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
  5000. // Scalar folding only succeeded if the result is a constant or UNDEF.
  5001. if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
  5002. ScalarResult.getOpcode() != ISD::ConstantFP)
  5003. return SDValue();
  5004. ScalarResults.push_back(ScalarResult);
  5005. }
  5006. SDValue V = NumElts.isScalable() ? getSplatVector(VT, DL, ScalarResults[0])
  5007. : getBuildVector(VT, DL, ScalarResults);
  5008. NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
  5009. return V;
  5010. }
  5011. SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
  5012. EVT VT, SDValue N1, SDValue N2) {
  5013. // TODO: We don't do any constant folding for strict FP opcodes here, but we
  5014. // should. That will require dealing with a potentially non-default
  5015. // rounding mode, checking the "opStatus" return value from the APFloat
  5016. // math calculations, and possibly other variations.
  5017. ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, /*AllowUndefs*/ false);
  5018. ConstantFPSDNode *N2CFP = isConstOrConstSplatFP(N2, /*AllowUndefs*/ false);
  5019. if (N1CFP && N2CFP) {
  5020. APFloat C1 = N1CFP->getValueAPF(); // make copy
  5021. const APFloat &C2 = N2CFP->getValueAPF();
  5022. switch (Opcode) {
  5023. case ISD::FADD:
  5024. C1.add(C2, APFloat::rmNearestTiesToEven);
  5025. return getConstantFP(C1, DL, VT);
  5026. case ISD::FSUB:
  5027. C1.subtract(C2, APFloat::rmNearestTiesToEven);
  5028. return getConstantFP(C1, DL, VT);
  5029. case ISD::FMUL:
  5030. C1.multiply(C2, APFloat::rmNearestTiesToEven);
  5031. return getConstantFP(C1, DL, VT);
  5032. case ISD::FDIV:
  5033. C1.divide(C2, APFloat::rmNearestTiesToEven);
  5034. return getConstantFP(C1, DL, VT);
  5035. case ISD::FREM:
  5036. C1.mod(C2);
  5037. return getConstantFP(C1, DL, VT);
  5038. case ISD::FCOPYSIGN:
  5039. C1.copySign(C2);
  5040. return getConstantFP(C1, DL, VT);
  5041. case ISD::FMINNUM:
  5042. return getConstantFP(minnum(C1, C2), DL, VT);
  5043. case ISD::FMAXNUM:
  5044. return getConstantFP(maxnum(C1, C2), DL, VT);
  5045. case ISD::FMINIMUM:
  5046. return getConstantFP(minimum(C1, C2), DL, VT);
  5047. case ISD::FMAXIMUM:
  5048. return getConstantFP(maximum(C1, C2), DL, VT);
  5049. default: break;
  5050. }
  5051. }
  5052. if (N1CFP && Opcode == ISD::FP_ROUND) {
  5053. APFloat C1 = N1CFP->getValueAPF(); // make copy
  5054. bool Unused;
  5055. // This can return overflow, underflow, or inexact; we don't care.
  5056. // FIXME need to be more flexible about rounding mode.
  5057. (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
  5058. &Unused);
  5059. return getConstantFP(C1, DL, VT);
  5060. }
  5061. switch (Opcode) {
  5062. case ISD::FSUB:
  5063. // -0.0 - undef --> undef (consistent with "fneg undef")
  5064. if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, /*AllowUndefs*/ true))
  5065. if (N1C && N1C->getValueAPF().isNegZero() && N2.isUndef())
  5066. return getUNDEF(VT);
  5067. LLVM_FALLTHROUGH;
  5068. case ISD::FADD:
  5069. case ISD::FMUL:
  5070. case ISD::FDIV:
  5071. case ISD::FREM:
  5072. // If both operands are undef, the result is undef. If 1 operand is undef,
  5073. // the result is NaN. This should match the behavior of the IR optimizer.
  5074. if (N1.isUndef() && N2.isUndef())
  5075. return getUNDEF(VT);
  5076. if (N1.isUndef() || N2.isUndef())
  5077. return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
  5078. }
  5079. return SDValue();
  5080. }
  5081. SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
  5082. assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
  5083. // There's no need to assert on a byte-aligned pointer. All pointers are at
  5084. // least byte aligned.
  5085. if (A == Align(1))
  5086. return Val;
  5087. FoldingSetNodeID ID;
  5088. AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
  5089. ID.AddInteger(A.value());
  5090. void *IP = nullptr;
  5091. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  5092. return SDValue(E, 0);
  5093. auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
  5094. Val.getValueType(), A);
  5095. createOperands(N, {Val});
  5096. CSEMap.InsertNode(N, IP);
  5097. InsertNode(N);
  5098. SDValue V(N, 0);
  5099. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5100. return V;
  5101. }
  5102. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  5103. SDValue N1, SDValue N2) {
  5104. SDNodeFlags Flags;
  5105. if (Inserter)
  5106. Flags = Inserter->getFlags();
  5107. return getNode(Opcode, DL, VT, N1, N2, Flags);
  5108. }
  5109. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  5110. SDValue N1, SDValue N2, const SDNodeFlags Flags) {
  5111. assert(N1.getOpcode() != ISD::DELETED_NODE &&
  5112. N2.getOpcode() != ISD::DELETED_NODE &&
  5113. "Operand is DELETED_NODE!");
  5114. // Canonicalize constant to RHS if commutative.
  5115. if (TLI->isCommutativeBinOp(Opcode)) {
  5116. bool IsN1C = isConstantIntBuildVectorOrConstantInt(N1);
  5117. bool IsN2C = isConstantIntBuildVectorOrConstantInt(N2);
  5118. bool IsN1CFP = isConstantFPBuildVectorOrConstantFP(N1);
  5119. bool IsN2CFP = isConstantFPBuildVectorOrConstantFP(N2);
  5120. if ((IsN1C && !IsN2C) || (IsN1CFP && !IsN2CFP))
  5121. std::swap(N1, N2);
  5122. }
  5123. auto *N1C = dyn_cast<ConstantSDNode>(N1);
  5124. auto *N2C = dyn_cast<ConstantSDNode>(N2);
  5125. // Don't allow undefs in vector splats - we might be returning N2 when folding
  5126. // to zero etc.
  5127. ConstantSDNode *N2CV =
  5128. isConstOrConstSplat(N2, /*AllowUndefs*/ false, /*AllowTruncation*/ true);
  5129. switch (Opcode) {
  5130. default: break;
  5131. case ISD::TokenFactor:
  5132. assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
  5133. N2.getValueType() == MVT::Other && "Invalid token factor!");
  5134. // Fold trivial token factors.
  5135. if (N1.getOpcode() == ISD::EntryToken) return N2;
  5136. if (N2.getOpcode() == ISD::EntryToken) return N1;
  5137. if (N1 == N2) return N1;
  5138. break;
  5139. case ISD::BUILD_VECTOR: {
  5140. // Attempt to simplify BUILD_VECTOR.
  5141. SDValue Ops[] = {N1, N2};
  5142. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  5143. return V;
  5144. break;
  5145. }
  5146. case ISD::CONCAT_VECTORS: {
  5147. SDValue Ops[] = {N1, N2};
  5148. if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
  5149. return V;
  5150. break;
  5151. }
  5152. case ISD::AND:
  5153. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5154. assert(N1.getValueType() == N2.getValueType() &&
  5155. N1.getValueType() == VT && "Binary operator types must match!");
  5156. // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
  5157. // worth handling here.
  5158. if (N2CV && N2CV->isZero())
  5159. return N2;
  5160. if (N2CV && N2CV->isAllOnes()) // X & -1 -> X
  5161. return N1;
  5162. break;
  5163. case ISD::OR:
  5164. case ISD::XOR:
  5165. case ISD::ADD:
  5166. case ISD::SUB:
  5167. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5168. assert(N1.getValueType() == N2.getValueType() &&
  5169. N1.getValueType() == VT && "Binary operator types must match!");
  5170. // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
  5171. // it's worth handling here.
  5172. if (N2CV && N2CV->isZero())
  5173. return N1;
  5174. if ((Opcode == ISD::ADD || Opcode == ISD::SUB) && VT.isVector() &&
  5175. VT.getVectorElementType() == MVT::i1)
  5176. return getNode(ISD::XOR, DL, VT, N1, N2);
  5177. break;
  5178. case ISD::MUL:
  5179. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5180. assert(N1.getValueType() == N2.getValueType() &&
  5181. N1.getValueType() == VT && "Binary operator types must match!");
  5182. if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
  5183. return getNode(ISD::AND, DL, VT, N1, N2);
  5184. if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
  5185. const APInt &MulImm = N1->getConstantOperandAPInt(0);
  5186. const APInt &N2CImm = N2C->getAPIntValue();
  5187. return getVScale(DL, VT, MulImm * N2CImm);
  5188. }
  5189. break;
  5190. case ISD::UDIV:
  5191. case ISD::UREM:
  5192. case ISD::MULHU:
  5193. case ISD::MULHS:
  5194. case ISD::SDIV:
  5195. case ISD::SREM:
  5196. case ISD::SADDSAT:
  5197. case ISD::SSUBSAT:
  5198. case ISD::UADDSAT:
  5199. case ISD::USUBSAT:
  5200. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5201. assert(N1.getValueType() == N2.getValueType() &&
  5202. N1.getValueType() == VT && "Binary operator types must match!");
  5203. if (VT.isVector() && VT.getVectorElementType() == MVT::i1) {
  5204. // fold (add_sat x, y) -> (or x, y) for bool types.
  5205. if (Opcode == ISD::SADDSAT || Opcode == ISD::UADDSAT)
  5206. return getNode(ISD::OR, DL, VT, N1, N2);
  5207. // fold (sub_sat x, y) -> (and x, ~y) for bool types.
  5208. if (Opcode == ISD::SSUBSAT || Opcode == ISD::USUBSAT)
  5209. return getNode(ISD::AND, DL, VT, N1, getNOT(DL, N2, VT));
  5210. }
  5211. break;
  5212. case ISD::SMIN:
  5213. case ISD::UMAX:
  5214. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5215. assert(N1.getValueType() == N2.getValueType() &&
  5216. N1.getValueType() == VT && "Binary operator types must match!");
  5217. if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
  5218. return getNode(ISD::OR, DL, VT, N1, N2);
  5219. break;
  5220. case ISD::SMAX:
  5221. case ISD::UMIN:
  5222. assert(VT.isInteger() && "This operator does not apply to FP types!");
  5223. assert(N1.getValueType() == N2.getValueType() &&
  5224. N1.getValueType() == VT && "Binary operator types must match!");
  5225. if (VT.isVector() && VT.getVectorElementType() == MVT::i1)
  5226. return getNode(ISD::AND, DL, VT, N1, N2);
  5227. break;
  5228. case ISD::FADD:
  5229. case ISD::FSUB:
  5230. case ISD::FMUL:
  5231. case ISD::FDIV:
  5232. case ISD::FREM:
  5233. assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
  5234. assert(N1.getValueType() == N2.getValueType() &&
  5235. N1.getValueType() == VT && "Binary operator types must match!");
  5236. if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
  5237. return V;
  5238. break;
  5239. case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
  5240. assert(N1.getValueType() == VT &&
  5241. N1.getValueType().isFloatingPoint() &&
  5242. N2.getValueType().isFloatingPoint() &&
  5243. "Invalid FCOPYSIGN!");
  5244. break;
  5245. case ISD::SHL:
  5246. if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
  5247. const APInt &MulImm = N1->getConstantOperandAPInt(0);
  5248. const APInt &ShiftImm = N2C->getAPIntValue();
  5249. return getVScale(DL, VT, MulImm << ShiftImm);
  5250. }
  5251. LLVM_FALLTHROUGH;
  5252. case ISD::SRA:
  5253. case ISD::SRL:
  5254. if (SDValue V = simplifyShift(N1, N2))
  5255. return V;
  5256. LLVM_FALLTHROUGH;
  5257. case ISD::ROTL:
  5258. case ISD::ROTR:
  5259. assert(VT == N1.getValueType() &&
  5260. "Shift operators return type must be the same as their first arg");
  5261. assert(VT.isInteger() && N2.getValueType().isInteger() &&
  5262. "Shifts only work on integers");
  5263. assert((!VT.isVector() || VT == N2.getValueType()) &&
  5264. "Vector shift amounts must be in the same as their first arg");
  5265. // Verify that the shift amount VT is big enough to hold valid shift
  5266. // amounts. This catches things like trying to shift an i1024 value by an
  5267. // i8, which is easy to fall into in generic code that uses
  5268. // TLI.getShiftAmount().
  5269. assert(N2.getValueType().getScalarSizeInBits() >=
  5270. Log2_32_Ceil(VT.getScalarSizeInBits()) &&
  5271. "Invalid use of small shift amount with oversized value!");
  5272. // Always fold shifts of i1 values so the code generator doesn't need to
  5273. // handle them. Since we know the size of the shift has to be less than the
  5274. // size of the value, the shift/rotate count is guaranteed to be zero.
  5275. if (VT == MVT::i1)
  5276. return N1;
  5277. if (N2CV && N2CV->isZero())
  5278. return N1;
  5279. break;
  5280. case ISD::FP_ROUND:
  5281. assert(VT.isFloatingPoint() &&
  5282. N1.getValueType().isFloatingPoint() &&
  5283. VT.bitsLE(N1.getValueType()) &&
  5284. N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
  5285. "Invalid FP_ROUND!");
  5286. if (N1.getValueType() == VT) return N1; // noop conversion.
  5287. break;
  5288. case ISD::AssertSext:
  5289. case ISD::AssertZext: {
  5290. EVT EVT = cast<VTSDNode>(N2)->getVT();
  5291. assert(VT == N1.getValueType() && "Not an inreg extend!");
  5292. assert(VT.isInteger() && EVT.isInteger() &&
  5293. "Cannot *_EXTEND_INREG FP types");
  5294. assert(!EVT.isVector() &&
  5295. "AssertSExt/AssertZExt type should be the vector element type "
  5296. "rather than the vector type!");
  5297. assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
  5298. if (VT.getScalarType() == EVT) return N1; // noop assertion.
  5299. break;
  5300. }
  5301. case ISD::SIGN_EXTEND_INREG: {
  5302. EVT EVT = cast<VTSDNode>(N2)->getVT();
  5303. assert(VT == N1.getValueType() && "Not an inreg extend!");
  5304. assert(VT.isInteger() && EVT.isInteger() &&
  5305. "Cannot *_EXTEND_INREG FP types");
  5306. assert(EVT.isVector() == VT.isVector() &&
  5307. "SIGN_EXTEND_INREG type should be vector iff the operand "
  5308. "type is vector!");
  5309. assert((!EVT.isVector() ||
  5310. EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
  5311. "Vector element counts must match in SIGN_EXTEND_INREG");
  5312. assert(EVT.bitsLE(VT) && "Not extending!");
  5313. if (EVT == VT) return N1; // Not actually extending
  5314. auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
  5315. unsigned FromBits = EVT.getScalarSizeInBits();
  5316. Val <<= Val.getBitWidth() - FromBits;
  5317. Val.ashrInPlace(Val.getBitWidth() - FromBits);
  5318. return getConstant(Val, DL, ConstantVT);
  5319. };
  5320. if (N1C) {
  5321. const APInt &Val = N1C->getAPIntValue();
  5322. return SignExtendInReg(Val, VT);
  5323. }
  5324. if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
  5325. SmallVector<SDValue, 8> Ops;
  5326. llvm::EVT OpVT = N1.getOperand(0).getValueType();
  5327. for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
  5328. SDValue Op = N1.getOperand(i);
  5329. if (Op.isUndef()) {
  5330. Ops.push_back(getUNDEF(OpVT));
  5331. continue;
  5332. }
  5333. ConstantSDNode *C = cast<ConstantSDNode>(Op);
  5334. APInt Val = C->getAPIntValue();
  5335. Ops.push_back(SignExtendInReg(Val, OpVT));
  5336. }
  5337. return getBuildVector(VT, DL, Ops);
  5338. }
  5339. break;
  5340. }
  5341. case ISD::FP_TO_SINT_SAT:
  5342. case ISD::FP_TO_UINT_SAT: {
  5343. assert(VT.isInteger() && cast<VTSDNode>(N2)->getVT().isInteger() &&
  5344. N1.getValueType().isFloatingPoint() && "Invalid FP_TO_*INT_SAT");
  5345. assert(N1.getValueType().isVector() == VT.isVector() &&
  5346. "FP_TO_*INT_SAT type should be vector iff the operand type is "
  5347. "vector!");
  5348. assert((!VT.isVector() || VT.getVectorNumElements() ==
  5349. N1.getValueType().getVectorNumElements()) &&
  5350. "Vector element counts must match in FP_TO_*INT_SAT");
  5351. assert(!cast<VTSDNode>(N2)->getVT().isVector() &&
  5352. "Type to saturate to must be a scalar.");
  5353. assert(cast<VTSDNode>(N2)->getVT().bitsLE(VT.getScalarType()) &&
  5354. "Not extending!");
  5355. break;
  5356. }
  5357. case ISD::EXTRACT_VECTOR_ELT:
  5358. assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
  5359. "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
  5360. element type of the vector.");
  5361. // Extract from an undefined value or using an undefined index is undefined.
  5362. if (N1.isUndef() || N2.isUndef())
  5363. return getUNDEF(VT);
  5364. // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
  5365. // vectors. For scalable vectors we will provide appropriate support for
  5366. // dealing with arbitrary indices.
  5367. if (N2C && N1.getValueType().isFixedLengthVector() &&
  5368. N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
  5369. return getUNDEF(VT);
  5370. // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
  5371. // expanding copies of large vectors from registers. This only works for
  5372. // fixed length vectors, since we need to know the exact number of
  5373. // elements.
  5374. if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
  5375. N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
  5376. unsigned Factor =
  5377. N1.getOperand(0).getValueType().getVectorNumElements();
  5378. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
  5379. N1.getOperand(N2C->getZExtValue() / Factor),
  5380. getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
  5381. }
  5382. // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
  5383. // lowering is expanding large vector constants.
  5384. if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
  5385. N1.getOpcode() == ISD::SPLAT_VECTOR)) {
  5386. assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
  5387. N1.getValueType().isFixedLengthVector()) &&
  5388. "BUILD_VECTOR used for scalable vectors");
  5389. unsigned Index =
  5390. N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
  5391. SDValue Elt = N1.getOperand(Index);
  5392. if (VT != Elt.getValueType())
  5393. // If the vector element type is not legal, the BUILD_VECTOR operands
  5394. // are promoted and implicitly truncated, and the result implicitly
  5395. // extended. Make that explicit here.
  5396. Elt = getAnyExtOrTrunc(Elt, DL, VT);
  5397. return Elt;
  5398. }
  5399. // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
  5400. // operations are lowered to scalars.
  5401. if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
  5402. // If the indices are the same, return the inserted element else
  5403. // if the indices are known different, extract the element from
  5404. // the original vector.
  5405. SDValue N1Op2 = N1.getOperand(2);
  5406. ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
  5407. if (N1Op2C && N2C) {
  5408. if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
  5409. if (VT == N1.getOperand(1).getValueType())
  5410. return N1.getOperand(1);
  5411. return getSExtOrTrunc(N1.getOperand(1), DL, VT);
  5412. }
  5413. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
  5414. }
  5415. }
  5416. // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
  5417. // when vector types are scalarized and v1iX is legal.
  5418. // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
  5419. // Here we are completely ignoring the extract element index (N2),
  5420. // which is fine for fixed width vectors, since any index other than 0
  5421. // is undefined anyway. However, this cannot be ignored for scalable
  5422. // vectors - in theory we could support this, but we don't want to do this
  5423. // without a profitability check.
  5424. if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  5425. N1.getValueType().isFixedLengthVector() &&
  5426. N1.getValueType().getVectorNumElements() == 1) {
  5427. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
  5428. N1.getOperand(1));
  5429. }
  5430. break;
  5431. case ISD::EXTRACT_ELEMENT:
  5432. assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
  5433. assert(!N1.getValueType().isVector() && !VT.isVector() &&
  5434. (N1.getValueType().isInteger() == VT.isInteger()) &&
  5435. N1.getValueType() != VT &&
  5436. "Wrong types for EXTRACT_ELEMENT!");
  5437. // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
  5438. // 64-bit integers into 32-bit parts. Instead of building the extract of
  5439. // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
  5440. if (N1.getOpcode() == ISD::BUILD_PAIR)
  5441. return N1.getOperand(N2C->getZExtValue());
  5442. // EXTRACT_ELEMENT of a constant int is also very common.
  5443. if (N1C) {
  5444. unsigned ElementSize = VT.getSizeInBits();
  5445. unsigned Shift = ElementSize * N2C->getZExtValue();
  5446. const APInt &Val = N1C->getAPIntValue();
  5447. return getConstant(Val.extractBits(ElementSize, Shift), DL, VT);
  5448. }
  5449. break;
  5450. case ISD::EXTRACT_SUBVECTOR: {
  5451. EVT N1VT = N1.getValueType();
  5452. assert(VT.isVector() && N1VT.isVector() &&
  5453. "Extract subvector VTs must be vectors!");
  5454. assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
  5455. "Extract subvector VTs must have the same element type!");
  5456. assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
  5457. "Cannot extract a scalable vector from a fixed length vector!");
  5458. assert((VT.isScalableVector() != N1VT.isScalableVector() ||
  5459. VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
  5460. "Extract subvector must be from larger vector to smaller vector!");
  5461. assert(N2C && "Extract subvector index must be a constant");
  5462. assert((VT.isScalableVector() != N1VT.isScalableVector() ||
  5463. (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
  5464. N1VT.getVectorMinNumElements()) &&
  5465. "Extract subvector overflow!");
  5466. assert(N2C->getAPIntValue().getBitWidth() ==
  5467. TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
  5468. "Constant index for EXTRACT_SUBVECTOR has an invalid size");
  5469. // Trivial extraction.
  5470. if (VT == N1VT)
  5471. return N1;
  5472. // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
  5473. if (N1.isUndef())
  5474. return getUNDEF(VT);
  5475. // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
  5476. // the concat have the same type as the extract.
  5477. if (N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0 &&
  5478. VT == N1.getOperand(0).getValueType()) {
  5479. unsigned Factor = VT.getVectorMinNumElements();
  5480. return N1.getOperand(N2C->getZExtValue() / Factor);
  5481. }
  5482. // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
  5483. // during shuffle legalization.
  5484. if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
  5485. VT == N1.getOperand(1).getValueType())
  5486. return N1.getOperand(1);
  5487. break;
  5488. }
  5489. }
  5490. // Perform trivial constant folding.
  5491. if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
  5492. return SV;
  5493. // Canonicalize an UNDEF to the RHS, even over a constant.
  5494. if (N1.isUndef()) {
  5495. if (TLI->isCommutativeBinOp(Opcode)) {
  5496. std::swap(N1, N2);
  5497. } else {
  5498. switch (Opcode) {
  5499. case ISD::SIGN_EXTEND_INREG:
  5500. case ISD::SUB:
  5501. return getUNDEF(VT); // fold op(undef, arg2) -> undef
  5502. case ISD::UDIV:
  5503. case ISD::SDIV:
  5504. case ISD::UREM:
  5505. case ISD::SREM:
  5506. case ISD::SSUBSAT:
  5507. case ISD::USUBSAT:
  5508. return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
  5509. }
  5510. }
  5511. }
  5512. // Fold a bunch of operators when the RHS is undef.
  5513. if (N2.isUndef()) {
  5514. switch (Opcode) {
  5515. case ISD::XOR:
  5516. if (N1.isUndef())
  5517. // Handle undef ^ undef -> 0 special case. This is a common
  5518. // idiom (misuse).
  5519. return getConstant(0, DL, VT);
  5520. LLVM_FALLTHROUGH;
  5521. case ISD::ADD:
  5522. case ISD::SUB:
  5523. case ISD::UDIV:
  5524. case ISD::SDIV:
  5525. case ISD::UREM:
  5526. case ISD::SREM:
  5527. return getUNDEF(VT); // fold op(arg1, undef) -> undef
  5528. case ISD::MUL:
  5529. case ISD::AND:
  5530. case ISD::SSUBSAT:
  5531. case ISD::USUBSAT:
  5532. return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
  5533. case ISD::OR:
  5534. case ISD::SADDSAT:
  5535. case ISD::UADDSAT:
  5536. return getAllOnesConstant(DL, VT);
  5537. }
  5538. }
  5539. // Memoize this node if possible.
  5540. SDNode *N;
  5541. SDVTList VTs = getVTList(VT);
  5542. SDValue Ops[] = {N1, N2};
  5543. if (VT != MVT::Glue) {
  5544. FoldingSetNodeID ID;
  5545. AddNodeIDNode(ID, Opcode, VTs, Ops);
  5546. void *IP = nullptr;
  5547. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  5548. E->intersectFlagsWith(Flags);
  5549. return SDValue(E, 0);
  5550. }
  5551. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  5552. N->setFlags(Flags);
  5553. createOperands(N, Ops);
  5554. CSEMap.InsertNode(N, IP);
  5555. } else {
  5556. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  5557. createOperands(N, Ops);
  5558. }
  5559. InsertNode(N);
  5560. SDValue V = SDValue(N, 0);
  5561. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5562. return V;
  5563. }
  5564. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  5565. SDValue N1, SDValue N2, SDValue N3) {
  5566. SDNodeFlags Flags;
  5567. if (Inserter)
  5568. Flags = Inserter->getFlags();
  5569. return getNode(Opcode, DL, VT, N1, N2, N3, Flags);
  5570. }
  5571. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  5572. SDValue N1, SDValue N2, SDValue N3,
  5573. const SDNodeFlags Flags) {
  5574. assert(N1.getOpcode() != ISD::DELETED_NODE &&
  5575. N2.getOpcode() != ISD::DELETED_NODE &&
  5576. N3.getOpcode() != ISD::DELETED_NODE &&
  5577. "Operand is DELETED_NODE!");
  5578. // Perform various simplifications.
  5579. switch (Opcode) {
  5580. case ISD::FMA: {
  5581. assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
  5582. assert(N1.getValueType() == VT && N2.getValueType() == VT &&
  5583. N3.getValueType() == VT && "FMA types must match!");
  5584. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  5585. ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  5586. ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
  5587. if (N1CFP && N2CFP && N3CFP) {
  5588. APFloat V1 = N1CFP->getValueAPF();
  5589. const APFloat &V2 = N2CFP->getValueAPF();
  5590. const APFloat &V3 = N3CFP->getValueAPF();
  5591. V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
  5592. return getConstantFP(V1, DL, VT);
  5593. }
  5594. break;
  5595. }
  5596. case ISD::BUILD_VECTOR: {
  5597. // Attempt to simplify BUILD_VECTOR.
  5598. SDValue Ops[] = {N1, N2, N3};
  5599. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  5600. return V;
  5601. break;
  5602. }
  5603. case ISD::CONCAT_VECTORS: {
  5604. SDValue Ops[] = {N1, N2, N3};
  5605. if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
  5606. return V;
  5607. break;
  5608. }
  5609. case ISD::SETCC: {
  5610. assert(VT.isInteger() && "SETCC result type must be an integer!");
  5611. assert(N1.getValueType() == N2.getValueType() &&
  5612. "SETCC operands must have the same type!");
  5613. assert(VT.isVector() == N1.getValueType().isVector() &&
  5614. "SETCC type should be vector iff the operand type is vector!");
  5615. assert((!VT.isVector() || VT.getVectorElementCount() ==
  5616. N1.getValueType().getVectorElementCount()) &&
  5617. "SETCC vector element counts must match!");
  5618. // Use FoldSetCC to simplify SETCC's.
  5619. if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
  5620. return V;
  5621. // Vector constant folding.
  5622. SDValue Ops[] = {N1, N2, N3};
  5623. if (SDValue V = FoldConstantArithmetic(Opcode, DL, VT, Ops)) {
  5624. NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
  5625. return V;
  5626. }
  5627. break;
  5628. }
  5629. case ISD::SELECT:
  5630. case ISD::VSELECT:
  5631. if (SDValue V = simplifySelect(N1, N2, N3))
  5632. return V;
  5633. break;
  5634. case ISD::VECTOR_SHUFFLE:
  5635. llvm_unreachable("should use getVectorShuffle constructor!");
  5636. case ISD::VECTOR_SPLICE: {
  5637. if (cast<ConstantSDNode>(N3)->isNullValue())
  5638. return N1;
  5639. break;
  5640. }
  5641. case ISD::INSERT_VECTOR_ELT: {
  5642. ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
  5643. // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
  5644. // for scalable vectors where we will generate appropriate code to
  5645. // deal with out-of-bounds cases correctly.
  5646. if (N3C && N1.getValueType().isFixedLengthVector() &&
  5647. N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
  5648. return getUNDEF(VT);
  5649. // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
  5650. if (N3.isUndef())
  5651. return getUNDEF(VT);
  5652. // If the inserted element is an UNDEF, just use the input vector.
  5653. if (N2.isUndef())
  5654. return N1;
  5655. break;
  5656. }
  5657. case ISD::INSERT_SUBVECTOR: {
  5658. // Inserting undef into undef is still undef.
  5659. if (N1.isUndef() && N2.isUndef())
  5660. return getUNDEF(VT);
  5661. EVT N2VT = N2.getValueType();
  5662. assert(VT == N1.getValueType() &&
  5663. "Dest and insert subvector source types must match!");
  5664. assert(VT.isVector() && N2VT.isVector() &&
  5665. "Insert subvector VTs must be vectors!");
  5666. assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
  5667. "Cannot insert a scalable vector into a fixed length vector!");
  5668. assert((VT.isScalableVector() != N2VT.isScalableVector() ||
  5669. VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
  5670. "Insert subvector must be from smaller vector to larger vector!");
  5671. assert(isa<ConstantSDNode>(N3) &&
  5672. "Insert subvector index must be constant");
  5673. assert((VT.isScalableVector() != N2VT.isScalableVector() ||
  5674. (N2VT.getVectorMinNumElements() +
  5675. cast<ConstantSDNode>(N3)->getZExtValue()) <=
  5676. VT.getVectorMinNumElements()) &&
  5677. "Insert subvector overflow!");
  5678. assert(cast<ConstantSDNode>(N3)->getAPIntValue().getBitWidth() ==
  5679. TLI->getVectorIdxTy(getDataLayout()).getFixedSizeInBits() &&
  5680. "Constant index for INSERT_SUBVECTOR has an invalid size");
  5681. // Trivial insertion.
  5682. if (VT == N2VT)
  5683. return N2;
  5684. // If this is an insert of an extracted vector into an undef vector, we
  5685. // can just use the input to the extract.
  5686. if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  5687. N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
  5688. return N2.getOperand(0);
  5689. break;
  5690. }
  5691. case ISD::BITCAST:
  5692. // Fold bit_convert nodes from a type to themselves.
  5693. if (N1.getValueType() == VT)
  5694. return N1;
  5695. break;
  5696. }
  5697. // Memoize node if it doesn't produce a flag.
  5698. SDNode *N;
  5699. SDVTList VTs = getVTList(VT);
  5700. SDValue Ops[] = {N1, N2, N3};
  5701. if (VT != MVT::Glue) {
  5702. FoldingSetNodeID ID;
  5703. AddNodeIDNode(ID, Opcode, VTs, Ops);
  5704. void *IP = nullptr;
  5705. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  5706. E->intersectFlagsWith(Flags);
  5707. return SDValue(E, 0);
  5708. }
  5709. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  5710. N->setFlags(Flags);
  5711. createOperands(N, Ops);
  5712. CSEMap.InsertNode(N, IP);
  5713. } else {
  5714. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  5715. createOperands(N, Ops);
  5716. }
  5717. InsertNode(N);
  5718. SDValue V = SDValue(N, 0);
  5719. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5720. return V;
  5721. }
  5722. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  5723. SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
  5724. SDValue Ops[] = { N1, N2, N3, N4 };
  5725. return getNode(Opcode, DL, VT, Ops);
  5726. }
  5727. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  5728. SDValue N1, SDValue N2, SDValue N3, SDValue N4,
  5729. SDValue N5) {
  5730. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  5731. return getNode(Opcode, DL, VT, Ops);
  5732. }
  5733. /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
  5734. /// the incoming stack arguments to be loaded from the stack.
  5735. SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
  5736. SmallVector<SDValue, 8> ArgChains;
  5737. // Include the original chain at the beginning of the list. When this is
  5738. // used by target LowerCall hooks, this helps legalize find the
  5739. // CALLSEQ_BEGIN node.
  5740. ArgChains.push_back(Chain);
  5741. // Add a chain value for each stack argument.
  5742. for (SDNode *U : getEntryNode().getNode()->uses())
  5743. if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
  5744. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
  5745. if (FI->getIndex() < 0)
  5746. ArgChains.push_back(SDValue(L, 1));
  5747. // Build a tokenfactor for all the chains.
  5748. return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
  5749. }
  5750. /// getMemsetValue - Vectorized representation of the memset value
  5751. /// operand.
  5752. static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
  5753. const SDLoc &dl) {
  5754. assert(!Value.isUndef());
  5755. unsigned NumBits = VT.getScalarSizeInBits();
  5756. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
  5757. assert(C->getAPIntValue().getBitWidth() == 8);
  5758. APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
  5759. if (VT.isInteger()) {
  5760. bool IsOpaque = VT.getSizeInBits() > 64 ||
  5761. !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
  5762. return DAG.getConstant(Val, dl, VT, false, IsOpaque);
  5763. }
  5764. return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
  5765. VT);
  5766. }
  5767. assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
  5768. EVT IntVT = VT.getScalarType();
  5769. if (!IntVT.isInteger())
  5770. IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
  5771. Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
  5772. if (NumBits > 8) {
  5773. // Use a multiplication with 0x010101... to extend the input to the
  5774. // required length.
  5775. APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
  5776. Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
  5777. DAG.getConstant(Magic, dl, IntVT));
  5778. }
  5779. if (VT != Value.getValueType() && !VT.isInteger())
  5780. Value = DAG.getBitcast(VT.getScalarType(), Value);
  5781. if (VT != Value.getValueType())
  5782. Value = DAG.getSplatBuildVector(VT, dl, Value);
  5783. return Value;
  5784. }
  5785. /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
  5786. /// used when a memcpy is turned into a memset when the source is a constant
  5787. /// string ptr.
  5788. static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
  5789. const TargetLowering &TLI,
  5790. const ConstantDataArraySlice &Slice) {
  5791. // Handle vector with all elements zero.
  5792. if (Slice.Array == nullptr) {
  5793. if (VT.isInteger())
  5794. return DAG.getConstant(0, dl, VT);
  5795. if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
  5796. return DAG.getConstantFP(0.0, dl, VT);
  5797. if (VT.isVector()) {
  5798. unsigned NumElts = VT.getVectorNumElements();
  5799. MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
  5800. return DAG.getNode(ISD::BITCAST, dl, VT,
  5801. DAG.getConstant(0, dl,
  5802. EVT::getVectorVT(*DAG.getContext(),
  5803. EltVT, NumElts)));
  5804. }
  5805. llvm_unreachable("Expected type!");
  5806. }
  5807. assert(!VT.isVector() && "Can't handle vector type here!");
  5808. unsigned NumVTBits = VT.getSizeInBits();
  5809. unsigned NumVTBytes = NumVTBits / 8;
  5810. unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
  5811. APInt Val(NumVTBits, 0);
  5812. if (DAG.getDataLayout().isLittleEndian()) {
  5813. for (unsigned i = 0; i != NumBytes; ++i)
  5814. Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
  5815. } else {
  5816. for (unsigned i = 0; i != NumBytes; ++i)
  5817. Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
  5818. }
  5819. // If the "cost" of materializing the integer immediate is less than the cost
  5820. // of a load, then it is cost effective to turn the load into the immediate.
  5821. Type *Ty = VT.getTypeForEVT(*DAG.getContext());
  5822. if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
  5823. return DAG.getConstant(Val, dl, VT);
  5824. return SDValue();
  5825. }
  5826. SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, TypeSize Offset,
  5827. const SDLoc &DL,
  5828. const SDNodeFlags Flags) {
  5829. EVT VT = Base.getValueType();
  5830. SDValue Index;
  5831. if (Offset.isScalable())
  5832. Index = getVScale(DL, Base.getValueType(),
  5833. APInt(Base.getValueSizeInBits().getFixedSize(),
  5834. Offset.getKnownMinSize()));
  5835. else
  5836. Index = getConstant(Offset.getFixedSize(), DL, VT);
  5837. return getMemBasePlusOffset(Base, Index, DL, Flags);
  5838. }
  5839. SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
  5840. const SDLoc &DL,
  5841. const SDNodeFlags Flags) {
  5842. assert(Offset.getValueType().isInteger());
  5843. EVT BasePtrVT = Ptr.getValueType();
  5844. return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
  5845. }
  5846. /// Returns true if memcpy source is constant data.
  5847. static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
  5848. uint64_t SrcDelta = 0;
  5849. GlobalAddressSDNode *G = nullptr;
  5850. if (Src.getOpcode() == ISD::GlobalAddress)
  5851. G = cast<GlobalAddressSDNode>(Src);
  5852. else if (Src.getOpcode() == ISD::ADD &&
  5853. Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
  5854. Src.getOperand(1).getOpcode() == ISD::Constant) {
  5855. G = cast<GlobalAddressSDNode>(Src.getOperand(0));
  5856. SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
  5857. }
  5858. if (!G)
  5859. return false;
  5860. return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
  5861. SrcDelta + G->getOffset());
  5862. }
  5863. static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
  5864. SelectionDAG &DAG) {
  5865. // On Darwin, -Os means optimize for size without hurting performance, so
  5866. // only really optimize for size when -Oz (MinSize) is used.
  5867. if (MF.getTarget().getTargetTriple().isOSDarwin())
  5868. return MF.getFunction().hasMinSize();
  5869. return DAG.shouldOptForSize();
  5870. }
  5871. static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
  5872. SmallVector<SDValue, 32> &OutChains, unsigned From,
  5873. unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
  5874. SmallVector<SDValue, 16> &OutStoreChains) {
  5875. assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
  5876. assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
  5877. SmallVector<SDValue, 16> GluedLoadChains;
  5878. for (unsigned i = From; i < To; ++i) {
  5879. OutChains.push_back(OutLoadChains[i]);
  5880. GluedLoadChains.push_back(OutLoadChains[i]);
  5881. }
  5882. // Chain for all loads.
  5883. SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  5884. GluedLoadChains);
  5885. for (unsigned i = From; i < To; ++i) {
  5886. StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
  5887. SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
  5888. ST->getBasePtr(), ST->getMemoryVT(),
  5889. ST->getMemOperand());
  5890. OutChains.push_back(NewStore);
  5891. }
  5892. }
  5893. static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
  5894. SDValue Chain, SDValue Dst, SDValue Src,
  5895. uint64_t Size, Align Alignment,
  5896. bool isVol, bool AlwaysInline,
  5897. MachinePointerInfo DstPtrInfo,
  5898. MachinePointerInfo SrcPtrInfo,
  5899. const AAMDNodes &AAInfo) {
  5900. // Turn a memcpy of undef to nop.
  5901. // FIXME: We need to honor volatile even is Src is undef.
  5902. if (Src.isUndef())
  5903. return Chain;
  5904. // Expand memcpy to a series of load and store ops if the size operand falls
  5905. // below a certain threshold.
  5906. // TODO: In the AlwaysInline case, if the size is big then generate a loop
  5907. // rather than maybe a humongous number of loads and stores.
  5908. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5909. const DataLayout &DL = DAG.getDataLayout();
  5910. LLVMContext &C = *DAG.getContext();
  5911. std::vector<EVT> MemOps;
  5912. bool DstAlignCanChange = false;
  5913. MachineFunction &MF = DAG.getMachineFunction();
  5914. MachineFrameInfo &MFI = MF.getFrameInfo();
  5915. bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
  5916. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  5917. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  5918. DstAlignCanChange = true;
  5919. MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
  5920. if (!SrcAlign || Alignment > *SrcAlign)
  5921. SrcAlign = Alignment;
  5922. assert(SrcAlign && "SrcAlign must be set");
  5923. ConstantDataArraySlice Slice;
  5924. // If marked as volatile, perform a copy even when marked as constant.
  5925. bool CopyFromConstant = !isVol && isMemSrcFromConstant(Src, Slice);
  5926. bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
  5927. unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
  5928. const MemOp Op = isZeroConstant
  5929. ? MemOp::Set(Size, DstAlignCanChange, Alignment,
  5930. /*IsZeroMemset*/ true, isVol)
  5931. : MemOp::Copy(Size, DstAlignCanChange, Alignment,
  5932. *SrcAlign, isVol, CopyFromConstant);
  5933. if (!TLI.findOptimalMemOpLowering(
  5934. MemOps, Limit, Op, DstPtrInfo.getAddrSpace(),
  5935. SrcPtrInfo.getAddrSpace(), MF.getFunction().getAttributes()))
  5936. return SDValue();
  5937. if (DstAlignCanChange) {
  5938. Type *Ty = MemOps[0].getTypeForEVT(C);
  5939. Align NewAlign = DL.getABITypeAlign(Ty);
  5940. // Don't promote to an alignment that would require dynamic stack
  5941. // realignment.
  5942. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  5943. if (!TRI->hasStackRealignment(MF))
  5944. while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
  5945. NewAlign = NewAlign / 2;
  5946. if (NewAlign > Alignment) {
  5947. // Give the stack frame object a larger alignment if needed.
  5948. if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
  5949. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  5950. Alignment = NewAlign;
  5951. }
  5952. }
  5953. // Prepare AAInfo for loads/stores after lowering this memcpy.
  5954. AAMDNodes NewAAInfo = AAInfo;
  5955. NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
  5956. MachineMemOperand::Flags MMOFlags =
  5957. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  5958. SmallVector<SDValue, 16> OutLoadChains;
  5959. SmallVector<SDValue, 16> OutStoreChains;
  5960. SmallVector<SDValue, 32> OutChains;
  5961. unsigned NumMemOps = MemOps.size();
  5962. uint64_t SrcOff = 0, DstOff = 0;
  5963. for (unsigned i = 0; i != NumMemOps; ++i) {
  5964. EVT VT = MemOps[i];
  5965. unsigned VTSize = VT.getSizeInBits() / 8;
  5966. SDValue Value, Store;
  5967. if (VTSize > Size) {
  5968. // Issuing an unaligned load / store pair that overlaps with the previous
  5969. // pair. Adjust the offset accordingly.
  5970. assert(i == NumMemOps-1 && i != 0);
  5971. SrcOff -= VTSize - Size;
  5972. DstOff -= VTSize - Size;
  5973. }
  5974. if (CopyFromConstant &&
  5975. (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
  5976. // It's unlikely a store of a vector immediate can be done in a single
  5977. // instruction. It would require a load from a constantpool first.
  5978. // We only handle zero vectors here.
  5979. // FIXME: Handle other cases where store of vector immediate is done in
  5980. // a single instruction.
  5981. ConstantDataArraySlice SubSlice;
  5982. if (SrcOff < Slice.Length) {
  5983. SubSlice = Slice;
  5984. SubSlice.move(SrcOff);
  5985. } else {
  5986. // This is an out-of-bounds access and hence UB. Pretend we read zero.
  5987. SubSlice.Array = nullptr;
  5988. SubSlice.Offset = 0;
  5989. SubSlice.Length = VTSize;
  5990. }
  5991. Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
  5992. if (Value.getNode()) {
  5993. Store = DAG.getStore(
  5994. Chain, dl, Value,
  5995. DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
  5996. DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
  5997. OutChains.push_back(Store);
  5998. }
  5999. }
  6000. if (!Store.getNode()) {
  6001. // The type might not be legal for the target. This should only happen
  6002. // if the type is smaller than a legal type, as on PPC, so the right
  6003. // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
  6004. // to Load/Store if NVT==VT.
  6005. // FIXME does the case above also need this?
  6006. EVT NVT = TLI.getTypeToTransformTo(C, VT);
  6007. assert(NVT.bitsGE(VT));
  6008. bool isDereferenceable =
  6009. SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
  6010. MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
  6011. if (isDereferenceable)
  6012. SrcMMOFlags |= MachineMemOperand::MODereferenceable;
  6013. Value = DAG.getExtLoad(
  6014. ISD::EXTLOAD, dl, NVT, Chain,
  6015. DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
  6016. SrcPtrInfo.getWithOffset(SrcOff), VT,
  6017. commonAlignment(*SrcAlign, SrcOff), SrcMMOFlags, NewAAInfo);
  6018. OutLoadChains.push_back(Value.getValue(1));
  6019. Store = DAG.getTruncStore(
  6020. Chain, dl, Value,
  6021. DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
  6022. DstPtrInfo.getWithOffset(DstOff), VT, Alignment, MMOFlags, NewAAInfo);
  6023. OutStoreChains.push_back(Store);
  6024. }
  6025. SrcOff += VTSize;
  6026. DstOff += VTSize;
  6027. Size -= VTSize;
  6028. }
  6029. unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
  6030. TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
  6031. unsigned NumLdStInMemcpy = OutStoreChains.size();
  6032. if (NumLdStInMemcpy) {
  6033. // It may be that memcpy might be converted to memset if it's memcpy
  6034. // of constants. In such a case, we won't have loads and stores, but
  6035. // just stores. In the absence of loads, there is nothing to gang up.
  6036. if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
  6037. // If target does not care, just leave as it.
  6038. for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
  6039. OutChains.push_back(OutLoadChains[i]);
  6040. OutChains.push_back(OutStoreChains[i]);
  6041. }
  6042. } else {
  6043. // Ld/St less than/equal limit set by target.
  6044. if (NumLdStInMemcpy <= GluedLdStLimit) {
  6045. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
  6046. NumLdStInMemcpy, OutLoadChains,
  6047. OutStoreChains);
  6048. } else {
  6049. unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
  6050. unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
  6051. unsigned GlueIter = 0;
  6052. for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
  6053. unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
  6054. unsigned IndexTo = NumLdStInMemcpy - GlueIter;
  6055. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
  6056. OutLoadChains, OutStoreChains);
  6057. GlueIter += GluedLdStLimit;
  6058. }
  6059. // Residual ld/st.
  6060. if (RemainingLdStInMemcpy) {
  6061. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
  6062. RemainingLdStInMemcpy, OutLoadChains,
  6063. OutStoreChains);
  6064. }
  6065. }
  6066. }
  6067. }
  6068. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  6069. }
  6070. static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
  6071. SDValue Chain, SDValue Dst, SDValue Src,
  6072. uint64_t Size, Align Alignment,
  6073. bool isVol, bool AlwaysInline,
  6074. MachinePointerInfo DstPtrInfo,
  6075. MachinePointerInfo SrcPtrInfo,
  6076. const AAMDNodes &AAInfo) {
  6077. // Turn a memmove of undef to nop.
  6078. // FIXME: We need to honor volatile even is Src is undef.
  6079. if (Src.isUndef())
  6080. return Chain;
  6081. // Expand memmove to a series of load and store ops if the size operand falls
  6082. // below a certain threshold.
  6083. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6084. const DataLayout &DL = DAG.getDataLayout();
  6085. LLVMContext &C = *DAG.getContext();
  6086. std::vector<EVT> MemOps;
  6087. bool DstAlignCanChange = false;
  6088. MachineFunction &MF = DAG.getMachineFunction();
  6089. MachineFrameInfo &MFI = MF.getFrameInfo();
  6090. bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
  6091. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  6092. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  6093. DstAlignCanChange = true;
  6094. MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
  6095. if (!SrcAlign || Alignment > *SrcAlign)
  6096. SrcAlign = Alignment;
  6097. assert(SrcAlign && "SrcAlign must be set");
  6098. unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
  6099. if (!TLI.findOptimalMemOpLowering(
  6100. MemOps, Limit,
  6101. MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
  6102. /*IsVolatile*/ true),
  6103. DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
  6104. MF.getFunction().getAttributes()))
  6105. return SDValue();
  6106. if (DstAlignCanChange) {
  6107. Type *Ty = MemOps[0].getTypeForEVT(C);
  6108. Align NewAlign = DL.getABITypeAlign(Ty);
  6109. if (NewAlign > Alignment) {
  6110. // Give the stack frame object a larger alignment if needed.
  6111. if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
  6112. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  6113. Alignment = NewAlign;
  6114. }
  6115. }
  6116. // Prepare AAInfo for loads/stores after lowering this memmove.
  6117. AAMDNodes NewAAInfo = AAInfo;
  6118. NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
  6119. MachineMemOperand::Flags MMOFlags =
  6120. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  6121. uint64_t SrcOff = 0, DstOff = 0;
  6122. SmallVector<SDValue, 8> LoadValues;
  6123. SmallVector<SDValue, 8> LoadChains;
  6124. SmallVector<SDValue, 8> OutChains;
  6125. unsigned NumMemOps = MemOps.size();
  6126. for (unsigned i = 0; i < NumMemOps; i++) {
  6127. EVT VT = MemOps[i];
  6128. unsigned VTSize = VT.getSizeInBits() / 8;
  6129. SDValue Value;
  6130. bool isDereferenceable =
  6131. SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
  6132. MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
  6133. if (isDereferenceable)
  6134. SrcMMOFlags |= MachineMemOperand::MODereferenceable;
  6135. Value = DAG.getLoad(
  6136. VT, dl, Chain,
  6137. DAG.getMemBasePlusOffset(Src, TypeSize::Fixed(SrcOff), dl),
  6138. SrcPtrInfo.getWithOffset(SrcOff), *SrcAlign, SrcMMOFlags, NewAAInfo);
  6139. LoadValues.push_back(Value);
  6140. LoadChains.push_back(Value.getValue(1));
  6141. SrcOff += VTSize;
  6142. }
  6143. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
  6144. OutChains.clear();
  6145. for (unsigned i = 0; i < NumMemOps; i++) {
  6146. EVT VT = MemOps[i];
  6147. unsigned VTSize = VT.getSizeInBits() / 8;
  6148. SDValue Store;
  6149. Store = DAG.getStore(
  6150. Chain, dl, LoadValues[i],
  6151. DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
  6152. DstPtrInfo.getWithOffset(DstOff), Alignment, MMOFlags, NewAAInfo);
  6153. OutChains.push_back(Store);
  6154. DstOff += VTSize;
  6155. }
  6156. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  6157. }
  6158. /// Lower the call to 'memset' intrinsic function into a series of store
  6159. /// operations.
  6160. ///
  6161. /// \param DAG Selection DAG where lowered code is placed.
  6162. /// \param dl Link to corresponding IR location.
  6163. /// \param Chain Control flow dependency.
  6164. /// \param Dst Pointer to destination memory location.
  6165. /// \param Src Value of byte to write into the memory.
  6166. /// \param Size Number of bytes to write.
  6167. /// \param Alignment Alignment of the destination in bytes.
  6168. /// \param isVol True if destination is volatile.
  6169. /// \param DstPtrInfo IR information on the memory pointer.
  6170. /// \returns New head in the control flow, if lowering was successful, empty
  6171. /// SDValue otherwise.
  6172. ///
  6173. /// The function tries to replace 'llvm.memset' intrinsic with several store
  6174. /// operations and value calculation code. This is usually profitable for small
  6175. /// memory size.
  6176. static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
  6177. SDValue Chain, SDValue Dst, SDValue Src,
  6178. uint64_t Size, Align Alignment, bool isVol,
  6179. MachinePointerInfo DstPtrInfo,
  6180. const AAMDNodes &AAInfo) {
  6181. // Turn a memset of undef to nop.
  6182. // FIXME: We need to honor volatile even is Src is undef.
  6183. if (Src.isUndef())
  6184. return Chain;
  6185. // Expand memset to a series of load/store ops if the size operand
  6186. // falls below a certain threshold.
  6187. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6188. std::vector<EVT> MemOps;
  6189. bool DstAlignCanChange = false;
  6190. MachineFunction &MF = DAG.getMachineFunction();
  6191. MachineFrameInfo &MFI = MF.getFrameInfo();
  6192. bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
  6193. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  6194. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  6195. DstAlignCanChange = true;
  6196. bool IsZeroVal =
  6197. isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isZero();
  6198. if (!TLI.findOptimalMemOpLowering(
  6199. MemOps, TLI.getMaxStoresPerMemset(OptSize),
  6200. MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
  6201. DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
  6202. return SDValue();
  6203. if (DstAlignCanChange) {
  6204. Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
  6205. Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
  6206. if (NewAlign > Alignment) {
  6207. // Give the stack frame object a larger alignment if needed.
  6208. if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
  6209. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  6210. Alignment = NewAlign;
  6211. }
  6212. }
  6213. SmallVector<SDValue, 8> OutChains;
  6214. uint64_t DstOff = 0;
  6215. unsigned NumMemOps = MemOps.size();
  6216. // Find the largest store and generate the bit pattern for it.
  6217. EVT LargestVT = MemOps[0];
  6218. for (unsigned i = 1; i < NumMemOps; i++)
  6219. if (MemOps[i].bitsGT(LargestVT))
  6220. LargestVT = MemOps[i];
  6221. SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
  6222. // Prepare AAInfo for loads/stores after lowering this memset.
  6223. AAMDNodes NewAAInfo = AAInfo;
  6224. NewAAInfo.TBAA = NewAAInfo.TBAAStruct = nullptr;
  6225. for (unsigned i = 0; i < NumMemOps; i++) {
  6226. EVT VT = MemOps[i];
  6227. unsigned VTSize = VT.getSizeInBits() / 8;
  6228. if (VTSize > Size) {
  6229. // Issuing an unaligned load / store pair that overlaps with the previous
  6230. // pair. Adjust the offset accordingly.
  6231. assert(i == NumMemOps-1 && i != 0);
  6232. DstOff -= VTSize - Size;
  6233. }
  6234. // If this store is smaller than the largest store see whether we can get
  6235. // the smaller value for free with a truncate.
  6236. SDValue Value = MemSetValue;
  6237. if (VT.bitsLT(LargestVT)) {
  6238. if (!LargestVT.isVector() && !VT.isVector() &&
  6239. TLI.isTruncateFree(LargestVT, VT))
  6240. Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
  6241. else
  6242. Value = getMemsetValue(Src, VT, DAG, dl);
  6243. }
  6244. assert(Value.getValueType() == VT && "Value with wrong type.");
  6245. SDValue Store = DAG.getStore(
  6246. Chain, dl, Value,
  6247. DAG.getMemBasePlusOffset(Dst, TypeSize::Fixed(DstOff), dl),
  6248. DstPtrInfo.getWithOffset(DstOff), Alignment,
  6249. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone,
  6250. NewAAInfo);
  6251. OutChains.push_back(Store);
  6252. DstOff += VT.getSizeInBits() / 8;
  6253. Size -= VTSize;
  6254. }
  6255. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  6256. }
  6257. static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
  6258. unsigned AS) {
  6259. // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
  6260. // pointer operands can be losslessly bitcasted to pointers of address space 0
  6261. if (AS != 0 && !TLI->getTargetMachine().isNoopAddrSpaceCast(AS, 0)) {
  6262. report_fatal_error("cannot lower memory intrinsic in address space " +
  6263. Twine(AS));
  6264. }
  6265. }
  6266. SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
  6267. SDValue Src, SDValue Size, Align Alignment,
  6268. bool isVol, bool AlwaysInline, bool isTailCall,
  6269. MachinePointerInfo DstPtrInfo,
  6270. MachinePointerInfo SrcPtrInfo,
  6271. const AAMDNodes &AAInfo) {
  6272. // Check to see if we should lower the memcpy to loads and stores first.
  6273. // For cases within the target-specified limits, this is the best choice.
  6274. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  6275. if (ConstantSize) {
  6276. // Memcpy with size zero? Just return the original chain.
  6277. if (ConstantSize->isZero())
  6278. return Chain;
  6279. SDValue Result = getMemcpyLoadsAndStores(
  6280. *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
  6281. isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
  6282. if (Result.getNode())
  6283. return Result;
  6284. }
  6285. // Then check to see if we should lower the memcpy with target-specific
  6286. // code. If the target chooses to do this, this is the next best.
  6287. if (TSI) {
  6288. SDValue Result = TSI->EmitTargetCodeForMemcpy(
  6289. *this, dl, Chain, Dst, Src, Size, Alignment, isVol, AlwaysInline,
  6290. DstPtrInfo, SrcPtrInfo);
  6291. if (Result.getNode())
  6292. return Result;
  6293. }
  6294. // If we really need inline code and the target declined to provide it,
  6295. // use a (potentially long) sequence of loads and stores.
  6296. if (AlwaysInline) {
  6297. assert(ConstantSize && "AlwaysInline requires a constant size!");
  6298. return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
  6299. ConstantSize->getZExtValue(), Alignment,
  6300. isVol, true, DstPtrInfo, SrcPtrInfo, AAInfo);
  6301. }
  6302. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  6303. checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
  6304. // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
  6305. // memcpy is not guaranteed to be safe. libc memcpys aren't required to
  6306. // respect volatile, so they may do things like read or write memory
  6307. // beyond the given memory regions. But fixing this isn't easy, and most
  6308. // people don't care.
  6309. // Emit a library call.
  6310. TargetLowering::ArgListTy Args;
  6311. TargetLowering::ArgListEntry Entry;
  6312. Entry.Ty = Type::getInt8PtrTy(*getContext());
  6313. Entry.Node = Dst; Args.push_back(Entry);
  6314. Entry.Node = Src; Args.push_back(Entry);
  6315. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6316. Entry.Node = Size; Args.push_back(Entry);
  6317. // FIXME: pass in SDLoc
  6318. TargetLowering::CallLoweringInfo CLI(*this);
  6319. CLI.setDebugLoc(dl)
  6320. .setChain(Chain)
  6321. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
  6322. Dst.getValueType().getTypeForEVT(*getContext()),
  6323. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
  6324. TLI->getPointerTy(getDataLayout())),
  6325. std::move(Args))
  6326. .setDiscardResult()
  6327. .setTailCall(isTailCall);
  6328. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  6329. return CallResult.second;
  6330. }
  6331. SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
  6332. SDValue Dst, unsigned DstAlign,
  6333. SDValue Src, unsigned SrcAlign,
  6334. SDValue Size, Type *SizeTy,
  6335. unsigned ElemSz, bool isTailCall,
  6336. MachinePointerInfo DstPtrInfo,
  6337. MachinePointerInfo SrcPtrInfo) {
  6338. // Emit a library call.
  6339. TargetLowering::ArgListTy Args;
  6340. TargetLowering::ArgListEntry Entry;
  6341. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6342. Entry.Node = Dst;
  6343. Args.push_back(Entry);
  6344. Entry.Node = Src;
  6345. Args.push_back(Entry);
  6346. Entry.Ty = SizeTy;
  6347. Entry.Node = Size;
  6348. Args.push_back(Entry);
  6349. RTLIB::Libcall LibraryCall =
  6350. RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  6351. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  6352. report_fatal_error("Unsupported element size");
  6353. TargetLowering::CallLoweringInfo CLI(*this);
  6354. CLI.setDebugLoc(dl)
  6355. .setChain(Chain)
  6356. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  6357. Type::getVoidTy(*getContext()),
  6358. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  6359. TLI->getPointerTy(getDataLayout())),
  6360. std::move(Args))
  6361. .setDiscardResult()
  6362. .setTailCall(isTailCall);
  6363. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  6364. return CallResult.second;
  6365. }
  6366. SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
  6367. SDValue Src, SDValue Size, Align Alignment,
  6368. bool isVol, bool isTailCall,
  6369. MachinePointerInfo DstPtrInfo,
  6370. MachinePointerInfo SrcPtrInfo,
  6371. const AAMDNodes &AAInfo) {
  6372. // Check to see if we should lower the memmove to loads and stores first.
  6373. // For cases within the target-specified limits, this is the best choice.
  6374. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  6375. if (ConstantSize) {
  6376. // Memmove with size zero? Just return the original chain.
  6377. if (ConstantSize->isZero())
  6378. return Chain;
  6379. SDValue Result = getMemmoveLoadsAndStores(
  6380. *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
  6381. isVol, false, DstPtrInfo, SrcPtrInfo, AAInfo);
  6382. if (Result.getNode())
  6383. return Result;
  6384. }
  6385. // Then check to see if we should lower the memmove with target-specific
  6386. // code. If the target chooses to do this, this is the next best.
  6387. if (TSI) {
  6388. SDValue Result =
  6389. TSI->EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size,
  6390. Alignment, isVol, DstPtrInfo, SrcPtrInfo);
  6391. if (Result.getNode())
  6392. return Result;
  6393. }
  6394. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  6395. checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
  6396. // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
  6397. // not be safe. See memcpy above for more details.
  6398. // Emit a library call.
  6399. TargetLowering::ArgListTy Args;
  6400. TargetLowering::ArgListEntry Entry;
  6401. Entry.Ty = Type::getInt8PtrTy(*getContext());
  6402. Entry.Node = Dst; Args.push_back(Entry);
  6403. Entry.Node = Src; Args.push_back(Entry);
  6404. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6405. Entry.Node = Size; Args.push_back(Entry);
  6406. // FIXME: pass in SDLoc
  6407. TargetLowering::CallLoweringInfo CLI(*this);
  6408. CLI.setDebugLoc(dl)
  6409. .setChain(Chain)
  6410. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
  6411. Dst.getValueType().getTypeForEVT(*getContext()),
  6412. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
  6413. TLI->getPointerTy(getDataLayout())),
  6414. std::move(Args))
  6415. .setDiscardResult()
  6416. .setTailCall(isTailCall);
  6417. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  6418. return CallResult.second;
  6419. }
  6420. SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
  6421. SDValue Dst, unsigned DstAlign,
  6422. SDValue Src, unsigned SrcAlign,
  6423. SDValue Size, Type *SizeTy,
  6424. unsigned ElemSz, bool isTailCall,
  6425. MachinePointerInfo DstPtrInfo,
  6426. MachinePointerInfo SrcPtrInfo) {
  6427. // Emit a library call.
  6428. TargetLowering::ArgListTy Args;
  6429. TargetLowering::ArgListEntry Entry;
  6430. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6431. Entry.Node = Dst;
  6432. Args.push_back(Entry);
  6433. Entry.Node = Src;
  6434. Args.push_back(Entry);
  6435. Entry.Ty = SizeTy;
  6436. Entry.Node = Size;
  6437. Args.push_back(Entry);
  6438. RTLIB::Libcall LibraryCall =
  6439. RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  6440. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  6441. report_fatal_error("Unsupported element size");
  6442. TargetLowering::CallLoweringInfo CLI(*this);
  6443. CLI.setDebugLoc(dl)
  6444. .setChain(Chain)
  6445. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  6446. Type::getVoidTy(*getContext()),
  6447. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  6448. TLI->getPointerTy(getDataLayout())),
  6449. std::move(Args))
  6450. .setDiscardResult()
  6451. .setTailCall(isTailCall);
  6452. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  6453. return CallResult.second;
  6454. }
  6455. SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
  6456. SDValue Src, SDValue Size, Align Alignment,
  6457. bool isVol, bool isTailCall,
  6458. MachinePointerInfo DstPtrInfo,
  6459. const AAMDNodes &AAInfo) {
  6460. // Check to see if we should lower the memset to stores first.
  6461. // For cases within the target-specified limits, this is the best choice.
  6462. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  6463. if (ConstantSize) {
  6464. // Memset with size zero? Just return the original chain.
  6465. if (ConstantSize->isZero())
  6466. return Chain;
  6467. SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
  6468. ConstantSize->getZExtValue(), Alignment,
  6469. isVol, DstPtrInfo, AAInfo);
  6470. if (Result.getNode())
  6471. return Result;
  6472. }
  6473. // Then check to see if we should lower the memset with target-specific
  6474. // code. If the target chooses to do this, this is the next best.
  6475. if (TSI) {
  6476. SDValue Result = TSI->EmitTargetCodeForMemset(
  6477. *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
  6478. if (Result.getNode())
  6479. return Result;
  6480. }
  6481. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  6482. // Emit a library call.
  6483. TargetLowering::ArgListTy Args;
  6484. TargetLowering::ArgListEntry Entry;
  6485. Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
  6486. Args.push_back(Entry);
  6487. Entry.Node = Src;
  6488. Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
  6489. Args.push_back(Entry);
  6490. Entry.Node = Size;
  6491. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6492. Args.push_back(Entry);
  6493. // FIXME: pass in SDLoc
  6494. TargetLowering::CallLoweringInfo CLI(*this);
  6495. CLI.setDebugLoc(dl)
  6496. .setChain(Chain)
  6497. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
  6498. Dst.getValueType().getTypeForEVT(*getContext()),
  6499. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
  6500. TLI->getPointerTy(getDataLayout())),
  6501. std::move(Args))
  6502. .setDiscardResult()
  6503. .setTailCall(isTailCall);
  6504. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  6505. return CallResult.second;
  6506. }
  6507. SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
  6508. SDValue Dst, unsigned DstAlign,
  6509. SDValue Value, SDValue Size, Type *SizeTy,
  6510. unsigned ElemSz, bool isTailCall,
  6511. MachinePointerInfo DstPtrInfo) {
  6512. // Emit a library call.
  6513. TargetLowering::ArgListTy Args;
  6514. TargetLowering::ArgListEntry Entry;
  6515. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  6516. Entry.Node = Dst;
  6517. Args.push_back(Entry);
  6518. Entry.Ty = Type::getInt8Ty(*getContext());
  6519. Entry.Node = Value;
  6520. Args.push_back(Entry);
  6521. Entry.Ty = SizeTy;
  6522. Entry.Node = Size;
  6523. Args.push_back(Entry);
  6524. RTLIB::Libcall LibraryCall =
  6525. RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  6526. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  6527. report_fatal_error("Unsupported element size");
  6528. TargetLowering::CallLoweringInfo CLI(*this);
  6529. CLI.setDebugLoc(dl)
  6530. .setChain(Chain)
  6531. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  6532. Type::getVoidTy(*getContext()),
  6533. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  6534. TLI->getPointerTy(getDataLayout())),
  6535. std::move(Args))
  6536. .setDiscardResult()
  6537. .setTailCall(isTailCall);
  6538. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  6539. return CallResult.second;
  6540. }
  6541. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  6542. SDVTList VTList, ArrayRef<SDValue> Ops,
  6543. MachineMemOperand *MMO) {
  6544. FoldingSetNodeID ID;
  6545. ID.AddInteger(MemVT.getRawBits());
  6546. AddNodeIDNode(ID, Opcode, VTList, Ops);
  6547. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6548. void* IP = nullptr;
  6549. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6550. cast<AtomicSDNode>(E)->refineAlignment(MMO);
  6551. return SDValue(E, 0);
  6552. }
  6553. auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  6554. VTList, MemVT, MMO);
  6555. createOperands(N, Ops);
  6556. CSEMap.InsertNode(N, IP);
  6557. InsertNode(N);
  6558. return SDValue(N, 0);
  6559. }
  6560. SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
  6561. EVT MemVT, SDVTList VTs, SDValue Chain,
  6562. SDValue Ptr, SDValue Cmp, SDValue Swp,
  6563. MachineMemOperand *MMO) {
  6564. assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
  6565. Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
  6566. assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
  6567. SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
  6568. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  6569. }
  6570. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  6571. SDValue Chain, SDValue Ptr, SDValue Val,
  6572. MachineMemOperand *MMO) {
  6573. assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
  6574. Opcode == ISD::ATOMIC_LOAD_SUB ||
  6575. Opcode == ISD::ATOMIC_LOAD_AND ||
  6576. Opcode == ISD::ATOMIC_LOAD_CLR ||
  6577. Opcode == ISD::ATOMIC_LOAD_OR ||
  6578. Opcode == ISD::ATOMIC_LOAD_XOR ||
  6579. Opcode == ISD::ATOMIC_LOAD_NAND ||
  6580. Opcode == ISD::ATOMIC_LOAD_MIN ||
  6581. Opcode == ISD::ATOMIC_LOAD_MAX ||
  6582. Opcode == ISD::ATOMIC_LOAD_UMIN ||
  6583. Opcode == ISD::ATOMIC_LOAD_UMAX ||
  6584. Opcode == ISD::ATOMIC_LOAD_FADD ||
  6585. Opcode == ISD::ATOMIC_LOAD_FSUB ||
  6586. Opcode == ISD::ATOMIC_SWAP ||
  6587. Opcode == ISD::ATOMIC_STORE) &&
  6588. "Invalid Atomic Op");
  6589. EVT VT = Val.getValueType();
  6590. SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
  6591. getVTList(VT, MVT::Other);
  6592. SDValue Ops[] = {Chain, Ptr, Val};
  6593. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  6594. }
  6595. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  6596. EVT VT, SDValue Chain, SDValue Ptr,
  6597. MachineMemOperand *MMO) {
  6598. assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
  6599. SDVTList VTs = getVTList(VT, MVT::Other);
  6600. SDValue Ops[] = {Chain, Ptr};
  6601. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  6602. }
  6603. /// getMergeValues - Create a MERGE_VALUES node from the given operands.
  6604. SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
  6605. if (Ops.size() == 1)
  6606. return Ops[0];
  6607. SmallVector<EVT, 4> VTs;
  6608. VTs.reserve(Ops.size());
  6609. for (const SDValue &Op : Ops)
  6610. VTs.push_back(Op.getValueType());
  6611. return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
  6612. }
  6613. SDValue SelectionDAG::getMemIntrinsicNode(
  6614. unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
  6615. EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
  6616. MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
  6617. if (!Size && MemVT.isScalableVector())
  6618. Size = MemoryLocation::UnknownSize;
  6619. else if (!Size)
  6620. Size = MemVT.getStoreSize();
  6621. MachineFunction &MF = getMachineFunction();
  6622. MachineMemOperand *MMO =
  6623. MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
  6624. return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
  6625. }
  6626. SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
  6627. SDVTList VTList,
  6628. ArrayRef<SDValue> Ops, EVT MemVT,
  6629. MachineMemOperand *MMO) {
  6630. assert((Opcode == ISD::INTRINSIC_VOID ||
  6631. Opcode == ISD::INTRINSIC_W_CHAIN ||
  6632. Opcode == ISD::PREFETCH ||
  6633. ((int)Opcode <= std::numeric_limits<int>::max() &&
  6634. (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
  6635. "Opcode is not a memory-accessing opcode!");
  6636. // Memoize the node unless it returns a flag.
  6637. MemIntrinsicSDNode *N;
  6638. if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
  6639. FoldingSetNodeID ID;
  6640. AddNodeIDNode(ID, Opcode, VTList, Ops);
  6641. ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
  6642. Opcode, dl.getIROrder(), VTList, MemVT, MMO));
  6643. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6644. void *IP = nullptr;
  6645. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6646. cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
  6647. return SDValue(E, 0);
  6648. }
  6649. N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  6650. VTList, MemVT, MMO);
  6651. createOperands(N, Ops);
  6652. CSEMap.InsertNode(N, IP);
  6653. } else {
  6654. N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  6655. VTList, MemVT, MMO);
  6656. createOperands(N, Ops);
  6657. }
  6658. InsertNode(N);
  6659. SDValue V(N, 0);
  6660. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6661. return V;
  6662. }
  6663. SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
  6664. SDValue Chain, int FrameIndex,
  6665. int64_t Size, int64_t Offset) {
  6666. const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
  6667. const auto VTs = getVTList(MVT::Other);
  6668. SDValue Ops[2] = {
  6669. Chain,
  6670. getFrameIndex(FrameIndex,
  6671. getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
  6672. true)};
  6673. FoldingSetNodeID ID;
  6674. AddNodeIDNode(ID, Opcode, VTs, Ops);
  6675. ID.AddInteger(FrameIndex);
  6676. ID.AddInteger(Size);
  6677. ID.AddInteger(Offset);
  6678. void *IP = nullptr;
  6679. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  6680. return SDValue(E, 0);
  6681. LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
  6682. Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
  6683. createOperands(N, Ops);
  6684. CSEMap.InsertNode(N, IP);
  6685. InsertNode(N);
  6686. SDValue V(N, 0);
  6687. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6688. return V;
  6689. }
  6690. SDValue SelectionDAG::getPseudoProbeNode(const SDLoc &Dl, SDValue Chain,
  6691. uint64_t Guid, uint64_t Index,
  6692. uint32_t Attr) {
  6693. const unsigned Opcode = ISD::PSEUDO_PROBE;
  6694. const auto VTs = getVTList(MVT::Other);
  6695. SDValue Ops[] = {Chain};
  6696. FoldingSetNodeID ID;
  6697. AddNodeIDNode(ID, Opcode, VTs, Ops);
  6698. ID.AddInteger(Guid);
  6699. ID.AddInteger(Index);
  6700. void *IP = nullptr;
  6701. if (SDNode *E = FindNodeOrInsertPos(ID, Dl, IP))
  6702. return SDValue(E, 0);
  6703. auto *N = newSDNode<PseudoProbeSDNode>(
  6704. Opcode, Dl.getIROrder(), Dl.getDebugLoc(), VTs, Guid, Index, Attr);
  6705. createOperands(N, Ops);
  6706. CSEMap.InsertNode(N, IP);
  6707. InsertNode(N);
  6708. SDValue V(N, 0);
  6709. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6710. return V;
  6711. }
  6712. /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
  6713. /// MachinePointerInfo record from it. This is particularly useful because the
  6714. /// code generator has many cases where it doesn't bother passing in a
  6715. /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
  6716. static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
  6717. SelectionDAG &DAG, SDValue Ptr,
  6718. int64_t Offset = 0) {
  6719. // If this is FI+Offset, we can model it.
  6720. if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
  6721. return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
  6722. FI->getIndex(), Offset);
  6723. // If this is (FI+Offset1)+Offset2, we can model it.
  6724. if (Ptr.getOpcode() != ISD::ADD ||
  6725. !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
  6726. !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
  6727. return Info;
  6728. int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
  6729. return MachinePointerInfo::getFixedStack(
  6730. DAG.getMachineFunction(), FI,
  6731. Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
  6732. }
  6733. /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
  6734. /// MachinePointerInfo record from it. This is particularly useful because the
  6735. /// code generator has many cases where it doesn't bother passing in a
  6736. /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
  6737. static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
  6738. SelectionDAG &DAG, SDValue Ptr,
  6739. SDValue OffsetOp) {
  6740. // If the 'Offset' value isn't a constant, we can't handle this.
  6741. if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
  6742. return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
  6743. if (OffsetOp.isUndef())
  6744. return InferPointerInfo(Info, DAG, Ptr);
  6745. return Info;
  6746. }
  6747. SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
  6748. EVT VT, const SDLoc &dl, SDValue Chain,
  6749. SDValue Ptr, SDValue Offset,
  6750. MachinePointerInfo PtrInfo, EVT MemVT,
  6751. Align Alignment,
  6752. MachineMemOperand::Flags MMOFlags,
  6753. const AAMDNodes &AAInfo, const MDNode *Ranges) {
  6754. assert(Chain.getValueType() == MVT::Other &&
  6755. "Invalid chain type");
  6756. MMOFlags |= MachineMemOperand::MOLoad;
  6757. assert((MMOFlags & MachineMemOperand::MOStore) == 0);
  6758. // If we don't have a PtrInfo, infer the trivial frame index case to simplify
  6759. // clients.
  6760. if (PtrInfo.V.isNull())
  6761. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
  6762. uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
  6763. MachineFunction &MF = getMachineFunction();
  6764. MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
  6765. Alignment, AAInfo, Ranges);
  6766. return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
  6767. }
  6768. SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
  6769. EVT VT, const SDLoc &dl, SDValue Chain,
  6770. SDValue Ptr, SDValue Offset, EVT MemVT,
  6771. MachineMemOperand *MMO) {
  6772. if (VT == MemVT) {
  6773. ExtType = ISD::NON_EXTLOAD;
  6774. } else if (ExtType == ISD::NON_EXTLOAD) {
  6775. assert(VT == MemVT && "Non-extending load from different memory type!");
  6776. } else {
  6777. // Extending load.
  6778. assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
  6779. "Should only be an extending load, not truncating!");
  6780. assert(VT.isInteger() == MemVT.isInteger() &&
  6781. "Cannot convert from FP to Int or Int -> FP!");
  6782. assert(VT.isVector() == MemVT.isVector() &&
  6783. "Cannot use an ext load to convert to or from a vector!");
  6784. assert((!VT.isVector() ||
  6785. VT.getVectorElementCount() == MemVT.getVectorElementCount()) &&
  6786. "Cannot use an ext load to change the number of vector elements!");
  6787. }
  6788. bool Indexed = AM != ISD::UNINDEXED;
  6789. assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
  6790. SDVTList VTs = Indexed ?
  6791. getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
  6792. SDValue Ops[] = { Chain, Ptr, Offset };
  6793. FoldingSetNodeID ID;
  6794. AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
  6795. ID.AddInteger(MemVT.getRawBits());
  6796. ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
  6797. dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
  6798. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6799. void *IP = nullptr;
  6800. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6801. cast<LoadSDNode>(E)->refineAlignment(MMO);
  6802. return SDValue(E, 0);
  6803. }
  6804. auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  6805. ExtType, MemVT, MMO);
  6806. createOperands(N, Ops);
  6807. CSEMap.InsertNode(N, IP);
  6808. InsertNode(N);
  6809. SDValue V(N, 0);
  6810. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6811. return V;
  6812. }
  6813. SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  6814. SDValue Ptr, MachinePointerInfo PtrInfo,
  6815. MaybeAlign Alignment,
  6816. MachineMemOperand::Flags MMOFlags,
  6817. const AAMDNodes &AAInfo, const MDNode *Ranges) {
  6818. SDValue Undef = getUNDEF(Ptr.getValueType());
  6819. return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  6820. PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
  6821. }
  6822. SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  6823. SDValue Ptr, MachineMemOperand *MMO) {
  6824. SDValue Undef = getUNDEF(Ptr.getValueType());
  6825. return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  6826. VT, MMO);
  6827. }
  6828. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
  6829. EVT VT, SDValue Chain, SDValue Ptr,
  6830. MachinePointerInfo PtrInfo, EVT MemVT,
  6831. MaybeAlign Alignment,
  6832. MachineMemOperand::Flags MMOFlags,
  6833. const AAMDNodes &AAInfo) {
  6834. SDValue Undef = getUNDEF(Ptr.getValueType());
  6835. return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
  6836. MemVT, Alignment, MMOFlags, AAInfo);
  6837. }
  6838. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
  6839. EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
  6840. MachineMemOperand *MMO) {
  6841. SDValue Undef = getUNDEF(Ptr.getValueType());
  6842. return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
  6843. MemVT, MMO);
  6844. }
  6845. SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
  6846. SDValue Base, SDValue Offset,
  6847. ISD::MemIndexedMode AM) {
  6848. LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
  6849. assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
  6850. // Don't propagate the invariant or dereferenceable flags.
  6851. auto MMOFlags =
  6852. LD->getMemOperand()->getFlags() &
  6853. ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  6854. return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
  6855. LD->getChain(), Base, Offset, LD->getPointerInfo(),
  6856. LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo());
  6857. }
  6858. SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6859. SDValue Ptr, MachinePointerInfo PtrInfo,
  6860. Align Alignment,
  6861. MachineMemOperand::Flags MMOFlags,
  6862. const AAMDNodes &AAInfo) {
  6863. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  6864. MMOFlags |= MachineMemOperand::MOStore;
  6865. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  6866. if (PtrInfo.V.isNull())
  6867. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  6868. MachineFunction &MF = getMachineFunction();
  6869. uint64_t Size =
  6870. MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
  6871. MachineMemOperand *MMO =
  6872. MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
  6873. return getStore(Chain, dl, Val, Ptr, MMO);
  6874. }
  6875. SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6876. SDValue Ptr, MachineMemOperand *MMO) {
  6877. assert(Chain.getValueType() == MVT::Other &&
  6878. "Invalid chain type");
  6879. EVT VT = Val.getValueType();
  6880. SDVTList VTs = getVTList(MVT::Other);
  6881. SDValue Undef = getUNDEF(Ptr.getValueType());
  6882. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  6883. FoldingSetNodeID ID;
  6884. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6885. ID.AddInteger(VT.getRawBits());
  6886. ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
  6887. dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
  6888. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6889. void *IP = nullptr;
  6890. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6891. cast<StoreSDNode>(E)->refineAlignment(MMO);
  6892. return SDValue(E, 0);
  6893. }
  6894. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6895. ISD::UNINDEXED, false, VT, MMO);
  6896. createOperands(N, Ops);
  6897. CSEMap.InsertNode(N, IP);
  6898. InsertNode(N);
  6899. SDValue V(N, 0);
  6900. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6901. return V;
  6902. }
  6903. SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6904. SDValue Ptr, MachinePointerInfo PtrInfo,
  6905. EVT SVT, Align Alignment,
  6906. MachineMemOperand::Flags MMOFlags,
  6907. const AAMDNodes &AAInfo) {
  6908. assert(Chain.getValueType() == MVT::Other &&
  6909. "Invalid chain type");
  6910. MMOFlags |= MachineMemOperand::MOStore;
  6911. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  6912. if (PtrInfo.V.isNull())
  6913. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  6914. MachineFunction &MF = getMachineFunction();
  6915. MachineMemOperand *MMO = MF.getMachineMemOperand(
  6916. PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
  6917. Alignment, AAInfo);
  6918. return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
  6919. }
  6920. SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6921. SDValue Ptr, EVT SVT,
  6922. MachineMemOperand *MMO) {
  6923. EVT VT = Val.getValueType();
  6924. assert(Chain.getValueType() == MVT::Other &&
  6925. "Invalid chain type");
  6926. if (VT == SVT)
  6927. return getStore(Chain, dl, Val, Ptr, MMO);
  6928. assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
  6929. "Should only be a truncating store, not extending!");
  6930. assert(VT.isInteger() == SVT.isInteger() &&
  6931. "Can't do FP-INT conversion!");
  6932. assert(VT.isVector() == SVT.isVector() &&
  6933. "Cannot use trunc store to convert to or from a vector!");
  6934. assert((!VT.isVector() ||
  6935. VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
  6936. "Cannot use trunc store to change the number of vector elements!");
  6937. SDVTList VTs = getVTList(MVT::Other);
  6938. SDValue Undef = getUNDEF(Ptr.getValueType());
  6939. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  6940. FoldingSetNodeID ID;
  6941. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6942. ID.AddInteger(SVT.getRawBits());
  6943. ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
  6944. dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
  6945. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6946. void *IP = nullptr;
  6947. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6948. cast<StoreSDNode>(E)->refineAlignment(MMO);
  6949. return SDValue(E, 0);
  6950. }
  6951. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6952. ISD::UNINDEXED, true, SVT, MMO);
  6953. createOperands(N, Ops);
  6954. CSEMap.InsertNode(N, IP);
  6955. InsertNode(N);
  6956. SDValue V(N, 0);
  6957. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6958. return V;
  6959. }
  6960. SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
  6961. SDValue Base, SDValue Offset,
  6962. ISD::MemIndexedMode AM) {
  6963. StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
  6964. assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
  6965. SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
  6966. SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
  6967. FoldingSetNodeID ID;
  6968. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6969. ID.AddInteger(ST->getMemoryVT().getRawBits());
  6970. ID.AddInteger(ST->getRawSubclassData());
  6971. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  6972. void *IP = nullptr;
  6973. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  6974. return SDValue(E, 0);
  6975. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  6976. ST->isTruncatingStore(), ST->getMemoryVT(),
  6977. ST->getMemOperand());
  6978. createOperands(N, Ops);
  6979. CSEMap.InsertNode(N, IP);
  6980. InsertNode(N);
  6981. SDValue V(N, 0);
  6982. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6983. return V;
  6984. }
  6985. SDValue SelectionDAG::getLoadVP(
  6986. ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, EVT VT, const SDLoc &dl,
  6987. SDValue Chain, SDValue Ptr, SDValue Offset, SDValue Mask, SDValue EVL,
  6988. MachinePointerInfo PtrInfo, EVT MemVT, Align Alignment,
  6989. MachineMemOperand::Flags MMOFlags, const AAMDNodes &AAInfo,
  6990. const MDNode *Ranges, bool IsExpanding) {
  6991. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  6992. MMOFlags |= MachineMemOperand::MOLoad;
  6993. assert((MMOFlags & MachineMemOperand::MOStore) == 0);
  6994. // If we don't have a PtrInfo, infer the trivial frame index case to simplify
  6995. // clients.
  6996. if (PtrInfo.V.isNull())
  6997. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
  6998. uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
  6999. MachineFunction &MF = getMachineFunction();
  7000. MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
  7001. Alignment, AAInfo, Ranges);
  7002. return getLoadVP(AM, ExtType, VT, dl, Chain, Ptr, Offset, Mask, EVL, MemVT,
  7003. MMO, IsExpanding);
  7004. }
  7005. SDValue SelectionDAG::getLoadVP(ISD::MemIndexedMode AM,
  7006. ISD::LoadExtType ExtType, EVT VT,
  7007. const SDLoc &dl, SDValue Chain, SDValue Ptr,
  7008. SDValue Offset, SDValue Mask, SDValue EVL,
  7009. EVT MemVT, MachineMemOperand *MMO,
  7010. bool IsExpanding) {
  7011. bool Indexed = AM != ISD::UNINDEXED;
  7012. assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
  7013. SDVTList VTs = Indexed ? getVTList(VT, Ptr.getValueType(), MVT::Other)
  7014. : getVTList(VT, MVT::Other);
  7015. SDValue Ops[] = {Chain, Ptr, Offset, Mask, EVL};
  7016. FoldingSetNodeID ID;
  7017. AddNodeIDNode(ID, ISD::VP_LOAD, VTs, Ops);
  7018. ID.AddInteger(VT.getRawBits());
  7019. ID.AddInteger(getSyntheticNodeSubclassData<VPLoadSDNode>(
  7020. dl.getIROrder(), VTs, AM, ExtType, IsExpanding, MemVT, MMO));
  7021. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7022. void *IP = nullptr;
  7023. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7024. cast<VPLoadSDNode>(E)->refineAlignment(MMO);
  7025. return SDValue(E, 0);
  7026. }
  7027. auto *N = newSDNode<VPLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  7028. ExtType, IsExpanding, MemVT, MMO);
  7029. createOperands(N, Ops);
  7030. CSEMap.InsertNode(N, IP);
  7031. InsertNode(N);
  7032. SDValue V(N, 0);
  7033. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7034. return V;
  7035. }
  7036. SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
  7037. SDValue Ptr, SDValue Mask, SDValue EVL,
  7038. MachinePointerInfo PtrInfo,
  7039. MaybeAlign Alignment,
  7040. MachineMemOperand::Flags MMOFlags,
  7041. const AAMDNodes &AAInfo, const MDNode *Ranges,
  7042. bool IsExpanding) {
  7043. SDValue Undef = getUNDEF(Ptr.getValueType());
  7044. return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  7045. Mask, EVL, PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges,
  7046. IsExpanding);
  7047. }
  7048. SDValue SelectionDAG::getLoadVP(EVT VT, const SDLoc &dl, SDValue Chain,
  7049. SDValue Ptr, SDValue Mask, SDValue EVL,
  7050. MachineMemOperand *MMO, bool IsExpanding) {
  7051. SDValue Undef = getUNDEF(Ptr.getValueType());
  7052. return getLoadVP(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  7053. Mask, EVL, VT, MMO, IsExpanding);
  7054. }
  7055. SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
  7056. EVT VT, SDValue Chain, SDValue Ptr,
  7057. SDValue Mask, SDValue EVL,
  7058. MachinePointerInfo PtrInfo, EVT MemVT,
  7059. MaybeAlign Alignment,
  7060. MachineMemOperand::Flags MMOFlags,
  7061. const AAMDNodes &AAInfo, bool IsExpanding) {
  7062. SDValue Undef = getUNDEF(Ptr.getValueType());
  7063. return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
  7064. EVL, PtrInfo, MemVT, Alignment, MMOFlags, AAInfo, nullptr,
  7065. IsExpanding);
  7066. }
  7067. SDValue SelectionDAG::getExtLoadVP(ISD::LoadExtType ExtType, const SDLoc &dl,
  7068. EVT VT, SDValue Chain, SDValue Ptr,
  7069. SDValue Mask, SDValue EVL, EVT MemVT,
  7070. MachineMemOperand *MMO, bool IsExpanding) {
  7071. SDValue Undef = getUNDEF(Ptr.getValueType());
  7072. return getLoadVP(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, Mask,
  7073. EVL, MemVT, MMO, IsExpanding);
  7074. }
  7075. SDValue SelectionDAG::getIndexedLoadVP(SDValue OrigLoad, const SDLoc &dl,
  7076. SDValue Base, SDValue Offset,
  7077. ISD::MemIndexedMode AM) {
  7078. auto *LD = cast<VPLoadSDNode>(OrigLoad);
  7079. assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
  7080. // Don't propagate the invariant or dereferenceable flags.
  7081. auto MMOFlags =
  7082. LD->getMemOperand()->getFlags() &
  7083. ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  7084. return getLoadVP(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
  7085. LD->getChain(), Base, Offset, LD->getMask(),
  7086. LD->getVectorLength(), LD->getPointerInfo(),
  7087. LD->getMemoryVT(), LD->getAlign(), MMOFlags, LD->getAAInfo(),
  7088. nullptr, LD->isExpandingLoad());
  7089. }
  7090. SDValue SelectionDAG::getStoreVP(SDValue Chain, const SDLoc &dl, SDValue Val,
  7091. SDValue Ptr, SDValue Offset, SDValue Mask,
  7092. SDValue EVL, EVT MemVT, MachineMemOperand *MMO,
  7093. ISD::MemIndexedMode AM, bool IsTruncating,
  7094. bool IsCompressing) {
  7095. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7096. bool Indexed = AM != ISD::UNINDEXED;
  7097. assert((Indexed || Offset.isUndef()) && "Unindexed vp_store with an offset!");
  7098. SDVTList VTs = Indexed ? getVTList(Ptr.getValueType(), MVT::Other)
  7099. : getVTList(MVT::Other);
  7100. SDValue Ops[] = {Chain, Val, Ptr, Offset, Mask, EVL};
  7101. FoldingSetNodeID ID;
  7102. AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
  7103. ID.AddInteger(MemVT.getRawBits());
  7104. ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
  7105. dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
  7106. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7107. void *IP = nullptr;
  7108. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7109. cast<VPStoreSDNode>(E)->refineAlignment(MMO);
  7110. return SDValue(E, 0);
  7111. }
  7112. auto *N = newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  7113. IsTruncating, IsCompressing, MemVT, MMO);
  7114. createOperands(N, Ops);
  7115. CSEMap.InsertNode(N, IP);
  7116. InsertNode(N);
  7117. SDValue V(N, 0);
  7118. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7119. return V;
  7120. }
  7121. SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
  7122. SDValue Val, SDValue Ptr, SDValue Mask,
  7123. SDValue EVL, MachinePointerInfo PtrInfo,
  7124. EVT SVT, Align Alignment,
  7125. MachineMemOperand::Flags MMOFlags,
  7126. const AAMDNodes &AAInfo,
  7127. bool IsCompressing) {
  7128. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7129. MMOFlags |= MachineMemOperand::MOStore;
  7130. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  7131. if (PtrInfo.V.isNull())
  7132. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  7133. MachineFunction &MF = getMachineFunction();
  7134. MachineMemOperand *MMO = MF.getMachineMemOperand(
  7135. PtrInfo, MMOFlags, MemoryLocation::getSizeOrUnknown(SVT.getStoreSize()),
  7136. Alignment, AAInfo);
  7137. return getTruncStoreVP(Chain, dl, Val, Ptr, Mask, EVL, SVT, MMO,
  7138. IsCompressing);
  7139. }
  7140. SDValue SelectionDAG::getTruncStoreVP(SDValue Chain, const SDLoc &dl,
  7141. SDValue Val, SDValue Ptr, SDValue Mask,
  7142. SDValue EVL, EVT SVT,
  7143. MachineMemOperand *MMO,
  7144. bool IsCompressing) {
  7145. EVT VT = Val.getValueType();
  7146. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  7147. if (VT == SVT)
  7148. return getStoreVP(Chain, dl, Val, Ptr, getUNDEF(Ptr.getValueType()), Mask,
  7149. EVL, VT, MMO, ISD::UNINDEXED,
  7150. /*IsTruncating*/ false, IsCompressing);
  7151. assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
  7152. "Should only be a truncating store, not extending!");
  7153. assert(VT.isInteger() == SVT.isInteger() && "Can't do FP-INT conversion!");
  7154. assert(VT.isVector() == SVT.isVector() &&
  7155. "Cannot use trunc store to convert to or from a vector!");
  7156. assert((!VT.isVector() ||
  7157. VT.getVectorElementCount() == SVT.getVectorElementCount()) &&
  7158. "Cannot use trunc store to change the number of vector elements!");
  7159. SDVTList VTs = getVTList(MVT::Other);
  7160. SDValue Undef = getUNDEF(Ptr.getValueType());
  7161. SDValue Ops[] = {Chain, Val, Ptr, Undef, Mask, EVL};
  7162. FoldingSetNodeID ID;
  7163. AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
  7164. ID.AddInteger(SVT.getRawBits());
  7165. ID.AddInteger(getSyntheticNodeSubclassData<VPStoreSDNode>(
  7166. dl.getIROrder(), VTs, ISD::UNINDEXED, true, IsCompressing, SVT, MMO));
  7167. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7168. void *IP = nullptr;
  7169. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7170. cast<VPStoreSDNode>(E)->refineAlignment(MMO);
  7171. return SDValue(E, 0);
  7172. }
  7173. auto *N =
  7174. newSDNode<VPStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7175. ISD::UNINDEXED, true, IsCompressing, SVT, MMO);
  7176. createOperands(N, Ops);
  7177. CSEMap.InsertNode(N, IP);
  7178. InsertNode(N);
  7179. SDValue V(N, 0);
  7180. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7181. return V;
  7182. }
  7183. SDValue SelectionDAG::getIndexedStoreVP(SDValue OrigStore, const SDLoc &dl,
  7184. SDValue Base, SDValue Offset,
  7185. ISD::MemIndexedMode AM) {
  7186. auto *ST = cast<VPStoreSDNode>(OrigStore);
  7187. assert(ST->getOffset().isUndef() && "Store is already an indexed store!");
  7188. SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
  7189. SDValue Ops[] = {ST->getChain(), ST->getValue(), Base,
  7190. Offset, ST->getMask(), ST->getVectorLength()};
  7191. FoldingSetNodeID ID;
  7192. AddNodeIDNode(ID, ISD::VP_STORE, VTs, Ops);
  7193. ID.AddInteger(ST->getMemoryVT().getRawBits());
  7194. ID.AddInteger(ST->getRawSubclassData());
  7195. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  7196. void *IP = nullptr;
  7197. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  7198. return SDValue(E, 0);
  7199. auto *N = newSDNode<VPStoreSDNode>(
  7200. dl.getIROrder(), dl.getDebugLoc(), VTs, AM, ST->isTruncatingStore(),
  7201. ST->isCompressingStore(), ST->getMemoryVT(), ST->getMemOperand());
  7202. createOperands(N, Ops);
  7203. CSEMap.InsertNode(N, IP);
  7204. InsertNode(N);
  7205. SDValue V(N, 0);
  7206. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7207. return V;
  7208. }
  7209. SDValue SelectionDAG::getGatherVP(SDVTList VTs, EVT VT, const SDLoc &dl,
  7210. ArrayRef<SDValue> Ops, MachineMemOperand *MMO,
  7211. ISD::MemIndexType IndexType) {
  7212. assert(Ops.size() == 6 && "Incompatible number of operands");
  7213. FoldingSetNodeID ID;
  7214. AddNodeIDNode(ID, ISD::VP_GATHER, VTs, Ops);
  7215. ID.AddInteger(VT.getRawBits());
  7216. ID.AddInteger(getSyntheticNodeSubclassData<VPGatherSDNode>(
  7217. dl.getIROrder(), VTs, VT, MMO, IndexType));
  7218. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7219. void *IP = nullptr;
  7220. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7221. cast<VPGatherSDNode>(E)->refineAlignment(MMO);
  7222. return SDValue(E, 0);
  7223. }
  7224. auto *N = newSDNode<VPGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7225. VT, MMO, IndexType);
  7226. createOperands(N, Ops);
  7227. assert(N->getMask().getValueType().getVectorElementCount() ==
  7228. N->getValueType(0).getVectorElementCount() &&
  7229. "Vector width mismatch between mask and data");
  7230. assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
  7231. N->getValueType(0).getVectorElementCount().isScalable() &&
  7232. "Scalable flags of index and data do not match");
  7233. assert(ElementCount::isKnownGE(
  7234. N->getIndex().getValueType().getVectorElementCount(),
  7235. N->getValueType(0).getVectorElementCount()) &&
  7236. "Vector width mismatch between index and data");
  7237. assert(isa<ConstantSDNode>(N->getScale()) &&
  7238. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  7239. "Scale should be a constant power of 2");
  7240. CSEMap.InsertNode(N, IP);
  7241. InsertNode(N);
  7242. SDValue V(N, 0);
  7243. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7244. return V;
  7245. }
  7246. SDValue SelectionDAG::getScatterVP(SDVTList VTs, EVT VT, const SDLoc &dl,
  7247. ArrayRef<SDValue> Ops,
  7248. MachineMemOperand *MMO,
  7249. ISD::MemIndexType IndexType) {
  7250. assert(Ops.size() == 7 && "Incompatible number of operands");
  7251. FoldingSetNodeID ID;
  7252. AddNodeIDNode(ID, ISD::VP_SCATTER, VTs, Ops);
  7253. ID.AddInteger(VT.getRawBits());
  7254. ID.AddInteger(getSyntheticNodeSubclassData<VPScatterSDNode>(
  7255. dl.getIROrder(), VTs, VT, MMO, IndexType));
  7256. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7257. void *IP = nullptr;
  7258. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7259. cast<VPScatterSDNode>(E)->refineAlignment(MMO);
  7260. return SDValue(E, 0);
  7261. }
  7262. auto *N = newSDNode<VPScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7263. VT, MMO, IndexType);
  7264. createOperands(N, Ops);
  7265. assert(N->getMask().getValueType().getVectorElementCount() ==
  7266. N->getValue().getValueType().getVectorElementCount() &&
  7267. "Vector width mismatch between mask and data");
  7268. assert(
  7269. N->getIndex().getValueType().getVectorElementCount().isScalable() ==
  7270. N->getValue().getValueType().getVectorElementCount().isScalable() &&
  7271. "Scalable flags of index and data do not match");
  7272. assert(ElementCount::isKnownGE(
  7273. N->getIndex().getValueType().getVectorElementCount(),
  7274. N->getValue().getValueType().getVectorElementCount()) &&
  7275. "Vector width mismatch between index and data");
  7276. assert(isa<ConstantSDNode>(N->getScale()) &&
  7277. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  7278. "Scale should be a constant power of 2");
  7279. CSEMap.InsertNode(N, IP);
  7280. InsertNode(N);
  7281. SDValue V(N, 0);
  7282. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7283. return V;
  7284. }
  7285. SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  7286. SDValue Base, SDValue Offset, SDValue Mask,
  7287. SDValue PassThru, EVT MemVT,
  7288. MachineMemOperand *MMO,
  7289. ISD::MemIndexedMode AM,
  7290. ISD::LoadExtType ExtTy, bool isExpanding) {
  7291. bool Indexed = AM != ISD::UNINDEXED;
  7292. assert((Indexed || Offset.isUndef()) &&
  7293. "Unindexed masked load with an offset!");
  7294. SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
  7295. : getVTList(VT, MVT::Other);
  7296. SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
  7297. FoldingSetNodeID ID;
  7298. AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
  7299. ID.AddInteger(MemVT.getRawBits());
  7300. ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
  7301. dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
  7302. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7303. void *IP = nullptr;
  7304. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7305. cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
  7306. return SDValue(E, 0);
  7307. }
  7308. auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  7309. AM, ExtTy, isExpanding, MemVT, MMO);
  7310. createOperands(N, Ops);
  7311. CSEMap.InsertNode(N, IP);
  7312. InsertNode(N);
  7313. SDValue V(N, 0);
  7314. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7315. return V;
  7316. }
  7317. SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
  7318. SDValue Base, SDValue Offset,
  7319. ISD::MemIndexedMode AM) {
  7320. MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
  7321. assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
  7322. return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
  7323. Offset, LD->getMask(), LD->getPassThru(),
  7324. LD->getMemoryVT(), LD->getMemOperand(), AM,
  7325. LD->getExtensionType(), LD->isExpandingLoad());
  7326. }
  7327. SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
  7328. SDValue Val, SDValue Base, SDValue Offset,
  7329. SDValue Mask, EVT MemVT,
  7330. MachineMemOperand *MMO,
  7331. ISD::MemIndexedMode AM, bool IsTruncating,
  7332. bool IsCompressing) {
  7333. assert(Chain.getValueType() == MVT::Other &&
  7334. "Invalid chain type");
  7335. bool Indexed = AM != ISD::UNINDEXED;
  7336. assert((Indexed || Offset.isUndef()) &&
  7337. "Unindexed masked store with an offset!");
  7338. SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
  7339. : getVTList(MVT::Other);
  7340. SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
  7341. FoldingSetNodeID ID;
  7342. AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
  7343. ID.AddInteger(MemVT.getRawBits());
  7344. ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
  7345. dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
  7346. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7347. void *IP = nullptr;
  7348. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7349. cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
  7350. return SDValue(E, 0);
  7351. }
  7352. auto *N =
  7353. newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  7354. IsTruncating, IsCompressing, MemVT, MMO);
  7355. createOperands(N, Ops);
  7356. CSEMap.InsertNode(N, IP);
  7357. InsertNode(N);
  7358. SDValue V(N, 0);
  7359. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7360. return V;
  7361. }
  7362. SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
  7363. SDValue Base, SDValue Offset,
  7364. ISD::MemIndexedMode AM) {
  7365. MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
  7366. assert(ST->getOffset().isUndef() &&
  7367. "Masked store is already a indexed store!");
  7368. return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
  7369. ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
  7370. AM, ST->isTruncatingStore(), ST->isCompressingStore());
  7371. }
  7372. SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT MemVT, const SDLoc &dl,
  7373. ArrayRef<SDValue> Ops,
  7374. MachineMemOperand *MMO,
  7375. ISD::MemIndexType IndexType,
  7376. ISD::LoadExtType ExtTy) {
  7377. assert(Ops.size() == 6 && "Incompatible number of operands");
  7378. FoldingSetNodeID ID;
  7379. AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
  7380. ID.AddInteger(MemVT.getRawBits());
  7381. ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
  7382. dl.getIROrder(), VTs, MemVT, MMO, IndexType, ExtTy));
  7383. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7384. void *IP = nullptr;
  7385. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7386. cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
  7387. return SDValue(E, 0);
  7388. }
  7389. IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
  7390. auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  7391. VTs, MemVT, MMO, IndexType, ExtTy);
  7392. createOperands(N, Ops);
  7393. assert(N->getPassThru().getValueType() == N->getValueType(0) &&
  7394. "Incompatible type of the PassThru value in MaskedGatherSDNode");
  7395. assert(N->getMask().getValueType().getVectorElementCount() ==
  7396. N->getValueType(0).getVectorElementCount() &&
  7397. "Vector width mismatch between mask and data");
  7398. assert(N->getIndex().getValueType().getVectorElementCount().isScalable() ==
  7399. N->getValueType(0).getVectorElementCount().isScalable() &&
  7400. "Scalable flags of index and data do not match");
  7401. assert(ElementCount::isKnownGE(
  7402. N->getIndex().getValueType().getVectorElementCount(),
  7403. N->getValueType(0).getVectorElementCount()) &&
  7404. "Vector width mismatch between index and data");
  7405. assert(isa<ConstantSDNode>(N->getScale()) &&
  7406. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  7407. "Scale should be a constant power of 2");
  7408. CSEMap.InsertNode(N, IP);
  7409. InsertNode(N);
  7410. SDValue V(N, 0);
  7411. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7412. return V;
  7413. }
  7414. SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT MemVT, const SDLoc &dl,
  7415. ArrayRef<SDValue> Ops,
  7416. MachineMemOperand *MMO,
  7417. ISD::MemIndexType IndexType,
  7418. bool IsTrunc) {
  7419. assert(Ops.size() == 6 && "Incompatible number of operands");
  7420. FoldingSetNodeID ID;
  7421. AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
  7422. ID.AddInteger(MemVT.getRawBits());
  7423. ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
  7424. dl.getIROrder(), VTs, MemVT, MMO, IndexType, IsTrunc));
  7425. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  7426. void *IP = nullptr;
  7427. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  7428. cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
  7429. return SDValue(E, 0);
  7430. }
  7431. IndexType = TLI->getCanonicalIndexType(IndexType, MemVT, Ops[4]);
  7432. auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  7433. VTs, MemVT, MMO, IndexType, IsTrunc);
  7434. createOperands(N, Ops);
  7435. assert(N->getMask().getValueType().getVectorElementCount() ==
  7436. N->getValue().getValueType().getVectorElementCount() &&
  7437. "Vector width mismatch between mask and data");
  7438. assert(
  7439. N->getIndex().getValueType().getVectorElementCount().isScalable() ==
  7440. N->getValue().getValueType().getVectorElementCount().isScalable() &&
  7441. "Scalable flags of index and data do not match");
  7442. assert(ElementCount::isKnownGE(
  7443. N->getIndex().getValueType().getVectorElementCount(),
  7444. N->getValue().getValueType().getVectorElementCount()) &&
  7445. "Vector width mismatch between index and data");
  7446. assert(isa<ConstantSDNode>(N->getScale()) &&
  7447. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  7448. "Scale should be a constant power of 2");
  7449. CSEMap.InsertNode(N, IP);
  7450. InsertNode(N);
  7451. SDValue V(N, 0);
  7452. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7453. return V;
  7454. }
  7455. SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
  7456. // select undef, T, F --> T (if T is a constant), otherwise F
  7457. // select, ?, undef, F --> F
  7458. // select, ?, T, undef --> T
  7459. if (Cond.isUndef())
  7460. return isConstantValueOfAnyType(T) ? T : F;
  7461. if (T.isUndef())
  7462. return F;
  7463. if (F.isUndef())
  7464. return T;
  7465. // select true, T, F --> T
  7466. // select false, T, F --> F
  7467. if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
  7468. return CondC->isZero() ? F : T;
  7469. // TODO: This should simplify VSELECT with constant condition using something
  7470. // like this (but check boolean contents to be complete?):
  7471. // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
  7472. // return T;
  7473. // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
  7474. // return F;
  7475. // select ?, T, T --> T
  7476. if (T == F)
  7477. return T;
  7478. return SDValue();
  7479. }
  7480. SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
  7481. // shift undef, Y --> 0 (can always assume that the undef value is 0)
  7482. if (X.isUndef())
  7483. return getConstant(0, SDLoc(X.getNode()), X.getValueType());
  7484. // shift X, undef --> undef (because it may shift by the bitwidth)
  7485. if (Y.isUndef())
  7486. return getUNDEF(X.getValueType());
  7487. // shift 0, Y --> 0
  7488. // shift X, 0 --> X
  7489. if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
  7490. return X;
  7491. // shift X, C >= bitwidth(X) --> undef
  7492. // All vector elements must be too big (or undef) to avoid partial undefs.
  7493. auto isShiftTooBig = [X](ConstantSDNode *Val) {
  7494. return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
  7495. };
  7496. if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
  7497. return getUNDEF(X.getValueType());
  7498. return SDValue();
  7499. }
  7500. SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
  7501. SDNodeFlags Flags) {
  7502. // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
  7503. // (an undef operand can be chosen to be Nan/Inf), then the result of this
  7504. // operation is poison. That result can be relaxed to undef.
  7505. ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
  7506. ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
  7507. bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
  7508. (YC && YC->getValueAPF().isNaN());
  7509. bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
  7510. (YC && YC->getValueAPF().isInfinity());
  7511. if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
  7512. return getUNDEF(X.getValueType());
  7513. if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
  7514. return getUNDEF(X.getValueType());
  7515. if (!YC)
  7516. return SDValue();
  7517. // X + -0.0 --> X
  7518. if (Opcode == ISD::FADD)
  7519. if (YC->getValueAPF().isNegZero())
  7520. return X;
  7521. // X - +0.0 --> X
  7522. if (Opcode == ISD::FSUB)
  7523. if (YC->getValueAPF().isPosZero())
  7524. return X;
  7525. // X * 1.0 --> X
  7526. // X / 1.0 --> X
  7527. if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
  7528. if (YC->getValueAPF().isExactlyValue(1.0))
  7529. return X;
  7530. // X * 0.0 --> 0.0
  7531. if (Opcode == ISD::FMUL && Flags.hasNoNaNs() && Flags.hasNoSignedZeros())
  7532. if (YC->getValueAPF().isZero())
  7533. return getConstantFP(0.0, SDLoc(Y), Y.getValueType());
  7534. return SDValue();
  7535. }
  7536. SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
  7537. SDValue Ptr, SDValue SV, unsigned Align) {
  7538. SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
  7539. return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
  7540. }
  7541. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  7542. ArrayRef<SDUse> Ops) {
  7543. switch (Ops.size()) {
  7544. case 0: return getNode(Opcode, DL, VT);
  7545. case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
  7546. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
  7547. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
  7548. default: break;
  7549. }
  7550. // Copy from an SDUse array into an SDValue array for use with
  7551. // the regular getNode logic.
  7552. SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
  7553. return getNode(Opcode, DL, VT, NewOps);
  7554. }
  7555. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  7556. ArrayRef<SDValue> Ops) {
  7557. SDNodeFlags Flags;
  7558. if (Inserter)
  7559. Flags = Inserter->getFlags();
  7560. return getNode(Opcode, DL, VT, Ops, Flags);
  7561. }
  7562. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  7563. ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
  7564. unsigned NumOps = Ops.size();
  7565. switch (NumOps) {
  7566. case 0: return getNode(Opcode, DL, VT);
  7567. case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
  7568. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
  7569. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
  7570. default: break;
  7571. }
  7572. #ifndef NDEBUG
  7573. for (auto &Op : Ops)
  7574. assert(Op.getOpcode() != ISD::DELETED_NODE &&
  7575. "Operand is DELETED_NODE!");
  7576. #endif
  7577. switch (Opcode) {
  7578. default: break;
  7579. case ISD::BUILD_VECTOR:
  7580. // Attempt to simplify BUILD_VECTOR.
  7581. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  7582. return V;
  7583. break;
  7584. case ISD::CONCAT_VECTORS:
  7585. if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
  7586. return V;
  7587. break;
  7588. case ISD::SELECT_CC:
  7589. assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
  7590. assert(Ops[0].getValueType() == Ops[1].getValueType() &&
  7591. "LHS and RHS of condition must have same type!");
  7592. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  7593. "True and False arms of SelectCC must have same type!");
  7594. assert(Ops[2].getValueType() == VT &&
  7595. "select_cc node must be of same type as true and false value!");
  7596. break;
  7597. case ISD::BR_CC:
  7598. assert(NumOps == 5 && "BR_CC takes 5 operands!");
  7599. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  7600. "LHS/RHS of comparison should match types!");
  7601. break;
  7602. }
  7603. // Memoize nodes.
  7604. SDNode *N;
  7605. SDVTList VTs = getVTList(VT);
  7606. if (VT != MVT::Glue) {
  7607. FoldingSetNodeID ID;
  7608. AddNodeIDNode(ID, Opcode, VTs, Ops);
  7609. void *IP = nullptr;
  7610. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  7611. return SDValue(E, 0);
  7612. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  7613. createOperands(N, Ops);
  7614. CSEMap.InsertNode(N, IP);
  7615. } else {
  7616. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  7617. createOperands(N, Ops);
  7618. }
  7619. N->setFlags(Flags);
  7620. InsertNode(N);
  7621. SDValue V(N, 0);
  7622. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7623. return V;
  7624. }
  7625. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
  7626. ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
  7627. return getNode(Opcode, DL, getVTList(ResultTys), Ops);
  7628. }
  7629. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  7630. ArrayRef<SDValue> Ops) {
  7631. SDNodeFlags Flags;
  7632. if (Inserter)
  7633. Flags = Inserter->getFlags();
  7634. return getNode(Opcode, DL, VTList, Ops, Flags);
  7635. }
  7636. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  7637. ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
  7638. if (VTList.NumVTs == 1)
  7639. return getNode(Opcode, DL, VTList.VTs[0], Ops);
  7640. #ifndef NDEBUG
  7641. for (auto &Op : Ops)
  7642. assert(Op.getOpcode() != ISD::DELETED_NODE &&
  7643. "Operand is DELETED_NODE!");
  7644. #endif
  7645. switch (Opcode) {
  7646. case ISD::STRICT_FP_EXTEND:
  7647. assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
  7648. "Invalid STRICT_FP_EXTEND!");
  7649. assert(VTList.VTs[0].isFloatingPoint() &&
  7650. Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
  7651. assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
  7652. "STRICT_FP_EXTEND result type should be vector iff the operand "
  7653. "type is vector!");
  7654. assert((!VTList.VTs[0].isVector() ||
  7655. VTList.VTs[0].getVectorNumElements() ==
  7656. Ops[1].getValueType().getVectorNumElements()) &&
  7657. "Vector element count mismatch!");
  7658. assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
  7659. "Invalid fpext node, dst <= src!");
  7660. break;
  7661. case ISD::STRICT_FP_ROUND:
  7662. assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
  7663. assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
  7664. "STRICT_FP_ROUND result type should be vector iff the operand "
  7665. "type is vector!");
  7666. assert((!VTList.VTs[0].isVector() ||
  7667. VTList.VTs[0].getVectorNumElements() ==
  7668. Ops[1].getValueType().getVectorNumElements()) &&
  7669. "Vector element count mismatch!");
  7670. assert(VTList.VTs[0].isFloatingPoint() &&
  7671. Ops[1].getValueType().isFloatingPoint() &&
  7672. VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
  7673. isa<ConstantSDNode>(Ops[2]) &&
  7674. (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
  7675. cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
  7676. "Invalid STRICT_FP_ROUND!");
  7677. break;
  7678. #if 0
  7679. // FIXME: figure out how to safely handle things like
  7680. // int foo(int x) { return 1 << (x & 255); }
  7681. // int bar() { return foo(256); }
  7682. case ISD::SRA_PARTS:
  7683. case ISD::SRL_PARTS:
  7684. case ISD::SHL_PARTS:
  7685. if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  7686. cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
  7687. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  7688. else if (N3.getOpcode() == ISD::AND)
  7689. if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
  7690. // If the and is only masking out bits that cannot effect the shift,
  7691. // eliminate the and.
  7692. unsigned NumBits = VT.getScalarSizeInBits()*2;
  7693. if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
  7694. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  7695. }
  7696. break;
  7697. #endif
  7698. }
  7699. // Memoize the node unless it returns a flag.
  7700. SDNode *N;
  7701. if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
  7702. FoldingSetNodeID ID;
  7703. AddNodeIDNode(ID, Opcode, VTList, Ops);
  7704. void *IP = nullptr;
  7705. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  7706. return SDValue(E, 0);
  7707. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
  7708. createOperands(N, Ops);
  7709. CSEMap.InsertNode(N, IP);
  7710. } else {
  7711. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
  7712. createOperands(N, Ops);
  7713. }
  7714. N->setFlags(Flags);
  7715. InsertNode(N);
  7716. SDValue V(N, 0);
  7717. NewSDValueDbgMsg(V, "Creating new node: ", this);
  7718. return V;
  7719. }
  7720. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
  7721. SDVTList VTList) {
  7722. return getNode(Opcode, DL, VTList, None);
  7723. }
  7724. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  7725. SDValue N1) {
  7726. SDValue Ops[] = { N1 };
  7727. return getNode(Opcode, DL, VTList, Ops);
  7728. }
  7729. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  7730. SDValue N1, SDValue N2) {
  7731. SDValue Ops[] = { N1, N2 };
  7732. return getNode(Opcode, DL, VTList, Ops);
  7733. }
  7734. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  7735. SDValue N1, SDValue N2, SDValue N3) {
  7736. SDValue Ops[] = { N1, N2, N3 };
  7737. return getNode(Opcode, DL, VTList, Ops);
  7738. }
  7739. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  7740. SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
  7741. SDValue Ops[] = { N1, N2, N3, N4 };
  7742. return getNode(Opcode, DL, VTList, Ops);
  7743. }
  7744. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  7745. SDValue N1, SDValue N2, SDValue N3, SDValue N4,
  7746. SDValue N5) {
  7747. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  7748. return getNode(Opcode, DL, VTList, Ops);
  7749. }
  7750. SDVTList SelectionDAG::getVTList(EVT VT) {
  7751. return makeVTList(SDNode::getValueTypeList(VT), 1);
  7752. }
  7753. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
  7754. FoldingSetNodeID ID;
  7755. ID.AddInteger(2U);
  7756. ID.AddInteger(VT1.getRawBits());
  7757. ID.AddInteger(VT2.getRawBits());
  7758. void *IP = nullptr;
  7759. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  7760. if (!Result) {
  7761. EVT *Array = Allocator.Allocate<EVT>(2);
  7762. Array[0] = VT1;
  7763. Array[1] = VT2;
  7764. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
  7765. VTListMap.InsertNode(Result, IP);
  7766. }
  7767. return Result->getSDVTList();
  7768. }
  7769. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
  7770. FoldingSetNodeID ID;
  7771. ID.AddInteger(3U);
  7772. ID.AddInteger(VT1.getRawBits());
  7773. ID.AddInteger(VT2.getRawBits());
  7774. ID.AddInteger(VT3.getRawBits());
  7775. void *IP = nullptr;
  7776. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  7777. if (!Result) {
  7778. EVT *Array = Allocator.Allocate<EVT>(3);
  7779. Array[0] = VT1;
  7780. Array[1] = VT2;
  7781. Array[2] = VT3;
  7782. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
  7783. VTListMap.InsertNode(Result, IP);
  7784. }
  7785. return Result->getSDVTList();
  7786. }
  7787. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
  7788. FoldingSetNodeID ID;
  7789. ID.AddInteger(4U);
  7790. ID.AddInteger(VT1.getRawBits());
  7791. ID.AddInteger(VT2.getRawBits());
  7792. ID.AddInteger(VT3.getRawBits());
  7793. ID.AddInteger(VT4.getRawBits());
  7794. void *IP = nullptr;
  7795. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  7796. if (!Result) {
  7797. EVT *Array = Allocator.Allocate<EVT>(4);
  7798. Array[0] = VT1;
  7799. Array[1] = VT2;
  7800. Array[2] = VT3;
  7801. Array[3] = VT4;
  7802. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
  7803. VTListMap.InsertNode(Result, IP);
  7804. }
  7805. return Result->getSDVTList();
  7806. }
  7807. SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
  7808. unsigned NumVTs = VTs.size();
  7809. FoldingSetNodeID ID;
  7810. ID.AddInteger(NumVTs);
  7811. for (unsigned index = 0; index < NumVTs; index++) {
  7812. ID.AddInteger(VTs[index].getRawBits());
  7813. }
  7814. void *IP = nullptr;
  7815. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  7816. if (!Result) {
  7817. EVT *Array = Allocator.Allocate<EVT>(NumVTs);
  7818. llvm::copy(VTs, Array);
  7819. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
  7820. VTListMap.InsertNode(Result, IP);
  7821. }
  7822. return Result->getSDVTList();
  7823. }
  7824. /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
  7825. /// specified operands. If the resultant node already exists in the DAG,
  7826. /// this does not modify the specified node, instead it returns the node that
  7827. /// already exists. If the resultant node does not exist in the DAG, the
  7828. /// input node is returned. As a degenerate case, if you specify the same
  7829. /// input operands as the node already has, the input node is returned.
  7830. SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
  7831. assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
  7832. // Check to see if there is no change.
  7833. if (Op == N->getOperand(0)) return N;
  7834. // See if the modified node already exists.
  7835. void *InsertPos = nullptr;
  7836. if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
  7837. return Existing;
  7838. // Nope it doesn't. Remove the node from its current place in the maps.
  7839. if (InsertPos)
  7840. if (!RemoveNodeFromCSEMaps(N))
  7841. InsertPos = nullptr;
  7842. // Now we update the operands.
  7843. N->OperandList[0].set(Op);
  7844. updateDivergence(N);
  7845. // If this gets put into a CSE map, add it.
  7846. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  7847. return N;
  7848. }
  7849. SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
  7850. assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
  7851. // Check to see if there is no change.
  7852. if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
  7853. return N; // No operands changed, just return the input node.
  7854. // See if the modified node already exists.
  7855. void *InsertPos = nullptr;
  7856. if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
  7857. return Existing;
  7858. // Nope it doesn't. Remove the node from its current place in the maps.
  7859. if (InsertPos)
  7860. if (!RemoveNodeFromCSEMaps(N))
  7861. InsertPos = nullptr;
  7862. // Now we update the operands.
  7863. if (N->OperandList[0] != Op1)
  7864. N->OperandList[0].set(Op1);
  7865. if (N->OperandList[1] != Op2)
  7866. N->OperandList[1].set(Op2);
  7867. updateDivergence(N);
  7868. // If this gets put into a CSE map, add it.
  7869. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  7870. return N;
  7871. }
  7872. SDNode *SelectionDAG::
  7873. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
  7874. SDValue Ops[] = { Op1, Op2, Op3 };
  7875. return UpdateNodeOperands(N, Ops);
  7876. }
  7877. SDNode *SelectionDAG::
  7878. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
  7879. SDValue Op3, SDValue Op4) {
  7880. SDValue Ops[] = { Op1, Op2, Op3, Op4 };
  7881. return UpdateNodeOperands(N, Ops);
  7882. }
  7883. SDNode *SelectionDAG::
  7884. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
  7885. SDValue Op3, SDValue Op4, SDValue Op5) {
  7886. SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
  7887. return UpdateNodeOperands(N, Ops);
  7888. }
  7889. SDNode *SelectionDAG::
  7890. UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
  7891. unsigned NumOps = Ops.size();
  7892. assert(N->getNumOperands() == NumOps &&
  7893. "Update with wrong number of operands");
  7894. // If no operands changed just return the input node.
  7895. if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
  7896. return N;
  7897. // See if the modified node already exists.
  7898. void *InsertPos = nullptr;
  7899. if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
  7900. return Existing;
  7901. // Nope it doesn't. Remove the node from its current place in the maps.
  7902. if (InsertPos)
  7903. if (!RemoveNodeFromCSEMaps(N))
  7904. InsertPos = nullptr;
  7905. // Now we update the operands.
  7906. for (unsigned i = 0; i != NumOps; ++i)
  7907. if (N->OperandList[i] != Ops[i])
  7908. N->OperandList[i].set(Ops[i]);
  7909. updateDivergence(N);
  7910. // If this gets put into a CSE map, add it.
  7911. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  7912. return N;
  7913. }
  7914. /// DropOperands - Release the operands and set this node to have
  7915. /// zero operands.
  7916. void SDNode::DropOperands() {
  7917. // Unlike the code in MorphNodeTo that does this, we don't need to
  7918. // watch for dead nodes here.
  7919. for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
  7920. SDUse &Use = *I++;
  7921. Use.set(SDValue());
  7922. }
  7923. }
  7924. void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
  7925. ArrayRef<MachineMemOperand *> NewMemRefs) {
  7926. if (NewMemRefs.empty()) {
  7927. N->clearMemRefs();
  7928. return;
  7929. }
  7930. // Check if we can avoid allocating by storing a single reference directly.
  7931. if (NewMemRefs.size() == 1) {
  7932. N->MemRefs = NewMemRefs[0];
  7933. N->NumMemRefs = 1;
  7934. return;
  7935. }
  7936. MachineMemOperand **MemRefsBuffer =
  7937. Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
  7938. llvm::copy(NewMemRefs, MemRefsBuffer);
  7939. N->MemRefs = MemRefsBuffer;
  7940. N->NumMemRefs = static_cast<int>(NewMemRefs.size());
  7941. }
  7942. /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
  7943. /// machine opcode.
  7944. ///
  7945. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7946. EVT VT) {
  7947. SDVTList VTs = getVTList(VT);
  7948. return SelectNodeTo(N, MachineOpc, VTs, None);
  7949. }
  7950. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7951. EVT VT, SDValue Op1) {
  7952. SDVTList VTs = getVTList(VT);
  7953. SDValue Ops[] = { Op1 };
  7954. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  7955. }
  7956. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7957. EVT VT, SDValue Op1,
  7958. SDValue Op2) {
  7959. SDVTList VTs = getVTList(VT);
  7960. SDValue Ops[] = { Op1, Op2 };
  7961. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  7962. }
  7963. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7964. EVT VT, SDValue Op1,
  7965. SDValue Op2, SDValue Op3) {
  7966. SDVTList VTs = getVTList(VT);
  7967. SDValue Ops[] = { Op1, Op2, Op3 };
  7968. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  7969. }
  7970. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7971. EVT VT, ArrayRef<SDValue> Ops) {
  7972. SDVTList VTs = getVTList(VT);
  7973. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  7974. }
  7975. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7976. EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
  7977. SDVTList VTs = getVTList(VT1, VT2);
  7978. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  7979. }
  7980. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7981. EVT VT1, EVT VT2) {
  7982. SDVTList VTs = getVTList(VT1, VT2);
  7983. return SelectNodeTo(N, MachineOpc, VTs, None);
  7984. }
  7985. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7986. EVT VT1, EVT VT2, EVT VT3,
  7987. ArrayRef<SDValue> Ops) {
  7988. SDVTList VTs = getVTList(VT1, VT2, VT3);
  7989. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  7990. }
  7991. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7992. EVT VT1, EVT VT2,
  7993. SDValue Op1, SDValue Op2) {
  7994. SDVTList VTs = getVTList(VT1, VT2);
  7995. SDValue Ops[] = { Op1, Op2 };
  7996. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  7997. }
  7998. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  7999. SDVTList VTs,ArrayRef<SDValue> Ops) {
  8000. SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
  8001. // Reset the NodeID to -1.
  8002. New->setNodeId(-1);
  8003. if (New != N) {
  8004. ReplaceAllUsesWith(N, New);
  8005. RemoveDeadNode(N);
  8006. }
  8007. return New;
  8008. }
  8009. /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
  8010. /// the line number information on the merged node since it is not possible to
  8011. /// preserve the information that operation is associated with multiple lines.
  8012. /// This will make the debugger working better at -O0, were there is a higher
  8013. /// probability having other instructions associated with that line.
  8014. ///
  8015. /// For IROrder, we keep the smaller of the two
  8016. SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
  8017. DebugLoc NLoc = N->getDebugLoc();
  8018. if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
  8019. N->setDebugLoc(DebugLoc());
  8020. }
  8021. unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
  8022. N->setIROrder(Order);
  8023. return N;
  8024. }
  8025. /// MorphNodeTo - This *mutates* the specified node to have the specified
  8026. /// return type, opcode, and operands.
  8027. ///
  8028. /// Note that MorphNodeTo returns the resultant node. If there is already a
  8029. /// node of the specified opcode and operands, it returns that node instead of
  8030. /// the current one. Note that the SDLoc need not be the same.
  8031. ///
  8032. /// Using MorphNodeTo is faster than creating a new node and swapping it in
  8033. /// with ReplaceAllUsesWith both because it often avoids allocating a new
  8034. /// node, and because it doesn't require CSE recalculation for any of
  8035. /// the node's users.
  8036. ///
  8037. /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
  8038. /// As a consequence it isn't appropriate to use from within the DAG combiner or
  8039. /// the legalizer which maintain worklists that would need to be updated when
  8040. /// deleting things.
  8041. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  8042. SDVTList VTs, ArrayRef<SDValue> Ops) {
  8043. // If an identical node already exists, use it.
  8044. void *IP = nullptr;
  8045. if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
  8046. FoldingSetNodeID ID;
  8047. AddNodeIDNode(ID, Opc, VTs, Ops);
  8048. if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
  8049. return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
  8050. }
  8051. if (!RemoveNodeFromCSEMaps(N))
  8052. IP = nullptr;
  8053. // Start the morphing.
  8054. N->NodeType = Opc;
  8055. N->ValueList = VTs.VTs;
  8056. N->NumValues = VTs.NumVTs;
  8057. // Clear the operands list, updating used nodes to remove this from their
  8058. // use list. Keep track of any operands that become dead as a result.
  8059. SmallPtrSet<SDNode*, 16> DeadNodeSet;
  8060. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  8061. SDUse &Use = *I++;
  8062. SDNode *Used = Use.getNode();
  8063. Use.set(SDValue());
  8064. if (Used->use_empty())
  8065. DeadNodeSet.insert(Used);
  8066. }
  8067. // For MachineNode, initialize the memory references information.
  8068. if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
  8069. MN->clearMemRefs();
  8070. // Swap for an appropriately sized array from the recycler.
  8071. removeOperands(N);
  8072. createOperands(N, Ops);
  8073. // Delete any nodes that are still dead after adding the uses for the
  8074. // new operands.
  8075. if (!DeadNodeSet.empty()) {
  8076. SmallVector<SDNode *, 16> DeadNodes;
  8077. for (SDNode *N : DeadNodeSet)
  8078. if (N->use_empty())
  8079. DeadNodes.push_back(N);
  8080. RemoveDeadNodes(DeadNodes);
  8081. }
  8082. if (IP)
  8083. CSEMap.InsertNode(N, IP); // Memoize the new node.
  8084. return N;
  8085. }
  8086. SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
  8087. unsigned OrigOpc = Node->getOpcode();
  8088. unsigned NewOpc;
  8089. switch (OrigOpc) {
  8090. default:
  8091. llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
  8092. #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  8093. case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
  8094. #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
  8095. case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
  8096. #include "llvm/IR/ConstrainedOps.def"
  8097. }
  8098. assert(Node->getNumValues() == 2 && "Unexpected number of results!");
  8099. // We're taking this node out of the chain, so we need to re-link things.
  8100. SDValue InputChain = Node->getOperand(0);
  8101. SDValue OutputChain = SDValue(Node, 1);
  8102. ReplaceAllUsesOfValueWith(OutputChain, InputChain);
  8103. SmallVector<SDValue, 3> Ops;
  8104. for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
  8105. Ops.push_back(Node->getOperand(i));
  8106. SDVTList VTs = getVTList(Node->getValueType(0));
  8107. SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
  8108. // MorphNodeTo can operate in two ways: if an existing node with the
  8109. // specified operands exists, it can just return it. Otherwise, it
  8110. // updates the node in place to have the requested operands.
  8111. if (Res == Node) {
  8112. // If we updated the node in place, reset the node ID. To the isel,
  8113. // this should be just like a newly allocated machine node.
  8114. Res->setNodeId(-1);
  8115. } else {
  8116. ReplaceAllUsesWith(Node, Res);
  8117. RemoveDeadNode(Node);
  8118. }
  8119. return Res;
  8120. }
  8121. /// getMachineNode - These are used for target selectors to create a new node
  8122. /// with specified return type(s), MachineInstr opcode, and operands.
  8123. ///
  8124. /// Note that getMachineNode returns the resultant node. If there is already a
  8125. /// node of the specified opcode and operands, it returns that node instead of
  8126. /// the current one.
  8127. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8128. EVT VT) {
  8129. SDVTList VTs = getVTList(VT);
  8130. return getMachineNode(Opcode, dl, VTs, None);
  8131. }
  8132. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8133. EVT VT, SDValue Op1) {
  8134. SDVTList VTs = getVTList(VT);
  8135. SDValue Ops[] = { Op1 };
  8136. return getMachineNode(Opcode, dl, VTs, Ops);
  8137. }
  8138. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8139. EVT VT, SDValue Op1, SDValue Op2) {
  8140. SDVTList VTs = getVTList(VT);
  8141. SDValue Ops[] = { Op1, Op2 };
  8142. return getMachineNode(Opcode, dl, VTs, Ops);
  8143. }
  8144. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8145. EVT VT, SDValue Op1, SDValue Op2,
  8146. SDValue Op3) {
  8147. SDVTList VTs = getVTList(VT);
  8148. SDValue Ops[] = { Op1, Op2, Op3 };
  8149. return getMachineNode(Opcode, dl, VTs, Ops);
  8150. }
  8151. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8152. EVT VT, ArrayRef<SDValue> Ops) {
  8153. SDVTList VTs = getVTList(VT);
  8154. return getMachineNode(Opcode, dl, VTs, Ops);
  8155. }
  8156. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8157. EVT VT1, EVT VT2, SDValue Op1,
  8158. SDValue Op2) {
  8159. SDVTList VTs = getVTList(VT1, VT2);
  8160. SDValue Ops[] = { Op1, Op2 };
  8161. return getMachineNode(Opcode, dl, VTs, Ops);
  8162. }
  8163. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8164. EVT VT1, EVT VT2, SDValue Op1,
  8165. SDValue Op2, SDValue Op3) {
  8166. SDVTList VTs = getVTList(VT1, VT2);
  8167. SDValue Ops[] = { Op1, Op2, Op3 };
  8168. return getMachineNode(Opcode, dl, VTs, Ops);
  8169. }
  8170. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8171. EVT VT1, EVT VT2,
  8172. ArrayRef<SDValue> Ops) {
  8173. SDVTList VTs = getVTList(VT1, VT2);
  8174. return getMachineNode(Opcode, dl, VTs, Ops);
  8175. }
  8176. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8177. EVT VT1, EVT VT2, EVT VT3,
  8178. SDValue Op1, SDValue Op2) {
  8179. SDVTList VTs = getVTList(VT1, VT2, VT3);
  8180. SDValue Ops[] = { Op1, Op2 };
  8181. return getMachineNode(Opcode, dl, VTs, Ops);
  8182. }
  8183. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8184. EVT VT1, EVT VT2, EVT VT3,
  8185. SDValue Op1, SDValue Op2,
  8186. SDValue Op3) {
  8187. SDVTList VTs = getVTList(VT1, VT2, VT3);
  8188. SDValue Ops[] = { Op1, Op2, Op3 };
  8189. return getMachineNode(Opcode, dl, VTs, Ops);
  8190. }
  8191. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8192. EVT VT1, EVT VT2, EVT VT3,
  8193. ArrayRef<SDValue> Ops) {
  8194. SDVTList VTs = getVTList(VT1, VT2, VT3);
  8195. return getMachineNode(Opcode, dl, VTs, Ops);
  8196. }
  8197. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  8198. ArrayRef<EVT> ResultTys,
  8199. ArrayRef<SDValue> Ops) {
  8200. SDVTList VTs = getVTList(ResultTys);
  8201. return getMachineNode(Opcode, dl, VTs, Ops);
  8202. }
  8203. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
  8204. SDVTList VTs,
  8205. ArrayRef<SDValue> Ops) {
  8206. bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
  8207. MachineSDNode *N;
  8208. void *IP = nullptr;
  8209. if (DoCSE) {
  8210. FoldingSetNodeID ID;
  8211. AddNodeIDNode(ID, ~Opcode, VTs, Ops);
  8212. IP = nullptr;
  8213. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  8214. return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
  8215. }
  8216. }
  8217. // Allocate a new MachineSDNode.
  8218. N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  8219. createOperands(N, Ops);
  8220. if (DoCSE)
  8221. CSEMap.InsertNode(N, IP);
  8222. InsertNode(N);
  8223. NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
  8224. return N;
  8225. }
  8226. /// getTargetExtractSubreg - A convenience function for creating
  8227. /// TargetOpcode::EXTRACT_SUBREG nodes.
  8228. SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
  8229. SDValue Operand) {
  8230. SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
  8231. SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
  8232. VT, Operand, SRIdxVal);
  8233. return SDValue(Subreg, 0);
  8234. }
  8235. /// getTargetInsertSubreg - A convenience function for creating
  8236. /// TargetOpcode::INSERT_SUBREG nodes.
  8237. SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
  8238. SDValue Operand, SDValue Subreg) {
  8239. SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
  8240. SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
  8241. VT, Operand, Subreg, SRIdxVal);
  8242. return SDValue(Result, 0);
  8243. }
  8244. /// getNodeIfExists - Get the specified node if it's already available, or
  8245. /// else return NULL.
  8246. SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
  8247. ArrayRef<SDValue> Ops) {
  8248. SDNodeFlags Flags;
  8249. if (Inserter)
  8250. Flags = Inserter->getFlags();
  8251. return getNodeIfExists(Opcode, VTList, Ops, Flags);
  8252. }
  8253. SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
  8254. ArrayRef<SDValue> Ops,
  8255. const SDNodeFlags Flags) {
  8256. if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
  8257. FoldingSetNodeID ID;
  8258. AddNodeIDNode(ID, Opcode, VTList, Ops);
  8259. void *IP = nullptr;
  8260. if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
  8261. E->intersectFlagsWith(Flags);
  8262. return E;
  8263. }
  8264. }
  8265. return nullptr;
  8266. }
  8267. /// doesNodeExist - Check if a node exists without modifying its flags.
  8268. bool SelectionDAG::doesNodeExist(unsigned Opcode, SDVTList VTList,
  8269. ArrayRef<SDValue> Ops) {
  8270. if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
  8271. FoldingSetNodeID ID;
  8272. AddNodeIDNode(ID, Opcode, VTList, Ops);
  8273. void *IP = nullptr;
  8274. if (FindNodeOrInsertPos(ID, SDLoc(), IP))
  8275. return true;
  8276. }
  8277. return false;
  8278. }
  8279. /// getDbgValue - Creates a SDDbgValue node.
  8280. ///
  8281. /// SDNode
  8282. SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
  8283. SDNode *N, unsigned R, bool IsIndirect,
  8284. const DebugLoc &DL, unsigned O) {
  8285. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  8286. "Expected inlined-at fields to agree");
  8287. return new (DbgInfo->getAlloc())
  8288. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromNode(N, R),
  8289. {}, IsIndirect, DL, O,
  8290. /*IsVariadic=*/false);
  8291. }
  8292. /// Constant
  8293. SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
  8294. DIExpression *Expr,
  8295. const Value *C,
  8296. const DebugLoc &DL, unsigned O) {
  8297. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  8298. "Expected inlined-at fields to agree");
  8299. return new (DbgInfo->getAlloc())
  8300. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromConst(C), {},
  8301. /*IsIndirect=*/false, DL, O,
  8302. /*IsVariadic=*/false);
  8303. }
  8304. /// FrameIndex
  8305. SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
  8306. DIExpression *Expr, unsigned FI,
  8307. bool IsIndirect,
  8308. const DebugLoc &DL,
  8309. unsigned O) {
  8310. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  8311. "Expected inlined-at fields to agree");
  8312. return getFrameIndexDbgValue(Var, Expr, FI, {}, IsIndirect, DL, O);
  8313. }
  8314. /// FrameIndex with dependencies
  8315. SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
  8316. DIExpression *Expr, unsigned FI,
  8317. ArrayRef<SDNode *> Dependencies,
  8318. bool IsIndirect,
  8319. const DebugLoc &DL,
  8320. unsigned O) {
  8321. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  8322. "Expected inlined-at fields to agree");
  8323. return new (DbgInfo->getAlloc())
  8324. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromFrameIdx(FI),
  8325. Dependencies, IsIndirect, DL, O,
  8326. /*IsVariadic=*/false);
  8327. }
  8328. /// VReg
  8329. SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var, DIExpression *Expr,
  8330. unsigned VReg, bool IsIndirect,
  8331. const DebugLoc &DL, unsigned O) {
  8332. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  8333. "Expected inlined-at fields to agree");
  8334. return new (DbgInfo->getAlloc())
  8335. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, SDDbgOperand::fromVReg(VReg),
  8336. {}, IsIndirect, DL, O,
  8337. /*IsVariadic=*/false);
  8338. }
  8339. SDDbgValue *SelectionDAG::getDbgValueList(DIVariable *Var, DIExpression *Expr,
  8340. ArrayRef<SDDbgOperand> Locs,
  8341. ArrayRef<SDNode *> Dependencies,
  8342. bool IsIndirect, const DebugLoc &DL,
  8343. unsigned O, bool IsVariadic) {
  8344. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  8345. "Expected inlined-at fields to agree");
  8346. return new (DbgInfo->getAlloc())
  8347. SDDbgValue(DbgInfo->getAlloc(), Var, Expr, Locs, Dependencies, IsIndirect,
  8348. DL, O, IsVariadic);
  8349. }
  8350. void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
  8351. unsigned OffsetInBits, unsigned SizeInBits,
  8352. bool InvalidateDbg) {
  8353. SDNode *FromNode = From.getNode();
  8354. SDNode *ToNode = To.getNode();
  8355. assert(FromNode && ToNode && "Can't modify dbg values");
  8356. // PR35338
  8357. // TODO: assert(From != To && "Redundant dbg value transfer");
  8358. // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
  8359. if (From == To || FromNode == ToNode)
  8360. return;
  8361. if (!FromNode->getHasDebugValue())
  8362. return;
  8363. SDDbgOperand FromLocOp =
  8364. SDDbgOperand::fromNode(From.getNode(), From.getResNo());
  8365. SDDbgOperand ToLocOp = SDDbgOperand::fromNode(To.getNode(), To.getResNo());
  8366. SmallVector<SDDbgValue *, 2> ClonedDVs;
  8367. for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
  8368. if (Dbg->isInvalidated())
  8369. continue;
  8370. // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
  8371. // Create a new location ops vector that is equal to the old vector, but
  8372. // with each instance of FromLocOp replaced with ToLocOp.
  8373. bool Changed = false;
  8374. auto NewLocOps = Dbg->copyLocationOps();
  8375. std::replace_if(
  8376. NewLocOps.begin(), NewLocOps.end(),
  8377. [&Changed, FromLocOp](const SDDbgOperand &Op) {
  8378. bool Match = Op == FromLocOp;
  8379. Changed |= Match;
  8380. return Match;
  8381. },
  8382. ToLocOp);
  8383. // Ignore this SDDbgValue if we didn't find a matching location.
  8384. if (!Changed)
  8385. continue;
  8386. DIVariable *Var = Dbg->getVariable();
  8387. auto *Expr = Dbg->getExpression();
  8388. // If a fragment is requested, update the expression.
  8389. if (SizeInBits) {
  8390. // When splitting a larger (e.g., sign-extended) value whose
  8391. // lower bits are described with an SDDbgValue, do not attempt
  8392. // to transfer the SDDbgValue to the upper bits.
  8393. if (auto FI = Expr->getFragmentInfo())
  8394. if (OffsetInBits + SizeInBits > FI->SizeInBits)
  8395. continue;
  8396. auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
  8397. SizeInBits);
  8398. if (!Fragment)
  8399. continue;
  8400. Expr = *Fragment;
  8401. }
  8402. auto AdditionalDependencies = Dbg->getAdditionalDependencies();
  8403. // Clone the SDDbgValue and move it to To.
  8404. SDDbgValue *Clone = getDbgValueList(
  8405. Var, Expr, NewLocOps, AdditionalDependencies, Dbg->isIndirect(),
  8406. Dbg->getDebugLoc(), std::max(ToNode->getIROrder(), Dbg->getOrder()),
  8407. Dbg->isVariadic());
  8408. ClonedDVs.push_back(Clone);
  8409. if (InvalidateDbg) {
  8410. // Invalidate value and indicate the SDDbgValue should not be emitted.
  8411. Dbg->setIsInvalidated();
  8412. Dbg->setIsEmitted();
  8413. }
  8414. }
  8415. for (SDDbgValue *Dbg : ClonedDVs) {
  8416. assert(is_contained(Dbg->getSDNodes(), ToNode) &&
  8417. "Transferred DbgValues should depend on the new SDNode");
  8418. AddDbgValue(Dbg, false);
  8419. }
  8420. }
  8421. void SelectionDAG::salvageDebugInfo(SDNode &N) {
  8422. if (!N.getHasDebugValue())
  8423. return;
  8424. SmallVector<SDDbgValue *, 2> ClonedDVs;
  8425. for (auto DV : GetDbgValues(&N)) {
  8426. if (DV->isInvalidated())
  8427. continue;
  8428. switch (N.getOpcode()) {
  8429. default:
  8430. break;
  8431. case ISD::ADD:
  8432. SDValue N0 = N.getOperand(0);
  8433. SDValue N1 = N.getOperand(1);
  8434. if (!isConstantIntBuildVectorOrConstantInt(N0) &&
  8435. isConstantIntBuildVectorOrConstantInt(N1)) {
  8436. uint64_t Offset = N.getConstantOperandVal(1);
  8437. // Rewrite an ADD constant node into a DIExpression. Since we are
  8438. // performing arithmetic to compute the variable's *value* in the
  8439. // DIExpression, we need to mark the expression with a
  8440. // DW_OP_stack_value.
  8441. auto *DIExpr = DV->getExpression();
  8442. auto NewLocOps = DV->copyLocationOps();
  8443. bool Changed = false;
  8444. for (size_t i = 0; i < NewLocOps.size(); ++i) {
  8445. // We're not given a ResNo to compare against because the whole
  8446. // node is going away. We know that any ISD::ADD only has one
  8447. // result, so we can assume any node match is using the result.
  8448. if (NewLocOps[i].getKind() != SDDbgOperand::SDNODE ||
  8449. NewLocOps[i].getSDNode() != &N)
  8450. continue;
  8451. NewLocOps[i] = SDDbgOperand::fromNode(N0.getNode(), N0.getResNo());
  8452. SmallVector<uint64_t, 3> ExprOps;
  8453. DIExpression::appendOffset(ExprOps, Offset);
  8454. DIExpr = DIExpression::appendOpsToArg(DIExpr, ExprOps, i, true);
  8455. Changed = true;
  8456. }
  8457. (void)Changed;
  8458. assert(Changed && "Salvage target doesn't use N");
  8459. auto AdditionalDependencies = DV->getAdditionalDependencies();
  8460. SDDbgValue *Clone = getDbgValueList(DV->getVariable(), DIExpr,
  8461. NewLocOps, AdditionalDependencies,
  8462. DV->isIndirect(), DV->getDebugLoc(),
  8463. DV->getOrder(), DV->isVariadic());
  8464. ClonedDVs.push_back(Clone);
  8465. DV->setIsInvalidated();
  8466. DV->setIsEmitted();
  8467. LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
  8468. N0.getNode()->dumprFull(this);
  8469. dbgs() << " into " << *DIExpr << '\n');
  8470. }
  8471. }
  8472. }
  8473. for (SDDbgValue *Dbg : ClonedDVs) {
  8474. assert(!Dbg->getSDNodes().empty() &&
  8475. "Salvaged DbgValue should depend on a new SDNode");
  8476. AddDbgValue(Dbg, false);
  8477. }
  8478. }
  8479. /// Creates a SDDbgLabel node.
  8480. SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
  8481. const DebugLoc &DL, unsigned O) {
  8482. assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
  8483. "Expected inlined-at fields to agree");
  8484. return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
  8485. }
  8486. namespace {
  8487. /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
  8488. /// pointed to by a use iterator is deleted, increment the use iterator
  8489. /// so that it doesn't dangle.
  8490. ///
  8491. class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
  8492. SDNode::use_iterator &UI;
  8493. SDNode::use_iterator &UE;
  8494. void NodeDeleted(SDNode *N, SDNode *E) override {
  8495. // Increment the iterator as needed.
  8496. while (UI != UE && N == *UI)
  8497. ++UI;
  8498. }
  8499. public:
  8500. RAUWUpdateListener(SelectionDAG &d,
  8501. SDNode::use_iterator &ui,
  8502. SDNode::use_iterator &ue)
  8503. : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
  8504. };
  8505. } // end anonymous namespace
  8506. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  8507. /// This can cause recursive merging of nodes in the DAG.
  8508. ///
  8509. /// This version assumes From has a single result value.
  8510. ///
  8511. void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
  8512. SDNode *From = FromN.getNode();
  8513. assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
  8514. "Cannot replace with this method!");
  8515. assert(From != To.getNode() && "Cannot replace uses of with self");
  8516. // Preserve Debug Values
  8517. transferDbgValues(FromN, To);
  8518. // Iterate over all the existing uses of From. New uses will be added
  8519. // to the beginning of the use list, which we avoid visiting.
  8520. // This specifically avoids visiting uses of From that arise while the
  8521. // replacement is happening, because any such uses would be the result
  8522. // of CSE: If an existing node looks like From after one of its operands
  8523. // is replaced by To, we don't want to replace of all its users with To
  8524. // too. See PR3018 for more info.
  8525. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  8526. RAUWUpdateListener Listener(*this, UI, UE);
  8527. while (UI != UE) {
  8528. SDNode *User = *UI;
  8529. // This node is about to morph, remove its old self from the CSE maps.
  8530. RemoveNodeFromCSEMaps(User);
  8531. // A user can appear in a use list multiple times, and when this
  8532. // happens the uses are usually next to each other in the list.
  8533. // To help reduce the number of CSE recomputations, process all
  8534. // the uses of this user that we can find this way.
  8535. do {
  8536. SDUse &Use = UI.getUse();
  8537. ++UI;
  8538. Use.set(To);
  8539. if (To->isDivergent() != From->isDivergent())
  8540. updateDivergence(User);
  8541. } while (UI != UE && *UI == User);
  8542. // Now that we have modified User, add it back to the CSE maps. If it
  8543. // already exists there, recursively merge the results together.
  8544. AddModifiedNodeToCSEMaps(User);
  8545. }
  8546. // If we just RAUW'd the root, take note.
  8547. if (FromN == getRoot())
  8548. setRoot(To);
  8549. }
  8550. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  8551. /// This can cause recursive merging of nodes in the DAG.
  8552. ///
  8553. /// This version assumes that for each value of From, there is a
  8554. /// corresponding value in To in the same position with the same type.
  8555. ///
  8556. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
  8557. #ifndef NDEBUG
  8558. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  8559. assert((!From->hasAnyUseOfValue(i) ||
  8560. From->getValueType(i) == To->getValueType(i)) &&
  8561. "Cannot use this version of ReplaceAllUsesWith!");
  8562. #endif
  8563. // Handle the trivial case.
  8564. if (From == To)
  8565. return;
  8566. // Preserve Debug Info. Only do this if there's a use.
  8567. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  8568. if (From->hasAnyUseOfValue(i)) {
  8569. assert((i < To->getNumValues()) && "Invalid To location");
  8570. transferDbgValues(SDValue(From, i), SDValue(To, i));
  8571. }
  8572. // Iterate over just the existing users of From. See the comments in
  8573. // the ReplaceAllUsesWith above.
  8574. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  8575. RAUWUpdateListener Listener(*this, UI, UE);
  8576. while (UI != UE) {
  8577. SDNode *User = *UI;
  8578. // This node is about to morph, remove its old self from the CSE maps.
  8579. RemoveNodeFromCSEMaps(User);
  8580. // A user can appear in a use list multiple times, and when this
  8581. // happens the uses are usually next to each other in the list.
  8582. // To help reduce the number of CSE recomputations, process all
  8583. // the uses of this user that we can find this way.
  8584. do {
  8585. SDUse &Use = UI.getUse();
  8586. ++UI;
  8587. Use.setNode(To);
  8588. if (To->isDivergent() != From->isDivergent())
  8589. updateDivergence(User);
  8590. } while (UI != UE && *UI == User);
  8591. // Now that we have modified User, add it back to the CSE maps. If it
  8592. // already exists there, recursively merge the results together.
  8593. AddModifiedNodeToCSEMaps(User);
  8594. }
  8595. // If we just RAUW'd the root, take note.
  8596. if (From == getRoot().getNode())
  8597. setRoot(SDValue(To, getRoot().getResNo()));
  8598. }
  8599. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  8600. /// This can cause recursive merging of nodes in the DAG.
  8601. ///
  8602. /// This version can replace From with any result values. To must match the
  8603. /// number and types of values returned by From.
  8604. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
  8605. if (From->getNumValues() == 1) // Handle the simple case efficiently.
  8606. return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
  8607. // Preserve Debug Info.
  8608. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  8609. transferDbgValues(SDValue(From, i), To[i]);
  8610. // Iterate over just the existing users of From. See the comments in
  8611. // the ReplaceAllUsesWith above.
  8612. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  8613. RAUWUpdateListener Listener(*this, UI, UE);
  8614. while (UI != UE) {
  8615. SDNode *User = *UI;
  8616. // This node is about to morph, remove its old self from the CSE maps.
  8617. RemoveNodeFromCSEMaps(User);
  8618. // A user can appear in a use list multiple times, and when this happens the
  8619. // uses are usually next to each other in the list. To help reduce the
  8620. // number of CSE and divergence recomputations, process all the uses of this
  8621. // user that we can find this way.
  8622. bool To_IsDivergent = false;
  8623. do {
  8624. SDUse &Use = UI.getUse();
  8625. const SDValue &ToOp = To[Use.getResNo()];
  8626. ++UI;
  8627. Use.set(ToOp);
  8628. To_IsDivergent |= ToOp->isDivergent();
  8629. } while (UI != UE && *UI == User);
  8630. if (To_IsDivergent != From->isDivergent())
  8631. updateDivergence(User);
  8632. // Now that we have modified User, add it back to the CSE maps. If it
  8633. // already exists there, recursively merge the results together.
  8634. AddModifiedNodeToCSEMaps(User);
  8635. }
  8636. // If we just RAUW'd the root, take note.
  8637. if (From == getRoot().getNode())
  8638. setRoot(SDValue(To[getRoot().getResNo()]));
  8639. }
  8640. /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
  8641. /// uses of other values produced by From.getNode() alone. The Deleted
  8642. /// vector is handled the same way as for ReplaceAllUsesWith.
  8643. void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
  8644. // Handle the really simple, really trivial case efficiently.
  8645. if (From == To) return;
  8646. // Handle the simple, trivial, case efficiently.
  8647. if (From.getNode()->getNumValues() == 1) {
  8648. ReplaceAllUsesWith(From, To);
  8649. return;
  8650. }
  8651. // Preserve Debug Info.
  8652. transferDbgValues(From, To);
  8653. // Iterate over just the existing users of From. See the comments in
  8654. // the ReplaceAllUsesWith above.
  8655. SDNode::use_iterator UI = From.getNode()->use_begin(),
  8656. UE = From.getNode()->use_end();
  8657. RAUWUpdateListener Listener(*this, UI, UE);
  8658. while (UI != UE) {
  8659. SDNode *User = *UI;
  8660. bool UserRemovedFromCSEMaps = false;
  8661. // A user can appear in a use list multiple times, and when this
  8662. // happens the uses are usually next to each other in the list.
  8663. // To help reduce the number of CSE recomputations, process all
  8664. // the uses of this user that we can find this way.
  8665. do {
  8666. SDUse &Use = UI.getUse();
  8667. // Skip uses of different values from the same node.
  8668. if (Use.getResNo() != From.getResNo()) {
  8669. ++UI;
  8670. continue;
  8671. }
  8672. // If this node hasn't been modified yet, it's still in the CSE maps,
  8673. // so remove its old self from the CSE maps.
  8674. if (!UserRemovedFromCSEMaps) {
  8675. RemoveNodeFromCSEMaps(User);
  8676. UserRemovedFromCSEMaps = true;
  8677. }
  8678. ++UI;
  8679. Use.set(To);
  8680. if (To->isDivergent() != From->isDivergent())
  8681. updateDivergence(User);
  8682. } while (UI != UE && *UI == User);
  8683. // We are iterating over all uses of the From node, so if a use
  8684. // doesn't use the specific value, no changes are made.
  8685. if (!UserRemovedFromCSEMaps)
  8686. continue;
  8687. // Now that we have modified User, add it back to the CSE maps. If it
  8688. // already exists there, recursively merge the results together.
  8689. AddModifiedNodeToCSEMaps(User);
  8690. }
  8691. // If we just RAUW'd the root, take note.
  8692. if (From == getRoot())
  8693. setRoot(To);
  8694. }
  8695. namespace {
  8696. /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
  8697. /// to record information about a use.
  8698. struct UseMemo {
  8699. SDNode *User;
  8700. unsigned Index;
  8701. SDUse *Use;
  8702. };
  8703. /// operator< - Sort Memos by User.
  8704. bool operator<(const UseMemo &L, const UseMemo &R) {
  8705. return (intptr_t)L.User < (intptr_t)R.User;
  8706. }
  8707. } // end anonymous namespace
  8708. bool SelectionDAG::calculateDivergence(SDNode *N) {
  8709. if (TLI->isSDNodeAlwaysUniform(N)) {
  8710. assert(!TLI->isSDNodeSourceOfDivergence(N, FLI, DA) &&
  8711. "Conflicting divergence information!");
  8712. return false;
  8713. }
  8714. if (TLI->isSDNodeSourceOfDivergence(N, FLI, DA))
  8715. return true;
  8716. for (auto &Op : N->ops()) {
  8717. if (Op.Val.getValueType() != MVT::Other && Op.getNode()->isDivergent())
  8718. return true;
  8719. }
  8720. return false;
  8721. }
  8722. void SelectionDAG::updateDivergence(SDNode *N) {
  8723. SmallVector<SDNode *, 16> Worklist(1, N);
  8724. do {
  8725. N = Worklist.pop_back_val();
  8726. bool IsDivergent = calculateDivergence(N);
  8727. if (N->SDNodeBits.IsDivergent != IsDivergent) {
  8728. N->SDNodeBits.IsDivergent = IsDivergent;
  8729. llvm::append_range(Worklist, N->uses());
  8730. }
  8731. } while (!Worklist.empty());
  8732. }
  8733. void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
  8734. DenseMap<SDNode *, unsigned> Degree;
  8735. Order.reserve(AllNodes.size());
  8736. for (auto &N : allnodes()) {
  8737. unsigned NOps = N.getNumOperands();
  8738. Degree[&N] = NOps;
  8739. if (0 == NOps)
  8740. Order.push_back(&N);
  8741. }
  8742. for (size_t I = 0; I != Order.size(); ++I) {
  8743. SDNode *N = Order[I];
  8744. for (auto U : N->uses()) {
  8745. unsigned &UnsortedOps = Degree[U];
  8746. if (0 == --UnsortedOps)
  8747. Order.push_back(U);
  8748. }
  8749. }
  8750. }
  8751. #ifndef NDEBUG
  8752. void SelectionDAG::VerifyDAGDivergence() {
  8753. std::vector<SDNode *> TopoOrder;
  8754. CreateTopologicalOrder(TopoOrder);
  8755. for (auto *N : TopoOrder) {
  8756. assert(calculateDivergence(N) == N->isDivergent() &&
  8757. "Divergence bit inconsistency detected");
  8758. }
  8759. }
  8760. #endif
  8761. /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
  8762. /// uses of other values produced by From.getNode() alone. The same value
  8763. /// may appear in both the From and To list. The Deleted vector is
  8764. /// handled the same way as for ReplaceAllUsesWith.
  8765. void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
  8766. const SDValue *To,
  8767. unsigned Num){
  8768. // Handle the simple, trivial case efficiently.
  8769. if (Num == 1)
  8770. return ReplaceAllUsesOfValueWith(*From, *To);
  8771. transferDbgValues(*From, *To);
  8772. // Read up all the uses and make records of them. This helps
  8773. // processing new uses that are introduced during the
  8774. // replacement process.
  8775. SmallVector<UseMemo, 4> Uses;
  8776. for (unsigned i = 0; i != Num; ++i) {
  8777. unsigned FromResNo = From[i].getResNo();
  8778. SDNode *FromNode = From[i].getNode();
  8779. for (SDNode::use_iterator UI = FromNode->use_begin(),
  8780. E = FromNode->use_end(); UI != E; ++UI) {
  8781. SDUse &Use = UI.getUse();
  8782. if (Use.getResNo() == FromResNo) {
  8783. UseMemo Memo = { *UI, i, &Use };
  8784. Uses.push_back(Memo);
  8785. }
  8786. }
  8787. }
  8788. // Sort the uses, so that all the uses from a given User are together.
  8789. llvm::sort(Uses);
  8790. for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
  8791. UseIndex != UseIndexEnd; ) {
  8792. // We know that this user uses some value of From. If it is the right
  8793. // value, update it.
  8794. SDNode *User = Uses[UseIndex].User;
  8795. // This node is about to morph, remove its old self from the CSE maps.
  8796. RemoveNodeFromCSEMaps(User);
  8797. // The Uses array is sorted, so all the uses for a given User
  8798. // are next to each other in the list.
  8799. // To help reduce the number of CSE recomputations, process all
  8800. // the uses of this user that we can find this way.
  8801. do {
  8802. unsigned i = Uses[UseIndex].Index;
  8803. SDUse &Use = *Uses[UseIndex].Use;
  8804. ++UseIndex;
  8805. Use.set(To[i]);
  8806. } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
  8807. // Now that we have modified User, add it back to the CSE maps. If it
  8808. // already exists there, recursively merge the results together.
  8809. AddModifiedNodeToCSEMaps(User);
  8810. }
  8811. }
  8812. /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
  8813. /// based on their topological order. It returns the maximum id and a vector
  8814. /// of the SDNodes* in assigned order by reference.
  8815. unsigned SelectionDAG::AssignTopologicalOrder() {
  8816. unsigned DAGSize = 0;
  8817. // SortedPos tracks the progress of the algorithm. Nodes before it are
  8818. // sorted, nodes after it are unsorted. When the algorithm completes
  8819. // it is at the end of the list.
  8820. allnodes_iterator SortedPos = allnodes_begin();
  8821. // Visit all the nodes. Move nodes with no operands to the front of
  8822. // the list immediately. Annotate nodes that do have operands with their
  8823. // operand count. Before we do this, the Node Id fields of the nodes
  8824. // may contain arbitrary values. After, the Node Id fields for nodes
  8825. // before SortedPos will contain the topological sort index, and the
  8826. // Node Id fields for nodes At SortedPos and after will contain the
  8827. // count of outstanding operands.
  8828. for (SDNode &N : llvm::make_early_inc_range(allnodes())) {
  8829. checkForCycles(&N, this);
  8830. unsigned Degree = N.getNumOperands();
  8831. if (Degree == 0) {
  8832. // A node with no uses, add it to the result array immediately.
  8833. N.setNodeId(DAGSize++);
  8834. allnodes_iterator Q(&N);
  8835. if (Q != SortedPos)
  8836. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
  8837. assert(SortedPos != AllNodes.end() && "Overran node list");
  8838. ++SortedPos;
  8839. } else {
  8840. // Temporarily use the Node Id as scratch space for the degree count.
  8841. N.setNodeId(Degree);
  8842. }
  8843. }
  8844. // Visit all the nodes. As we iterate, move nodes into sorted order,
  8845. // such that by the time the end is reached all nodes will be sorted.
  8846. for (SDNode &Node : allnodes()) {
  8847. SDNode *N = &Node;
  8848. checkForCycles(N, this);
  8849. // N is in sorted position, so all its uses have one less operand
  8850. // that needs to be sorted.
  8851. for (SDNode *P : N->uses()) {
  8852. unsigned Degree = P->getNodeId();
  8853. assert(Degree != 0 && "Invalid node degree");
  8854. --Degree;
  8855. if (Degree == 0) {
  8856. // All of P's operands are sorted, so P may sorted now.
  8857. P->setNodeId(DAGSize++);
  8858. if (P->getIterator() != SortedPos)
  8859. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
  8860. assert(SortedPos != AllNodes.end() && "Overran node list");
  8861. ++SortedPos;
  8862. } else {
  8863. // Update P's outstanding operand count.
  8864. P->setNodeId(Degree);
  8865. }
  8866. }
  8867. if (Node.getIterator() == SortedPos) {
  8868. #ifndef NDEBUG
  8869. allnodes_iterator I(N);
  8870. SDNode *S = &*++I;
  8871. dbgs() << "Overran sorted position:\n";
  8872. S->dumprFull(this); dbgs() << "\n";
  8873. dbgs() << "Checking if this is due to cycles\n";
  8874. checkForCycles(this, true);
  8875. #endif
  8876. llvm_unreachable(nullptr);
  8877. }
  8878. }
  8879. assert(SortedPos == AllNodes.end() &&
  8880. "Topological sort incomplete!");
  8881. assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
  8882. "First node in topological sort is not the entry token!");
  8883. assert(AllNodes.front().getNodeId() == 0 &&
  8884. "First node in topological sort has non-zero id!");
  8885. assert(AllNodes.front().getNumOperands() == 0 &&
  8886. "First node in topological sort has operands!");
  8887. assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
  8888. "Last node in topologic sort has unexpected id!");
  8889. assert(AllNodes.back().use_empty() &&
  8890. "Last node in topologic sort has users!");
  8891. assert(DAGSize == allnodes_size() && "Node count mismatch!");
  8892. return DAGSize;
  8893. }
  8894. /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
  8895. /// value is produced by SD.
  8896. void SelectionDAG::AddDbgValue(SDDbgValue *DB, bool isParameter) {
  8897. for (SDNode *SD : DB->getSDNodes()) {
  8898. if (!SD)
  8899. continue;
  8900. assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
  8901. SD->setHasDebugValue(true);
  8902. }
  8903. DbgInfo->add(DB, isParameter);
  8904. }
  8905. void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) { DbgInfo->add(DB); }
  8906. SDValue SelectionDAG::makeEquivalentMemoryOrdering(SDValue OldChain,
  8907. SDValue NewMemOpChain) {
  8908. assert(isa<MemSDNode>(NewMemOpChain) && "Expected a memop node");
  8909. assert(NewMemOpChain.getValueType() == MVT::Other && "Expected a token VT");
  8910. // The new memory operation must have the same position as the old load in
  8911. // terms of memory dependency. Create a TokenFactor for the old load and new
  8912. // memory operation and update uses of the old load's output chain to use that
  8913. // TokenFactor.
  8914. if (OldChain == NewMemOpChain || OldChain.use_empty())
  8915. return NewMemOpChain;
  8916. SDValue TokenFactor = getNode(ISD::TokenFactor, SDLoc(OldChain), MVT::Other,
  8917. OldChain, NewMemOpChain);
  8918. ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
  8919. UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewMemOpChain);
  8920. return TokenFactor;
  8921. }
  8922. SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
  8923. SDValue NewMemOp) {
  8924. assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
  8925. SDValue OldChain = SDValue(OldLoad, 1);
  8926. SDValue NewMemOpChain = NewMemOp.getValue(1);
  8927. return makeEquivalentMemoryOrdering(OldChain, NewMemOpChain);
  8928. }
  8929. SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
  8930. Function **OutFunction) {
  8931. assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
  8932. auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
  8933. auto *Module = MF->getFunction().getParent();
  8934. auto *Function = Module->getFunction(Symbol);
  8935. if (OutFunction != nullptr)
  8936. *OutFunction = Function;
  8937. if (Function != nullptr) {
  8938. auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
  8939. return getGlobalAddress(Function, SDLoc(Op), PtrTy);
  8940. }
  8941. std::string ErrorStr;
  8942. raw_string_ostream ErrorFormatter(ErrorStr);
  8943. ErrorFormatter << "Undefined external symbol ";
  8944. ErrorFormatter << '"' << Symbol << '"';
  8945. report_fatal_error(Twine(ErrorFormatter.str()));
  8946. }
  8947. //===----------------------------------------------------------------------===//
  8948. // SDNode Class
  8949. //===----------------------------------------------------------------------===//
  8950. bool llvm::isNullConstant(SDValue V) {
  8951. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  8952. return Const != nullptr && Const->isZero();
  8953. }
  8954. bool llvm::isNullFPConstant(SDValue V) {
  8955. ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
  8956. return Const != nullptr && Const->isZero() && !Const->isNegative();
  8957. }
  8958. bool llvm::isAllOnesConstant(SDValue V) {
  8959. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  8960. return Const != nullptr && Const->isAllOnes();
  8961. }
  8962. bool llvm::isOneConstant(SDValue V) {
  8963. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  8964. return Const != nullptr && Const->isOne();
  8965. }
  8966. SDValue llvm::peekThroughBitcasts(SDValue V) {
  8967. while (V.getOpcode() == ISD::BITCAST)
  8968. V = V.getOperand(0);
  8969. return V;
  8970. }
  8971. SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
  8972. while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
  8973. V = V.getOperand(0);
  8974. return V;
  8975. }
  8976. SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
  8977. while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
  8978. V = V.getOperand(0);
  8979. return V;
  8980. }
  8981. bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
  8982. if (V.getOpcode() != ISD::XOR)
  8983. return false;
  8984. V = peekThroughBitcasts(V.getOperand(1));
  8985. unsigned NumBits = V.getScalarValueSizeInBits();
  8986. ConstantSDNode *C =
  8987. isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
  8988. return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
  8989. }
  8990. ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
  8991. bool AllowTruncation) {
  8992. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
  8993. return CN;
  8994. // SplatVectors can truncate their operands. Ignore that case here unless
  8995. // AllowTruncation is set.
  8996. if (N->getOpcode() == ISD::SPLAT_VECTOR) {
  8997. EVT VecEltVT = N->getValueType(0).getVectorElementType();
  8998. if (auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
  8999. EVT CVT = CN->getValueType(0);
  9000. assert(CVT.bitsGE(VecEltVT) && "Illegal splat_vector element extension");
  9001. if (AllowTruncation || CVT == VecEltVT)
  9002. return CN;
  9003. }
  9004. }
  9005. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  9006. BitVector UndefElements;
  9007. ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
  9008. // BuildVectors can truncate their operands. Ignore that case here unless
  9009. // AllowTruncation is set.
  9010. if (CN && (UndefElements.none() || AllowUndefs)) {
  9011. EVT CVT = CN->getValueType(0);
  9012. EVT NSVT = N.getValueType().getScalarType();
  9013. assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
  9014. if (AllowTruncation || (CVT == NSVT))
  9015. return CN;
  9016. }
  9017. }
  9018. return nullptr;
  9019. }
  9020. ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
  9021. bool AllowUndefs,
  9022. bool AllowTruncation) {
  9023. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
  9024. return CN;
  9025. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  9026. BitVector UndefElements;
  9027. ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
  9028. // BuildVectors can truncate their operands. Ignore that case here unless
  9029. // AllowTruncation is set.
  9030. if (CN && (UndefElements.none() || AllowUndefs)) {
  9031. EVT CVT = CN->getValueType(0);
  9032. EVT NSVT = N.getValueType().getScalarType();
  9033. assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
  9034. if (AllowTruncation || (CVT == NSVT))
  9035. return CN;
  9036. }
  9037. }
  9038. return nullptr;
  9039. }
  9040. ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
  9041. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
  9042. return CN;
  9043. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  9044. BitVector UndefElements;
  9045. ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
  9046. if (CN && (UndefElements.none() || AllowUndefs))
  9047. return CN;
  9048. }
  9049. if (N.getOpcode() == ISD::SPLAT_VECTOR)
  9050. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N.getOperand(0)))
  9051. return CN;
  9052. return nullptr;
  9053. }
  9054. ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
  9055. const APInt &DemandedElts,
  9056. bool AllowUndefs) {
  9057. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
  9058. return CN;
  9059. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  9060. BitVector UndefElements;
  9061. ConstantFPSDNode *CN =
  9062. BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
  9063. if (CN && (UndefElements.none() || AllowUndefs))
  9064. return CN;
  9065. }
  9066. return nullptr;
  9067. }
  9068. bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
  9069. // TODO: may want to use peekThroughBitcast() here.
  9070. ConstantSDNode *C =
  9071. isConstOrConstSplat(N, AllowUndefs, /*AllowTruncation=*/true);
  9072. return C && C->isZero();
  9073. }
  9074. bool llvm::isOneOrOneSplat(SDValue N, bool AllowUndefs) {
  9075. // TODO: may want to use peekThroughBitcast() here.
  9076. unsigned BitWidth = N.getScalarValueSizeInBits();
  9077. ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
  9078. return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
  9079. }
  9080. bool llvm::isAllOnesOrAllOnesSplat(SDValue N, bool AllowUndefs) {
  9081. N = peekThroughBitcasts(N);
  9082. unsigned BitWidth = N.getScalarValueSizeInBits();
  9083. ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
  9084. return C && C->isAllOnes() && C->getValueSizeInBits(0) == BitWidth;
  9085. }
  9086. HandleSDNode::~HandleSDNode() {
  9087. DropOperands();
  9088. }
  9089. GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
  9090. const DebugLoc &DL,
  9091. const GlobalValue *GA, EVT VT,
  9092. int64_t o, unsigned TF)
  9093. : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
  9094. TheGlobal = GA;
  9095. }
  9096. AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
  9097. EVT VT, unsigned SrcAS,
  9098. unsigned DestAS)
  9099. : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
  9100. SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
  9101. MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
  9102. SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
  9103. : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
  9104. MemSDNodeBits.IsVolatile = MMO->isVolatile();
  9105. MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
  9106. MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
  9107. MemSDNodeBits.IsInvariant = MMO->isInvariant();
  9108. // We check here that the size of the memory operand fits within the size of
  9109. // the MMO. This is because the MMO might indicate only a possible address
  9110. // range instead of specifying the affected memory addresses precisely.
  9111. // TODO: Make MachineMemOperands aware of scalable vectors.
  9112. assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
  9113. "Size mismatch!");
  9114. }
  9115. /// Profile - Gather unique data for the node.
  9116. ///
  9117. void SDNode::Profile(FoldingSetNodeID &ID) const {
  9118. AddNodeIDNode(ID, this);
  9119. }
  9120. namespace {
  9121. struct EVTArray {
  9122. std::vector<EVT> VTs;
  9123. EVTArray() {
  9124. VTs.reserve(MVT::VALUETYPE_SIZE);
  9125. for (unsigned i = 0; i < MVT::VALUETYPE_SIZE; ++i)
  9126. VTs.push_back(MVT((MVT::SimpleValueType)i));
  9127. }
  9128. };
  9129. } // end anonymous namespace
  9130. static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
  9131. static ManagedStatic<EVTArray> SimpleVTArray;
  9132. static ManagedStatic<sys::SmartMutex<true>> VTMutex;
  9133. /// getValueTypeList - Return a pointer to the specified value type.
  9134. ///
  9135. const EVT *SDNode::getValueTypeList(EVT VT) {
  9136. if (VT.isExtended()) {
  9137. sys::SmartScopedLock<true> Lock(*VTMutex);
  9138. return &(*EVTs->insert(VT).first);
  9139. }
  9140. assert(VT.getSimpleVT() < MVT::VALUETYPE_SIZE && "Value type out of range!");
  9141. return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
  9142. }
  9143. /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
  9144. /// indicated value. This method ignores uses of other values defined by this
  9145. /// operation.
  9146. bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
  9147. assert(Value < getNumValues() && "Bad value!");
  9148. // TODO: Only iterate over uses of a given value of the node
  9149. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
  9150. if (UI.getUse().getResNo() == Value) {
  9151. if (NUses == 0)
  9152. return false;
  9153. --NUses;
  9154. }
  9155. }
  9156. // Found exactly the right number of uses?
  9157. return NUses == 0;
  9158. }
  9159. /// hasAnyUseOfValue - Return true if there are any use of the indicated
  9160. /// value. This method ignores uses of other values defined by this operation.
  9161. bool SDNode::hasAnyUseOfValue(unsigned Value) const {
  9162. assert(Value < getNumValues() && "Bad value!");
  9163. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
  9164. if (UI.getUse().getResNo() == Value)
  9165. return true;
  9166. return false;
  9167. }
  9168. /// isOnlyUserOf - Return true if this node is the only use of N.
  9169. bool SDNode::isOnlyUserOf(const SDNode *N) const {
  9170. bool Seen = false;
  9171. for (const SDNode *User : N->uses()) {
  9172. if (User == this)
  9173. Seen = true;
  9174. else
  9175. return false;
  9176. }
  9177. return Seen;
  9178. }
  9179. /// Return true if the only users of N are contained in Nodes.
  9180. bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
  9181. bool Seen = false;
  9182. for (const SDNode *User : N->uses()) {
  9183. if (llvm::is_contained(Nodes, User))
  9184. Seen = true;
  9185. else
  9186. return false;
  9187. }
  9188. return Seen;
  9189. }
  9190. /// isOperand - Return true if this node is an operand of N.
  9191. bool SDValue::isOperandOf(const SDNode *N) const {
  9192. return is_contained(N->op_values(), *this);
  9193. }
  9194. bool SDNode::isOperandOf(const SDNode *N) const {
  9195. return any_of(N->op_values(),
  9196. [this](SDValue Op) { return this == Op.getNode(); });
  9197. }
  9198. /// reachesChainWithoutSideEffects - Return true if this operand (which must
  9199. /// be a chain) reaches the specified operand without crossing any
  9200. /// side-effecting instructions on any chain path. In practice, this looks
  9201. /// through token factors and non-volatile loads. In order to remain efficient,
  9202. /// this only looks a couple of nodes in, it does not do an exhaustive search.
  9203. ///
  9204. /// Note that we only need to examine chains when we're searching for
  9205. /// side-effects; SelectionDAG requires that all side-effects are represented
  9206. /// by chains, even if another operand would force a specific ordering. This
  9207. /// constraint is necessary to allow transformations like splitting loads.
  9208. bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
  9209. unsigned Depth) const {
  9210. if (*this == Dest) return true;
  9211. // Don't search too deeply, we just want to be able to see through
  9212. // TokenFactor's etc.
  9213. if (Depth == 0) return false;
  9214. // If this is a token factor, all inputs to the TF happen in parallel.
  9215. if (getOpcode() == ISD::TokenFactor) {
  9216. // First, try a shallow search.
  9217. if (is_contained((*this)->ops(), Dest)) {
  9218. // We found the chain we want as an operand of this TokenFactor.
  9219. // Essentially, we reach the chain without side-effects if we could
  9220. // serialize the TokenFactor into a simple chain of operations with
  9221. // Dest as the last operation. This is automatically true if the
  9222. // chain has one use: there are no other ordering constraints.
  9223. // If the chain has more than one use, we give up: some other
  9224. // use of Dest might force a side-effect between Dest and the current
  9225. // node.
  9226. if (Dest.hasOneUse())
  9227. return true;
  9228. }
  9229. // Next, try a deep search: check whether every operand of the TokenFactor
  9230. // reaches Dest.
  9231. return llvm::all_of((*this)->ops(), [=](SDValue Op) {
  9232. return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
  9233. });
  9234. }
  9235. // Loads don't have side effects, look through them.
  9236. if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
  9237. if (Ld->isUnordered())
  9238. return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
  9239. }
  9240. return false;
  9241. }
  9242. bool SDNode::hasPredecessor(const SDNode *N) const {
  9243. SmallPtrSet<const SDNode *, 32> Visited;
  9244. SmallVector<const SDNode *, 16> Worklist;
  9245. Worklist.push_back(this);
  9246. return hasPredecessorHelper(N, Visited, Worklist);
  9247. }
  9248. void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
  9249. this->Flags.intersectWith(Flags);
  9250. }
  9251. SDValue
  9252. SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
  9253. ArrayRef<ISD::NodeType> CandidateBinOps,
  9254. bool AllowPartials) {
  9255. // The pattern must end in an extract from index 0.
  9256. if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  9257. !isNullConstant(Extract->getOperand(1)))
  9258. return SDValue();
  9259. // Match against one of the candidate binary ops.
  9260. SDValue Op = Extract->getOperand(0);
  9261. if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
  9262. return Op.getOpcode() == unsigned(BinOp);
  9263. }))
  9264. return SDValue();
  9265. // Floating-point reductions may require relaxed constraints on the final step
  9266. // of the reduction because they may reorder intermediate operations.
  9267. unsigned CandidateBinOp = Op.getOpcode();
  9268. if (Op.getValueType().isFloatingPoint()) {
  9269. SDNodeFlags Flags = Op->getFlags();
  9270. switch (CandidateBinOp) {
  9271. case ISD::FADD:
  9272. if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
  9273. return SDValue();
  9274. break;
  9275. default:
  9276. llvm_unreachable("Unhandled FP opcode for binop reduction");
  9277. }
  9278. }
  9279. // Matching failed - attempt to see if we did enough stages that a partial
  9280. // reduction from a subvector is possible.
  9281. auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
  9282. if (!AllowPartials || !Op)
  9283. return SDValue();
  9284. EVT OpVT = Op.getValueType();
  9285. EVT OpSVT = OpVT.getScalarType();
  9286. EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
  9287. if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
  9288. return SDValue();
  9289. BinOp = (ISD::NodeType)CandidateBinOp;
  9290. return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
  9291. getVectorIdxConstant(0, SDLoc(Op)));
  9292. };
  9293. // At each stage, we're looking for something that looks like:
  9294. // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
  9295. // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
  9296. // i32 undef, i32 undef, i32 undef, i32 undef>
  9297. // %a = binop <8 x i32> %op, %s
  9298. // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
  9299. // we expect something like:
  9300. // <4,5,6,7,u,u,u,u>
  9301. // <2,3,u,u,u,u,u,u>
  9302. // <1,u,u,u,u,u,u,u>
  9303. // While a partial reduction match would be:
  9304. // <2,3,u,u,u,u,u,u>
  9305. // <1,u,u,u,u,u,u,u>
  9306. unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
  9307. SDValue PrevOp;
  9308. for (unsigned i = 0; i < Stages; ++i) {
  9309. unsigned MaskEnd = (1 << i);
  9310. if (Op.getOpcode() != CandidateBinOp)
  9311. return PartialReduction(PrevOp, MaskEnd);
  9312. SDValue Op0 = Op.getOperand(0);
  9313. SDValue Op1 = Op.getOperand(1);
  9314. ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
  9315. if (Shuffle) {
  9316. Op = Op1;
  9317. } else {
  9318. Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
  9319. Op = Op0;
  9320. }
  9321. // The first operand of the shuffle should be the same as the other operand
  9322. // of the binop.
  9323. if (!Shuffle || Shuffle->getOperand(0) != Op)
  9324. return PartialReduction(PrevOp, MaskEnd);
  9325. // Verify the shuffle has the expected (at this stage of the pyramid) mask.
  9326. for (int Index = 0; Index < (int)MaskEnd; ++Index)
  9327. if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
  9328. return PartialReduction(PrevOp, MaskEnd);
  9329. PrevOp = Op;
  9330. }
  9331. // Handle subvector reductions, which tend to appear after the shuffle
  9332. // reduction stages.
  9333. while (Op.getOpcode() == CandidateBinOp) {
  9334. unsigned NumElts = Op.getValueType().getVectorNumElements();
  9335. SDValue Op0 = Op.getOperand(0);
  9336. SDValue Op1 = Op.getOperand(1);
  9337. if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
  9338. Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
  9339. Op0.getOperand(0) != Op1.getOperand(0))
  9340. break;
  9341. SDValue Src = Op0.getOperand(0);
  9342. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  9343. if (NumSrcElts != (2 * NumElts))
  9344. break;
  9345. if (!(Op0.getConstantOperandAPInt(1) == 0 &&
  9346. Op1.getConstantOperandAPInt(1) == NumElts) &&
  9347. !(Op1.getConstantOperandAPInt(1) == 0 &&
  9348. Op0.getConstantOperandAPInt(1) == NumElts))
  9349. break;
  9350. Op = Src;
  9351. }
  9352. BinOp = (ISD::NodeType)CandidateBinOp;
  9353. return Op;
  9354. }
  9355. SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
  9356. assert(N->getNumValues() == 1 &&
  9357. "Can't unroll a vector with multiple results!");
  9358. EVT VT = N->getValueType(0);
  9359. unsigned NE = VT.getVectorNumElements();
  9360. EVT EltVT = VT.getVectorElementType();
  9361. SDLoc dl(N);
  9362. SmallVector<SDValue, 8> Scalars;
  9363. SmallVector<SDValue, 4> Operands(N->getNumOperands());
  9364. // If ResNE is 0, fully unroll the vector op.
  9365. if (ResNE == 0)
  9366. ResNE = NE;
  9367. else if (NE > ResNE)
  9368. NE = ResNE;
  9369. unsigned i;
  9370. for (i= 0; i != NE; ++i) {
  9371. for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
  9372. SDValue Operand = N->getOperand(j);
  9373. EVT OperandVT = Operand.getValueType();
  9374. if (OperandVT.isVector()) {
  9375. // A vector operand; extract a single element.
  9376. EVT OperandEltVT = OperandVT.getVectorElementType();
  9377. Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
  9378. Operand, getVectorIdxConstant(i, dl));
  9379. } else {
  9380. // A scalar operand; just use it as is.
  9381. Operands[j] = Operand;
  9382. }
  9383. }
  9384. switch (N->getOpcode()) {
  9385. default: {
  9386. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
  9387. N->getFlags()));
  9388. break;
  9389. }
  9390. case ISD::VSELECT:
  9391. Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
  9392. break;
  9393. case ISD::SHL:
  9394. case ISD::SRA:
  9395. case ISD::SRL:
  9396. case ISD::ROTL:
  9397. case ISD::ROTR:
  9398. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
  9399. getShiftAmountOperand(Operands[0].getValueType(),
  9400. Operands[1])));
  9401. break;
  9402. case ISD::SIGN_EXTEND_INREG: {
  9403. EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
  9404. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
  9405. Operands[0],
  9406. getValueType(ExtVT)));
  9407. }
  9408. }
  9409. }
  9410. for (; i < ResNE; ++i)
  9411. Scalars.push_back(getUNDEF(EltVT));
  9412. EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
  9413. return getBuildVector(VecVT, dl, Scalars);
  9414. }
  9415. std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
  9416. SDNode *N, unsigned ResNE) {
  9417. unsigned Opcode = N->getOpcode();
  9418. assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
  9419. Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
  9420. Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
  9421. "Expected an overflow opcode");
  9422. EVT ResVT = N->getValueType(0);
  9423. EVT OvVT = N->getValueType(1);
  9424. EVT ResEltVT = ResVT.getVectorElementType();
  9425. EVT OvEltVT = OvVT.getVectorElementType();
  9426. SDLoc dl(N);
  9427. // If ResNE is 0, fully unroll the vector op.
  9428. unsigned NE = ResVT.getVectorNumElements();
  9429. if (ResNE == 0)
  9430. ResNE = NE;
  9431. else if (NE > ResNE)
  9432. NE = ResNE;
  9433. SmallVector<SDValue, 8> LHSScalars;
  9434. SmallVector<SDValue, 8> RHSScalars;
  9435. ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
  9436. ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
  9437. EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
  9438. SDVTList VTs = getVTList(ResEltVT, SVT);
  9439. SmallVector<SDValue, 8> ResScalars;
  9440. SmallVector<SDValue, 8> OvScalars;
  9441. for (unsigned i = 0; i < NE; ++i) {
  9442. SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
  9443. SDValue Ov =
  9444. getSelect(dl, OvEltVT, Res.getValue(1),
  9445. getBoolConstant(true, dl, OvEltVT, ResVT),
  9446. getConstant(0, dl, OvEltVT));
  9447. ResScalars.push_back(Res);
  9448. OvScalars.push_back(Ov);
  9449. }
  9450. ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
  9451. OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
  9452. EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
  9453. EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
  9454. return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
  9455. getBuildVector(NewOvVT, dl, OvScalars));
  9456. }
  9457. bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
  9458. LoadSDNode *Base,
  9459. unsigned Bytes,
  9460. int Dist) const {
  9461. if (LD->isVolatile() || Base->isVolatile())
  9462. return false;
  9463. // TODO: probably too restrictive for atomics, revisit
  9464. if (!LD->isSimple())
  9465. return false;
  9466. if (LD->isIndexed() || Base->isIndexed())
  9467. return false;
  9468. if (LD->getChain() != Base->getChain())
  9469. return false;
  9470. EVT VT = LD->getValueType(0);
  9471. if (VT.getSizeInBits() / 8 != Bytes)
  9472. return false;
  9473. auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
  9474. auto LocDecomp = BaseIndexOffset::match(LD, *this);
  9475. int64_t Offset = 0;
  9476. if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
  9477. return (Dist * Bytes == Offset);
  9478. return false;
  9479. }
  9480. /// InferPtrAlignment - Infer alignment of a load / store address. Return None
  9481. /// if it cannot be inferred.
  9482. MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
  9483. // If this is a GlobalAddress + cst, return the alignment.
  9484. const GlobalValue *GV = nullptr;
  9485. int64_t GVOffset = 0;
  9486. if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
  9487. unsigned PtrWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
  9488. KnownBits Known(PtrWidth);
  9489. llvm::computeKnownBits(GV, Known, getDataLayout());
  9490. unsigned AlignBits = Known.countMinTrailingZeros();
  9491. if (AlignBits)
  9492. return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
  9493. }
  9494. // If this is a direct reference to a stack slot, use information about the
  9495. // stack slot's alignment.
  9496. int FrameIdx = INT_MIN;
  9497. int64_t FrameOffset = 0;
  9498. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
  9499. FrameIdx = FI->getIndex();
  9500. } else if (isBaseWithConstantOffset(Ptr) &&
  9501. isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
  9502. // Handle FI+Cst
  9503. FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
  9504. FrameOffset = Ptr.getConstantOperandVal(1);
  9505. }
  9506. if (FrameIdx != INT_MIN) {
  9507. const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
  9508. return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
  9509. }
  9510. return None;
  9511. }
  9512. /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
  9513. /// which is split (or expanded) into two not necessarily identical pieces.
  9514. std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
  9515. // Currently all types are split in half.
  9516. EVT LoVT, HiVT;
  9517. if (!VT.isVector())
  9518. LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
  9519. else
  9520. LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
  9521. return std::make_pair(LoVT, HiVT);
  9522. }
  9523. /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
  9524. /// type, dependent on an enveloping VT that has been split into two identical
  9525. /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
  9526. std::pair<EVT, EVT>
  9527. SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
  9528. bool *HiIsEmpty) const {
  9529. EVT EltTp = VT.getVectorElementType();
  9530. // Examples:
  9531. // custom VL=8 with enveloping VL=8/8 yields 8/0 (hi empty)
  9532. // custom VL=9 with enveloping VL=8/8 yields 8/1
  9533. // custom VL=10 with enveloping VL=8/8 yields 8/2
  9534. // etc.
  9535. ElementCount VTNumElts = VT.getVectorElementCount();
  9536. ElementCount EnvNumElts = EnvVT.getVectorElementCount();
  9537. assert(VTNumElts.isScalable() == EnvNumElts.isScalable() &&
  9538. "Mixing fixed width and scalable vectors when enveloping a type");
  9539. EVT LoVT, HiVT;
  9540. if (VTNumElts.getKnownMinValue() > EnvNumElts.getKnownMinValue()) {
  9541. LoVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
  9542. HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts);
  9543. *HiIsEmpty = false;
  9544. } else {
  9545. // Flag that hi type has zero storage size, but return split envelop type
  9546. // (this would be easier if vector types with zero elements were allowed).
  9547. LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts);
  9548. HiVT = EVT::getVectorVT(*getContext(), EltTp, EnvNumElts);
  9549. *HiIsEmpty = true;
  9550. }
  9551. return std::make_pair(LoVT, HiVT);
  9552. }
  9553. /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
  9554. /// low/high part.
  9555. std::pair<SDValue, SDValue>
  9556. SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
  9557. const EVT &HiVT) {
  9558. assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
  9559. LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
  9560. "Splitting vector with an invalid mixture of fixed and scalable "
  9561. "vector types");
  9562. assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
  9563. N.getValueType().getVectorMinNumElements() &&
  9564. "More vector elements requested than available!");
  9565. SDValue Lo, Hi;
  9566. Lo =
  9567. getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
  9568. // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
  9569. // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
  9570. // IDX with the runtime scaling factor of the result vector type. For
  9571. // fixed-width result vectors, that runtime scaling factor is 1.
  9572. Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
  9573. getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
  9574. return std::make_pair(Lo, Hi);
  9575. }
  9576. std::pair<SDValue, SDValue> SelectionDAG::SplitEVL(SDValue N, EVT VecVT,
  9577. const SDLoc &DL) {
  9578. // Split the vector length parameter.
  9579. // %evl -> umin(%evl, %halfnumelts) and usubsat(%evl - %halfnumelts).
  9580. EVT VT = N.getValueType();
  9581. assert(VecVT.getVectorElementCount().isKnownEven() &&
  9582. "Expecting the mask to be an evenly-sized vector");
  9583. unsigned HalfMinNumElts = VecVT.getVectorMinNumElements() / 2;
  9584. SDValue HalfNumElts =
  9585. VecVT.isFixedLengthVector()
  9586. ? getConstant(HalfMinNumElts, DL, VT)
  9587. : getVScale(DL, VT, APInt(VT.getScalarSizeInBits(), HalfMinNumElts));
  9588. SDValue Lo = getNode(ISD::UMIN, DL, VT, N, HalfNumElts);
  9589. SDValue Hi = getNode(ISD::USUBSAT, DL, VT, N, HalfNumElts);
  9590. return std::make_pair(Lo, Hi);
  9591. }
  9592. /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
  9593. SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
  9594. EVT VT = N.getValueType();
  9595. EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
  9596. NextPowerOf2(VT.getVectorNumElements()));
  9597. return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
  9598. getVectorIdxConstant(0, DL));
  9599. }
  9600. void SelectionDAG::ExtractVectorElements(SDValue Op,
  9601. SmallVectorImpl<SDValue> &Args,
  9602. unsigned Start, unsigned Count,
  9603. EVT EltVT) {
  9604. EVT VT = Op.getValueType();
  9605. if (Count == 0)
  9606. Count = VT.getVectorNumElements();
  9607. if (EltVT == EVT())
  9608. EltVT = VT.getVectorElementType();
  9609. SDLoc SL(Op);
  9610. for (unsigned i = Start, e = Start + Count; i != e; ++i) {
  9611. Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
  9612. getVectorIdxConstant(i, SL)));
  9613. }
  9614. }
  9615. // getAddressSpace - Return the address space this GlobalAddress belongs to.
  9616. unsigned GlobalAddressSDNode::getAddressSpace() const {
  9617. return getGlobal()->getType()->getAddressSpace();
  9618. }
  9619. Type *ConstantPoolSDNode::getType() const {
  9620. if (isMachineConstantPoolEntry())
  9621. return Val.MachineCPVal->getType();
  9622. return Val.ConstVal->getType();
  9623. }
  9624. bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
  9625. unsigned &SplatBitSize,
  9626. bool &HasAnyUndefs,
  9627. unsigned MinSplatBits,
  9628. bool IsBigEndian) const {
  9629. EVT VT = getValueType(0);
  9630. assert(VT.isVector() && "Expected a vector type");
  9631. unsigned VecWidth = VT.getSizeInBits();
  9632. if (MinSplatBits > VecWidth)
  9633. return false;
  9634. // FIXME: The widths are based on this node's type, but build vectors can
  9635. // truncate their operands.
  9636. SplatValue = APInt(VecWidth, 0);
  9637. SplatUndef = APInt(VecWidth, 0);
  9638. // Get the bits. Bits with undefined values (when the corresponding element
  9639. // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
  9640. // in SplatValue. If any of the values are not constant, give up and return
  9641. // false.
  9642. unsigned int NumOps = getNumOperands();
  9643. assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
  9644. unsigned EltWidth = VT.getScalarSizeInBits();
  9645. for (unsigned j = 0; j < NumOps; ++j) {
  9646. unsigned i = IsBigEndian ? NumOps - 1 - j : j;
  9647. SDValue OpVal = getOperand(i);
  9648. unsigned BitPos = j * EltWidth;
  9649. if (OpVal.isUndef())
  9650. SplatUndef.setBits(BitPos, BitPos + EltWidth);
  9651. else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
  9652. SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
  9653. else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
  9654. SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
  9655. else
  9656. return false;
  9657. }
  9658. // The build_vector is all constants or undefs. Find the smallest element
  9659. // size that splats the vector.
  9660. HasAnyUndefs = (SplatUndef != 0);
  9661. // FIXME: This does not work for vectors with elements less than 8 bits.
  9662. while (VecWidth > 8) {
  9663. unsigned HalfSize = VecWidth / 2;
  9664. APInt HighValue = SplatValue.extractBits(HalfSize, HalfSize);
  9665. APInt LowValue = SplatValue.extractBits(HalfSize, 0);
  9666. APInt HighUndef = SplatUndef.extractBits(HalfSize, HalfSize);
  9667. APInt LowUndef = SplatUndef.extractBits(HalfSize, 0);
  9668. // If the two halves do not match (ignoring undef bits), stop here.
  9669. if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
  9670. MinSplatBits > HalfSize)
  9671. break;
  9672. SplatValue = HighValue | LowValue;
  9673. SplatUndef = HighUndef & LowUndef;
  9674. VecWidth = HalfSize;
  9675. }
  9676. SplatBitSize = VecWidth;
  9677. return true;
  9678. }
  9679. SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
  9680. BitVector *UndefElements) const {
  9681. unsigned NumOps = getNumOperands();
  9682. if (UndefElements) {
  9683. UndefElements->clear();
  9684. UndefElements->resize(NumOps);
  9685. }
  9686. assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
  9687. if (!DemandedElts)
  9688. return SDValue();
  9689. SDValue Splatted;
  9690. for (unsigned i = 0; i != NumOps; ++i) {
  9691. if (!DemandedElts[i])
  9692. continue;
  9693. SDValue Op = getOperand(i);
  9694. if (Op.isUndef()) {
  9695. if (UndefElements)
  9696. (*UndefElements)[i] = true;
  9697. } else if (!Splatted) {
  9698. Splatted = Op;
  9699. } else if (Splatted != Op) {
  9700. return SDValue();
  9701. }
  9702. }
  9703. if (!Splatted) {
  9704. unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
  9705. assert(getOperand(FirstDemandedIdx).isUndef() &&
  9706. "Can only have a splat without a constant for all undefs.");
  9707. return getOperand(FirstDemandedIdx);
  9708. }
  9709. return Splatted;
  9710. }
  9711. SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
  9712. APInt DemandedElts = APInt::getAllOnes(getNumOperands());
  9713. return getSplatValue(DemandedElts, UndefElements);
  9714. }
  9715. bool BuildVectorSDNode::getRepeatedSequence(const APInt &DemandedElts,
  9716. SmallVectorImpl<SDValue> &Sequence,
  9717. BitVector *UndefElements) const {
  9718. unsigned NumOps = getNumOperands();
  9719. Sequence.clear();
  9720. if (UndefElements) {
  9721. UndefElements->clear();
  9722. UndefElements->resize(NumOps);
  9723. }
  9724. assert(NumOps == DemandedElts.getBitWidth() && "Unexpected vector size");
  9725. if (!DemandedElts || NumOps < 2 || !isPowerOf2_32(NumOps))
  9726. return false;
  9727. // Set the undefs even if we don't find a sequence (like getSplatValue).
  9728. if (UndefElements)
  9729. for (unsigned I = 0; I != NumOps; ++I)
  9730. if (DemandedElts[I] && getOperand(I).isUndef())
  9731. (*UndefElements)[I] = true;
  9732. // Iteratively widen the sequence length looking for repetitions.
  9733. for (unsigned SeqLen = 1; SeqLen < NumOps; SeqLen *= 2) {
  9734. Sequence.append(SeqLen, SDValue());
  9735. for (unsigned I = 0; I != NumOps; ++I) {
  9736. if (!DemandedElts[I])
  9737. continue;
  9738. SDValue &SeqOp = Sequence[I % SeqLen];
  9739. SDValue Op = getOperand(I);
  9740. if (Op.isUndef()) {
  9741. if (!SeqOp)
  9742. SeqOp = Op;
  9743. continue;
  9744. }
  9745. if (SeqOp && !SeqOp.isUndef() && SeqOp != Op) {
  9746. Sequence.clear();
  9747. break;
  9748. }
  9749. SeqOp = Op;
  9750. }
  9751. if (!Sequence.empty())
  9752. return true;
  9753. }
  9754. assert(Sequence.empty() && "Failed to empty non-repeating sequence pattern");
  9755. return false;
  9756. }
  9757. bool BuildVectorSDNode::getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
  9758. BitVector *UndefElements) const {
  9759. APInt DemandedElts = APInt::getAllOnes(getNumOperands());
  9760. return getRepeatedSequence(DemandedElts, Sequence, UndefElements);
  9761. }
  9762. ConstantSDNode *
  9763. BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
  9764. BitVector *UndefElements) const {
  9765. return dyn_cast_or_null<ConstantSDNode>(
  9766. getSplatValue(DemandedElts, UndefElements));
  9767. }
  9768. ConstantSDNode *
  9769. BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
  9770. return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
  9771. }
  9772. ConstantFPSDNode *
  9773. BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
  9774. BitVector *UndefElements) const {
  9775. return dyn_cast_or_null<ConstantFPSDNode>(
  9776. getSplatValue(DemandedElts, UndefElements));
  9777. }
  9778. ConstantFPSDNode *
  9779. BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
  9780. return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
  9781. }
  9782. int32_t
  9783. BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
  9784. uint32_t BitWidth) const {
  9785. if (ConstantFPSDNode *CN =
  9786. dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
  9787. bool IsExact;
  9788. APSInt IntVal(BitWidth);
  9789. const APFloat &APF = CN->getValueAPF();
  9790. if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
  9791. APFloat::opOK ||
  9792. !IsExact)
  9793. return -1;
  9794. return IntVal.exactLogBase2();
  9795. }
  9796. return -1;
  9797. }
  9798. bool BuildVectorSDNode::getConstantRawBits(
  9799. bool IsLittleEndian, unsigned DstEltSizeInBits,
  9800. SmallVectorImpl<APInt> &RawBitElements, BitVector &UndefElements) const {
  9801. // Early-out if this contains anything but Undef/Constant/ConstantFP.
  9802. if (!isConstant())
  9803. return false;
  9804. unsigned NumSrcOps = getNumOperands();
  9805. unsigned SrcEltSizeInBits = getValueType(0).getScalarSizeInBits();
  9806. assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
  9807. "Invalid bitcast scale");
  9808. // Extract raw src bits.
  9809. SmallVector<APInt> SrcBitElements(NumSrcOps,
  9810. APInt::getNullValue(SrcEltSizeInBits));
  9811. BitVector SrcUndeElements(NumSrcOps, false);
  9812. for (unsigned I = 0; I != NumSrcOps; ++I) {
  9813. SDValue Op = getOperand(I);
  9814. if (Op.isUndef()) {
  9815. SrcUndeElements.set(I);
  9816. continue;
  9817. }
  9818. auto *CInt = dyn_cast<ConstantSDNode>(Op);
  9819. auto *CFP = dyn_cast<ConstantFPSDNode>(Op);
  9820. assert((CInt || CFP) && "Unknown constant");
  9821. SrcBitElements[I] =
  9822. CInt ? CInt->getAPIntValue().truncOrSelf(SrcEltSizeInBits)
  9823. : CFP->getValueAPF().bitcastToAPInt();
  9824. }
  9825. // Recast to dst width.
  9826. recastRawBits(IsLittleEndian, DstEltSizeInBits, RawBitElements,
  9827. SrcBitElements, UndefElements, SrcUndeElements);
  9828. return true;
  9829. }
  9830. void BuildVectorSDNode::recastRawBits(bool IsLittleEndian,
  9831. unsigned DstEltSizeInBits,
  9832. SmallVectorImpl<APInt> &DstBitElements,
  9833. ArrayRef<APInt> SrcBitElements,
  9834. BitVector &DstUndefElements,
  9835. const BitVector &SrcUndefElements) {
  9836. unsigned NumSrcOps = SrcBitElements.size();
  9837. unsigned SrcEltSizeInBits = SrcBitElements[0].getBitWidth();
  9838. assert(((NumSrcOps * SrcEltSizeInBits) % DstEltSizeInBits) == 0 &&
  9839. "Invalid bitcast scale");
  9840. assert(NumSrcOps == SrcUndefElements.size() &&
  9841. "Vector size mismatch");
  9842. unsigned NumDstOps = (NumSrcOps * SrcEltSizeInBits) / DstEltSizeInBits;
  9843. DstUndefElements.clear();
  9844. DstUndefElements.resize(NumDstOps, false);
  9845. DstBitElements.assign(NumDstOps, APInt::getNullValue(DstEltSizeInBits));
  9846. // Concatenate src elements constant bits together into dst element.
  9847. if (SrcEltSizeInBits <= DstEltSizeInBits) {
  9848. unsigned Scale = DstEltSizeInBits / SrcEltSizeInBits;
  9849. for (unsigned I = 0; I != NumDstOps; ++I) {
  9850. DstUndefElements.set(I);
  9851. APInt &DstBits = DstBitElements[I];
  9852. for (unsigned J = 0; J != Scale; ++J) {
  9853. unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
  9854. if (SrcUndefElements[Idx])
  9855. continue;
  9856. DstUndefElements.reset(I);
  9857. const APInt &SrcBits = SrcBitElements[Idx];
  9858. assert(SrcBits.getBitWidth() == SrcEltSizeInBits &&
  9859. "Illegal constant bitwidths");
  9860. DstBits.insertBits(SrcBits, J * SrcEltSizeInBits);
  9861. }
  9862. }
  9863. return;
  9864. }
  9865. // Split src element constant bits into dst elements.
  9866. unsigned Scale = SrcEltSizeInBits / DstEltSizeInBits;
  9867. for (unsigned I = 0; I != NumSrcOps; ++I) {
  9868. if (SrcUndefElements[I]) {
  9869. DstUndefElements.set(I * Scale, (I + 1) * Scale);
  9870. continue;
  9871. }
  9872. const APInt &SrcBits = SrcBitElements[I];
  9873. for (unsigned J = 0; J != Scale; ++J) {
  9874. unsigned Idx = (I * Scale) + (IsLittleEndian ? J : (Scale - J - 1));
  9875. APInt &DstBits = DstBitElements[Idx];
  9876. DstBits = SrcBits.extractBits(DstEltSizeInBits, J * DstEltSizeInBits);
  9877. }
  9878. }
  9879. }
  9880. bool BuildVectorSDNode::isConstant() const {
  9881. for (const SDValue &Op : op_values()) {
  9882. unsigned Opc = Op.getOpcode();
  9883. if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
  9884. return false;
  9885. }
  9886. return true;
  9887. }
  9888. bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
  9889. // Find the first non-undef value in the shuffle mask.
  9890. unsigned i, e;
  9891. for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
  9892. /* search */;
  9893. // If all elements are undefined, this shuffle can be considered a splat
  9894. // (although it should eventually get simplified away completely).
  9895. if (i == e)
  9896. return true;
  9897. // Make sure all remaining elements are either undef or the same as the first
  9898. // non-undef value.
  9899. for (int Idx = Mask[i]; i != e; ++i)
  9900. if (Mask[i] >= 0 && Mask[i] != Idx)
  9901. return false;
  9902. return true;
  9903. }
  9904. // Returns the SDNode if it is a constant integer BuildVector
  9905. // or constant integer.
  9906. SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) const {
  9907. if (isa<ConstantSDNode>(N))
  9908. return N.getNode();
  9909. if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
  9910. return N.getNode();
  9911. // Treat a GlobalAddress supporting constant offset folding as a
  9912. // constant integer.
  9913. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
  9914. if (GA->getOpcode() == ISD::GlobalAddress &&
  9915. TLI->isOffsetFoldingLegal(GA))
  9916. return GA;
  9917. if ((N.getOpcode() == ISD::SPLAT_VECTOR) &&
  9918. isa<ConstantSDNode>(N.getOperand(0)))
  9919. return N.getNode();
  9920. return nullptr;
  9921. }
  9922. // Returns the SDNode if it is a constant float BuildVector
  9923. // or constant float.
  9924. SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) const {
  9925. if (isa<ConstantFPSDNode>(N))
  9926. return N.getNode();
  9927. if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
  9928. return N.getNode();
  9929. return nullptr;
  9930. }
  9931. void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
  9932. assert(!Node->OperandList && "Node already has operands");
  9933. assert(SDNode::getMaxNumOperands() >= Vals.size() &&
  9934. "too many operands to fit into SDNode");
  9935. SDUse *Ops = OperandRecycler.allocate(
  9936. ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
  9937. bool IsDivergent = false;
  9938. for (unsigned I = 0; I != Vals.size(); ++I) {
  9939. Ops[I].setUser(Node);
  9940. Ops[I].setInitial(Vals[I]);
  9941. if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
  9942. IsDivergent |= Ops[I].getNode()->isDivergent();
  9943. }
  9944. Node->NumOperands = Vals.size();
  9945. Node->OperandList = Ops;
  9946. if (!TLI->isSDNodeAlwaysUniform(Node)) {
  9947. IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
  9948. Node->SDNodeBits.IsDivergent = IsDivergent;
  9949. }
  9950. checkForCycles(Node);
  9951. }
  9952. SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
  9953. SmallVectorImpl<SDValue> &Vals) {
  9954. size_t Limit = SDNode::getMaxNumOperands();
  9955. while (Vals.size() > Limit) {
  9956. unsigned SliceIdx = Vals.size() - Limit;
  9957. auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
  9958. SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
  9959. Vals.erase(Vals.begin() + SliceIdx, Vals.end());
  9960. Vals.emplace_back(NewTF);
  9961. }
  9962. return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
  9963. }
  9964. SDValue SelectionDAG::getNeutralElement(unsigned Opcode, const SDLoc &DL,
  9965. EVT VT, SDNodeFlags Flags) {
  9966. switch (Opcode) {
  9967. default:
  9968. return SDValue();
  9969. case ISD::ADD:
  9970. case ISD::OR:
  9971. case ISD::XOR:
  9972. case ISD::UMAX:
  9973. return getConstant(0, DL, VT);
  9974. case ISD::MUL:
  9975. return getConstant(1, DL, VT);
  9976. case ISD::AND:
  9977. case ISD::UMIN:
  9978. return getAllOnesConstant(DL, VT);
  9979. case ISD::SMAX:
  9980. return getConstant(APInt::getSignedMinValue(VT.getSizeInBits()), DL, VT);
  9981. case ISD::SMIN:
  9982. return getConstant(APInt::getSignedMaxValue(VT.getSizeInBits()), DL, VT);
  9983. case ISD::FADD:
  9984. return getConstantFP(-0.0, DL, VT);
  9985. case ISD::FMUL:
  9986. return getConstantFP(1.0, DL, VT);
  9987. case ISD::FMINNUM:
  9988. case ISD::FMAXNUM: {
  9989. // Neutral element for fminnum is NaN, Inf or FLT_MAX, depending on FMF.
  9990. const fltSemantics &Semantics = EVTToAPFloatSemantics(VT);
  9991. APFloat NeutralAF = !Flags.hasNoNaNs() ? APFloat::getQNaN(Semantics) :
  9992. !Flags.hasNoInfs() ? APFloat::getInf(Semantics) :
  9993. APFloat::getLargest(Semantics);
  9994. if (Opcode == ISD::FMAXNUM)
  9995. NeutralAF.changeSign();
  9996. return getConstantFP(NeutralAF, DL, VT);
  9997. }
  9998. }
  9999. }
  10000. #ifndef NDEBUG
  10001. static void checkForCyclesHelper(const SDNode *N,
  10002. SmallPtrSetImpl<const SDNode*> &Visited,
  10003. SmallPtrSetImpl<const SDNode*> &Checked,
  10004. const llvm::SelectionDAG *DAG) {
  10005. // If this node has already been checked, don't check it again.
  10006. if (Checked.count(N))
  10007. return;
  10008. // If a node has already been visited on this depth-first walk, reject it as
  10009. // a cycle.
  10010. if (!Visited.insert(N).second) {
  10011. errs() << "Detected cycle in SelectionDAG\n";
  10012. dbgs() << "Offending node:\n";
  10013. N->dumprFull(DAG); dbgs() << "\n";
  10014. abort();
  10015. }
  10016. for (const SDValue &Op : N->op_values())
  10017. checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
  10018. Checked.insert(N);
  10019. Visited.erase(N);
  10020. }
  10021. #endif
  10022. void llvm::checkForCycles(const llvm::SDNode *N,
  10023. const llvm::SelectionDAG *DAG,
  10024. bool force) {
  10025. #ifndef NDEBUG
  10026. bool check = force;
  10027. #ifdef EXPENSIVE_CHECKS
  10028. check = true;
  10029. #endif // EXPENSIVE_CHECKS
  10030. if (check) {
  10031. assert(N && "Checking nonexistent SDNode");
  10032. SmallPtrSet<const SDNode*, 32> visited;
  10033. SmallPtrSet<const SDNode*, 32> checked;
  10034. checkForCyclesHelper(N, visited, checked, DAG);
  10035. }
  10036. #endif // !NDEBUG
  10037. }
  10038. void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
  10039. checkForCycles(DAG->getRoot().getNode(), DAG, force);
  10040. }