SelectionDAGBuilder.cpp 410 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552
  1. //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "SelectionDAGBuilder.h"
  13. #include "SDNodeDbgValue.h"
  14. #include "llvm/ADT/APFloat.h"
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/BitVector.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/None.h"
  20. #include "llvm/ADT/Optional.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallPtrSet.h"
  23. #include "llvm/ADT/SmallSet.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/ADT/Triple.h"
  27. #include "llvm/ADT/Twine.h"
  28. #include "llvm/Analysis/AliasAnalysis.h"
  29. #include "llvm/Analysis/BranchProbabilityInfo.h"
  30. #include "llvm/Analysis/ConstantFolding.h"
  31. #include "llvm/Analysis/EHPersonalities.h"
  32. #include "llvm/Analysis/Loads.h"
  33. #include "llvm/Analysis/MemoryLocation.h"
  34. #include "llvm/Analysis/TargetLibraryInfo.h"
  35. #include "llvm/Analysis/ValueTracking.h"
  36. #include "llvm/Analysis/VectorUtils.h"
  37. #include "llvm/CodeGen/Analysis.h"
  38. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  39. #include "llvm/CodeGen/GCMetadata.h"
  40. #include "llvm/CodeGen/ISDOpcodes.h"
  41. #include "llvm/CodeGen/MachineBasicBlock.h"
  42. #include "llvm/CodeGen/MachineFrameInfo.h"
  43. #include "llvm/CodeGen/MachineFunction.h"
  44. #include "llvm/CodeGen/MachineInstr.h"
  45. #include "llvm/CodeGen/MachineInstrBuilder.h"
  46. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  47. #include "llvm/CodeGen/MachineMemOperand.h"
  48. #include "llvm/CodeGen/MachineModuleInfo.h"
  49. #include "llvm/CodeGen/MachineOperand.h"
  50. #include "llvm/CodeGen/MachineRegisterInfo.h"
  51. #include "llvm/CodeGen/RuntimeLibcalls.h"
  52. #include "llvm/CodeGen/SelectionDAG.h"
  53. #include "llvm/CodeGen/SelectionDAGNodes.h"
  54. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  55. #include "llvm/CodeGen/StackMaps.h"
  56. #include "llvm/CodeGen/SwiftErrorValueTracking.h"
  57. #include "llvm/CodeGen/TargetFrameLowering.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetLowering.h"
  60. #include "llvm/CodeGen/TargetOpcodes.h"
  61. #include "llvm/CodeGen/TargetRegisterInfo.h"
  62. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  63. #include "llvm/CodeGen/ValueTypes.h"
  64. #include "llvm/CodeGen/WinEHFuncInfo.h"
  65. #include "llvm/IR/Argument.h"
  66. #include "llvm/IR/Attributes.h"
  67. #include "llvm/IR/BasicBlock.h"
  68. #include "llvm/IR/CFG.h"
  69. #include "llvm/IR/CallSite.h"
  70. #include "llvm/IR/CallingConv.h"
  71. #include "llvm/IR/Constant.h"
  72. #include "llvm/IR/ConstantRange.h"
  73. #include "llvm/IR/Constants.h"
  74. #include "llvm/IR/DataLayout.h"
  75. #include "llvm/IR/DebugInfoMetadata.h"
  76. #include "llvm/IR/DebugLoc.h"
  77. #include "llvm/IR/DerivedTypes.h"
  78. #include "llvm/IR/Function.h"
  79. #include "llvm/IR/GetElementPtrTypeIterator.h"
  80. #include "llvm/IR/InlineAsm.h"
  81. #include "llvm/IR/InstrTypes.h"
  82. #include "llvm/IR/Instruction.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/Intrinsics.h"
  86. #include "llvm/IR/LLVMContext.h"
  87. #include "llvm/IR/Metadata.h"
  88. #include "llvm/IR/Module.h"
  89. #include "llvm/IR/Operator.h"
  90. #include "llvm/IR/PatternMatch.h"
  91. #include "llvm/IR/Statepoint.h"
  92. #include "llvm/IR/Type.h"
  93. #include "llvm/IR/User.h"
  94. #include "llvm/IR/Value.h"
  95. #include "llvm/MC/MCContext.h"
  96. #include "llvm/MC/MCSymbol.h"
  97. #include "llvm/Support/AtomicOrdering.h"
  98. #include "llvm/Support/BranchProbability.h"
  99. #include "llvm/Support/Casting.h"
  100. #include "llvm/Support/CodeGen.h"
  101. #include "llvm/Support/CommandLine.h"
  102. #include "llvm/Support/Compiler.h"
  103. #include "llvm/Support/Debug.h"
  104. #include "llvm/Support/ErrorHandling.h"
  105. #include "llvm/Support/MachineValueType.h"
  106. #include "llvm/Support/MathExtras.h"
  107. #include "llvm/Support/raw_ostream.h"
  108. #include "llvm/Target/TargetIntrinsicInfo.h"
  109. #include "llvm/Target/TargetMachine.h"
  110. #include "llvm/Target/TargetOptions.h"
  111. #include "llvm/Transforms/Utils/Local.h"
  112. #include <algorithm>
  113. #include <cassert>
  114. #include <cstddef>
  115. #include <cstdint>
  116. #include <cstring>
  117. #include <iterator>
  118. #include <limits>
  119. #include <numeric>
  120. #include <tuple>
  121. #include <utility>
  122. #include <vector>
  123. using namespace llvm;
  124. using namespace PatternMatch;
  125. using namespace SwitchCG;
  126. #define DEBUG_TYPE "isel"
  127. /// LimitFloatPrecision - Generate low-precision inline sequences for
  128. /// some float libcalls (6, 8 or 12 bits).
  129. static unsigned LimitFloatPrecision;
  130. static cl::opt<unsigned, true>
  131. LimitFPPrecision("limit-float-precision",
  132. cl::desc("Generate low-precision inline sequences "
  133. "for some float libcalls"),
  134. cl::location(LimitFloatPrecision), cl::Hidden,
  135. cl::init(0));
  136. static cl::opt<unsigned> SwitchPeelThreshold(
  137. "switch-peel-threshold", cl::Hidden, cl::init(66),
  138. cl::desc("Set the case probability threshold for peeling the case from a "
  139. "switch statement. A value greater than 100 will void this "
  140. "optimization"));
  141. // Limit the width of DAG chains. This is important in general to prevent
  142. // DAG-based analysis from blowing up. For example, alias analysis and
  143. // load clustering may not complete in reasonable time. It is difficult to
  144. // recognize and avoid this situation within each individual analysis, and
  145. // future analyses are likely to have the same behavior. Limiting DAG width is
  146. // the safe approach and will be especially important with global DAGs.
  147. //
  148. // MaxParallelChains default is arbitrarily high to avoid affecting
  149. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  150. // sequence over this should have been converted to llvm.memcpy by the
  151. // frontend. It is easy to induce this behavior with .ll code such as:
  152. // %buffer = alloca [4096 x i8]
  153. // %data = load [4096 x i8]* %argPtr
  154. // store [4096 x i8] %data, [4096 x i8]* %buffer
  155. static const unsigned MaxParallelChains = 64;
  156. // Return the calling convention if the Value passed requires ABI mangling as it
  157. // is a parameter to a function or a return value from a function which is not
  158. // an intrinsic.
  159. static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
  160. if (auto *R = dyn_cast<ReturnInst>(V))
  161. return R->getParent()->getParent()->getCallingConv();
  162. if (auto *CI = dyn_cast<CallInst>(V)) {
  163. const bool IsInlineAsm = CI->isInlineAsm();
  164. const bool IsIndirectFunctionCall =
  165. !IsInlineAsm && !CI->getCalledFunction();
  166. // It is possible that the call instruction is an inline asm statement or an
  167. // indirect function call in which case the return value of
  168. // getCalledFunction() would be nullptr.
  169. const bool IsInstrinsicCall =
  170. !IsInlineAsm && !IsIndirectFunctionCall &&
  171. CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
  172. if (!IsInlineAsm && !IsInstrinsicCall)
  173. return CI->getCallingConv();
  174. }
  175. return None;
  176. }
  177. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  178. const SDValue *Parts, unsigned NumParts,
  179. MVT PartVT, EVT ValueVT, const Value *V,
  180. Optional<CallingConv::ID> CC);
  181. /// getCopyFromParts - Create a value that contains the specified legal parts
  182. /// combined into the value they represent. If the parts combine to a type
  183. /// larger than ValueVT then AssertOp can be used to specify whether the extra
  184. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  185. /// (ISD::AssertSext).
  186. static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
  187. const SDValue *Parts, unsigned NumParts,
  188. MVT PartVT, EVT ValueVT, const Value *V,
  189. Optional<CallingConv::ID> CC = None,
  190. Optional<ISD::NodeType> AssertOp = None) {
  191. if (ValueVT.isVector())
  192. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
  193. CC);
  194. assert(NumParts > 0 && "No parts to assemble!");
  195. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  196. SDValue Val = Parts[0];
  197. if (NumParts > 1) {
  198. // Assemble the value from multiple parts.
  199. if (ValueVT.isInteger()) {
  200. unsigned PartBits = PartVT.getSizeInBits();
  201. unsigned ValueBits = ValueVT.getSizeInBits();
  202. // Assemble the power of 2 part.
  203. unsigned RoundParts =
  204. (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
  205. unsigned RoundBits = PartBits * RoundParts;
  206. EVT RoundVT = RoundBits == ValueBits ?
  207. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  208. SDValue Lo, Hi;
  209. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  210. if (RoundParts > 2) {
  211. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  212. PartVT, HalfVT, V);
  213. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  214. RoundParts / 2, PartVT, HalfVT, V);
  215. } else {
  216. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  217. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  218. }
  219. if (DAG.getDataLayout().isBigEndian())
  220. std::swap(Lo, Hi);
  221. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  222. if (RoundParts < NumParts) {
  223. // Assemble the trailing non-power-of-2 part.
  224. unsigned OddParts = NumParts - RoundParts;
  225. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  226. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
  227. OddVT, V, CC);
  228. // Combine the round and odd parts.
  229. Lo = Val;
  230. if (DAG.getDataLayout().isBigEndian())
  231. std::swap(Lo, Hi);
  232. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  233. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  234. Hi =
  235. DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  236. DAG.getConstant(Lo.getValueSizeInBits(), DL,
  237. TLI.getPointerTy(DAG.getDataLayout())));
  238. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  239. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  240. }
  241. } else if (PartVT.isFloatingPoint()) {
  242. // FP split into multiple FP parts (for ppcf128)
  243. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
  244. "Unexpected split");
  245. SDValue Lo, Hi;
  246. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  247. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  248. if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
  249. std::swap(Lo, Hi);
  250. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  251. } else {
  252. // FP split into integer parts (soft fp)
  253. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  254. !PartVT.isVector() && "Unexpected split");
  255. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  256. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
  257. }
  258. }
  259. // There is now one part, held in Val. Correct it to match ValueVT.
  260. // PartEVT is the type of the register class that holds the value.
  261. // ValueVT is the type of the inline asm operation.
  262. EVT PartEVT = Val.getValueType();
  263. if (PartEVT == ValueVT)
  264. return Val;
  265. if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
  266. ValueVT.bitsLT(PartEVT)) {
  267. // For an FP value in an integer part, we need to truncate to the right
  268. // width first.
  269. PartEVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  270. Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
  271. }
  272. // Handle types that have the same size.
  273. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
  274. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  275. // Handle types with different sizes.
  276. if (PartEVT.isInteger() && ValueVT.isInteger()) {
  277. if (ValueVT.bitsLT(PartEVT)) {
  278. // For a truncate, see if we have any information to
  279. // indicate whether the truncated bits will always be
  280. // zero or sign-extension.
  281. if (AssertOp.hasValue())
  282. Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
  283. DAG.getValueType(ValueVT));
  284. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  285. }
  286. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  287. }
  288. if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  289. // FP_ROUND's are always exact here.
  290. if (ValueVT.bitsLT(Val.getValueType()))
  291. return DAG.getNode(
  292. ISD::FP_ROUND, DL, ValueVT, Val,
  293. DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
  294. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  295. }
  296. // Handle MMX to a narrower integer type by bitcasting MMX to integer and
  297. // then truncating.
  298. if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
  299. ValueVT.bitsLT(PartEVT)) {
  300. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
  301. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  302. }
  303. report_fatal_error("Unknown mismatch in getCopyFromParts!");
  304. }
  305. static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
  306. const Twine &ErrMsg) {
  307. const Instruction *I = dyn_cast_or_null<Instruction>(V);
  308. if (!V)
  309. return Ctx.emitError(ErrMsg);
  310. const char *AsmError = ", possible invalid constraint for vector type";
  311. if (const CallInst *CI = dyn_cast<CallInst>(I))
  312. if (isa<InlineAsm>(CI->getCalledValue()))
  313. return Ctx.emitError(I, ErrMsg + AsmError);
  314. return Ctx.emitError(I, ErrMsg);
  315. }
  316. /// getCopyFromPartsVector - Create a value that contains the specified legal
  317. /// parts combined into the value they represent. If the parts combine to a
  318. /// type larger than ValueVT then AssertOp can be used to specify whether the
  319. /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
  320. /// ValueVT (ISD::AssertSext).
  321. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  322. const SDValue *Parts, unsigned NumParts,
  323. MVT PartVT, EVT ValueVT, const Value *V,
  324. Optional<CallingConv::ID> CallConv) {
  325. assert(ValueVT.isVector() && "Not a vector value");
  326. assert(NumParts > 0 && "No parts to assemble!");
  327. const bool IsABIRegCopy = CallConv.hasValue();
  328. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  329. SDValue Val = Parts[0];
  330. // Handle a multi-element vector.
  331. if (NumParts > 1) {
  332. EVT IntermediateVT;
  333. MVT RegisterVT;
  334. unsigned NumIntermediates;
  335. unsigned NumRegs;
  336. if (IsABIRegCopy) {
  337. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  338. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  339. NumIntermediates, RegisterVT);
  340. } else {
  341. NumRegs =
  342. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  343. NumIntermediates, RegisterVT);
  344. }
  345. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  346. NumParts = NumRegs; // Silence a compiler warning.
  347. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  348. assert(RegisterVT.getSizeInBits() ==
  349. Parts[0].getSimpleValueType().getSizeInBits() &&
  350. "Part type sizes don't match!");
  351. // Assemble the parts into intermediate operands.
  352. SmallVector<SDValue, 8> Ops(NumIntermediates);
  353. if (NumIntermediates == NumParts) {
  354. // If the register was not expanded, truncate or copy the value,
  355. // as appropriate.
  356. for (unsigned i = 0; i != NumParts; ++i)
  357. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  358. PartVT, IntermediateVT, V);
  359. } else if (NumParts > 0) {
  360. // If the intermediate type was expanded, build the intermediate
  361. // operands from the parts.
  362. assert(NumParts % NumIntermediates == 0 &&
  363. "Must expand into a divisible number of parts!");
  364. unsigned Factor = NumParts / NumIntermediates;
  365. for (unsigned i = 0; i != NumIntermediates; ++i)
  366. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  367. PartVT, IntermediateVT, V);
  368. }
  369. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  370. // intermediate operands.
  371. EVT BuiltVectorTy =
  372. EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
  373. (IntermediateVT.isVector()
  374. ? IntermediateVT.getVectorNumElements() * NumParts
  375. : NumIntermediates));
  376. Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
  377. : ISD::BUILD_VECTOR,
  378. DL, BuiltVectorTy, Ops);
  379. }
  380. // There is now one part, held in Val. Correct it to match ValueVT.
  381. EVT PartEVT = Val.getValueType();
  382. if (PartEVT == ValueVT)
  383. return Val;
  384. if (PartEVT.isVector()) {
  385. // If the element type of the source/dest vectors are the same, but the
  386. // parts vector has more elements than the value vector, then we have a
  387. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  388. // elements we want.
  389. if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  390. assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  391. "Cannot narrow, it would be a lossy transformation");
  392. return DAG.getNode(
  393. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  394. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  395. }
  396. // Vector/Vector bitcast.
  397. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
  398. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  399. assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
  400. "Cannot handle this kind of promotion");
  401. // Promoted vector extract
  402. return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
  403. }
  404. // Trivial bitcast if the types are the same size and the destination
  405. // vector type is legal.
  406. if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
  407. TLI.isTypeLegal(ValueVT))
  408. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  409. if (ValueVT.getVectorNumElements() != 1) {
  410. // Certain ABIs require that vectors are passed as integers. For vectors
  411. // are the same size, this is an obvious bitcast.
  412. if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
  413. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  414. } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
  415. // Bitcast Val back the original type and extract the corresponding
  416. // vector we want.
  417. unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
  418. EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
  419. ValueVT.getVectorElementType(), Elts);
  420. Val = DAG.getBitcast(WiderVecType, Val);
  421. return DAG.getNode(
  422. ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  423. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  424. }
  425. diagnosePossiblyInvalidConstraint(
  426. *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
  427. return DAG.getUNDEF(ValueVT);
  428. }
  429. // Handle cases such as i8 -> <1 x i1>
  430. EVT ValueSVT = ValueVT.getVectorElementType();
  431. if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
  432. Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
  433. : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
  434. return DAG.getBuildVector(ValueVT, DL, Val);
  435. }
  436. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
  437. SDValue Val, SDValue *Parts, unsigned NumParts,
  438. MVT PartVT, const Value *V,
  439. Optional<CallingConv::ID> CallConv);
  440. /// getCopyToParts - Create a series of nodes that contain the specified value
  441. /// split into legal parts. If the parts contain more bits than Val, then, for
  442. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  443. static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
  444. SDValue *Parts, unsigned NumParts, MVT PartVT,
  445. const Value *V,
  446. Optional<CallingConv::ID> CallConv = None,
  447. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  448. EVT ValueVT = Val.getValueType();
  449. // Handle the vector case separately.
  450. if (ValueVT.isVector())
  451. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
  452. CallConv);
  453. unsigned PartBits = PartVT.getSizeInBits();
  454. unsigned OrigNumParts = NumParts;
  455. assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
  456. "Copying to an illegal type!");
  457. if (NumParts == 0)
  458. return;
  459. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  460. EVT PartEVT = PartVT;
  461. if (PartEVT == ValueVT) {
  462. assert(NumParts == 1 && "No-op copy with multiple parts!");
  463. Parts[0] = Val;
  464. return;
  465. }
  466. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  467. // If the parts cover more bits than the value has, promote the value.
  468. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  469. assert(NumParts == 1 && "Do not know what to promote to!");
  470. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  471. } else {
  472. if (ValueVT.isFloatingPoint()) {
  473. // FP values need to be bitcast, then extended if they are being put
  474. // into a larger container.
  475. ValueVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  476. Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  477. }
  478. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  479. ValueVT.isInteger() &&
  480. "Unknown mismatch!");
  481. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  482. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  483. if (PartVT == MVT::x86mmx)
  484. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  485. }
  486. } else if (PartBits == ValueVT.getSizeInBits()) {
  487. // Different types of the same size.
  488. assert(NumParts == 1 && PartEVT != ValueVT);
  489. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  490. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  491. // If the parts cover less bits than value has, truncate the value.
  492. assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
  493. ValueVT.isInteger() &&
  494. "Unknown mismatch!");
  495. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  496. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  497. if (PartVT == MVT::x86mmx)
  498. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  499. }
  500. // The value may have changed - recompute ValueVT.
  501. ValueVT = Val.getValueType();
  502. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  503. "Failed to tile the value with PartVT!");
  504. if (NumParts == 1) {
  505. if (PartEVT != ValueVT) {
  506. diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
  507. "scalar-to-vector conversion failed");
  508. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  509. }
  510. Parts[0] = Val;
  511. return;
  512. }
  513. // Expand the value into multiple parts.
  514. if (NumParts & (NumParts - 1)) {
  515. // The number of parts is not a power of 2. Split off and copy the tail.
  516. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  517. "Do not know what to expand to!");
  518. unsigned RoundParts = 1 << Log2_32(NumParts);
  519. unsigned RoundBits = RoundParts * PartBits;
  520. unsigned OddParts = NumParts - RoundParts;
  521. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  522. DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
  523. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
  524. CallConv);
  525. if (DAG.getDataLayout().isBigEndian())
  526. // The odd parts were reversed by getCopyToParts - unreverse them.
  527. std::reverse(Parts + RoundParts, Parts + NumParts);
  528. NumParts = RoundParts;
  529. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  530. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  531. }
  532. // The number of parts is a power of 2. Repeatedly bisect the value using
  533. // EXTRACT_ELEMENT.
  534. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  535. EVT::getIntegerVT(*DAG.getContext(),
  536. ValueVT.getSizeInBits()),
  537. Val);
  538. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  539. for (unsigned i = 0; i < NumParts; i += StepSize) {
  540. unsigned ThisBits = StepSize * PartBits / 2;
  541. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  542. SDValue &Part0 = Parts[i];
  543. SDValue &Part1 = Parts[i+StepSize/2];
  544. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  545. ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
  546. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  547. ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
  548. if (ThisBits == PartBits && ThisVT != PartVT) {
  549. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  550. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  551. }
  552. }
  553. }
  554. if (DAG.getDataLayout().isBigEndian())
  555. std::reverse(Parts, Parts + OrigNumParts);
  556. }
  557. static SDValue widenVectorToPartType(SelectionDAG &DAG,
  558. SDValue Val, const SDLoc &DL, EVT PartVT) {
  559. if (!PartVT.isVector())
  560. return SDValue();
  561. EVT ValueVT = Val.getValueType();
  562. unsigned PartNumElts = PartVT.getVectorNumElements();
  563. unsigned ValueNumElts = ValueVT.getVectorNumElements();
  564. if (PartNumElts > ValueNumElts &&
  565. PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  566. EVT ElementVT = PartVT.getVectorElementType();
  567. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  568. // undef elements.
  569. SmallVector<SDValue, 16> Ops;
  570. DAG.ExtractVectorElements(Val, Ops);
  571. SDValue EltUndef = DAG.getUNDEF(ElementVT);
  572. for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
  573. Ops.push_back(EltUndef);
  574. // FIXME: Use CONCAT for 2x -> 4x.
  575. return DAG.getBuildVector(PartVT, DL, Ops);
  576. }
  577. return SDValue();
  578. }
  579. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  580. /// value split into legal parts.
  581. static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
  582. SDValue Val, SDValue *Parts, unsigned NumParts,
  583. MVT PartVT, const Value *V,
  584. Optional<CallingConv::ID> CallConv) {
  585. EVT ValueVT = Val.getValueType();
  586. assert(ValueVT.isVector() && "Not a vector");
  587. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  588. const bool IsABIRegCopy = CallConv.hasValue();
  589. if (NumParts == 1) {
  590. EVT PartEVT = PartVT;
  591. if (PartEVT == ValueVT) {
  592. // Nothing to do.
  593. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  594. // Bitconvert vector->vector case.
  595. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  596. } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
  597. Val = Widened;
  598. } else if (PartVT.isVector() &&
  599. PartEVT.getVectorElementType().bitsGE(
  600. ValueVT.getVectorElementType()) &&
  601. PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
  602. // Promoted vector extract
  603. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  604. } else {
  605. if (ValueVT.getVectorNumElements() == 1) {
  606. Val = DAG.getNode(
  607. ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
  608. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  609. } else {
  610. assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
  611. "lossy conversion of vector to scalar type");
  612. EVT IntermediateType =
  613. EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  614. Val = DAG.getBitcast(IntermediateType, Val);
  615. Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
  616. }
  617. }
  618. assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
  619. Parts[0] = Val;
  620. return;
  621. }
  622. // Handle a multi-element vector.
  623. EVT IntermediateVT;
  624. MVT RegisterVT;
  625. unsigned NumIntermediates;
  626. unsigned NumRegs;
  627. if (IsABIRegCopy) {
  628. NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
  629. *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
  630. NumIntermediates, RegisterVT);
  631. } else {
  632. NumRegs =
  633. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  634. NumIntermediates, RegisterVT);
  635. }
  636. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  637. NumParts = NumRegs; // Silence a compiler warning.
  638. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  639. unsigned IntermediateNumElts = IntermediateVT.isVector() ?
  640. IntermediateVT.getVectorNumElements() : 1;
  641. // Convert the vector to the appropiate type if necessary.
  642. unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
  643. EVT BuiltVectorTy = EVT::getVectorVT(
  644. *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
  645. MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  646. if (ValueVT != BuiltVectorTy) {
  647. if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
  648. Val = Widened;
  649. Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
  650. }
  651. // Split the vector into intermediate operands.
  652. SmallVector<SDValue, 8> Ops(NumIntermediates);
  653. for (unsigned i = 0; i != NumIntermediates; ++i) {
  654. if (IntermediateVT.isVector()) {
  655. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
  656. DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
  657. } else {
  658. Ops[i] = DAG.getNode(
  659. ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
  660. DAG.getConstant(i, DL, IdxVT));
  661. }
  662. }
  663. // Split the intermediate operands into legal parts.
  664. if (NumParts == NumIntermediates) {
  665. // If the register was not expanded, promote or copy the value,
  666. // as appropriate.
  667. for (unsigned i = 0; i != NumParts; ++i)
  668. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
  669. } else if (NumParts > 0) {
  670. // If the intermediate type was expanded, split each the value into
  671. // legal parts.
  672. assert(NumIntermediates != 0 && "division by zero");
  673. assert(NumParts % NumIntermediates == 0 &&
  674. "Must expand into a divisible number of parts!");
  675. unsigned Factor = NumParts / NumIntermediates;
  676. for (unsigned i = 0; i != NumIntermediates; ++i)
  677. getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
  678. CallConv);
  679. }
  680. }
  681. RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
  682. EVT valuevt, Optional<CallingConv::ID> CC)
  683. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
  684. RegCount(1, regs.size()), CallConv(CC) {}
  685. RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
  686. const DataLayout &DL, unsigned Reg, Type *Ty,
  687. Optional<CallingConv::ID> CC) {
  688. ComputeValueVTs(TLI, DL, Ty, ValueVTs);
  689. CallConv = CC;
  690. for (EVT ValueVT : ValueVTs) {
  691. unsigned NumRegs =
  692. isABIMangled()
  693. ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
  694. : TLI.getNumRegisters(Context, ValueVT);
  695. MVT RegisterVT =
  696. isABIMangled()
  697. ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
  698. : TLI.getRegisterType(Context, ValueVT);
  699. for (unsigned i = 0; i != NumRegs; ++i)
  700. Regs.push_back(Reg + i);
  701. RegVTs.push_back(RegisterVT);
  702. RegCount.push_back(NumRegs);
  703. Reg += NumRegs;
  704. }
  705. }
  706. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  707. FunctionLoweringInfo &FuncInfo,
  708. const SDLoc &dl, SDValue &Chain,
  709. SDValue *Flag, const Value *V) const {
  710. // A Value with type {} or [0 x %t] needs no registers.
  711. if (ValueVTs.empty())
  712. return SDValue();
  713. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  714. // Assemble the legal parts into the final values.
  715. SmallVector<SDValue, 4> Values(ValueVTs.size());
  716. SmallVector<SDValue, 8> Parts;
  717. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  718. // Copy the legal parts from the registers.
  719. EVT ValueVT = ValueVTs[Value];
  720. unsigned NumRegs = RegCount[Value];
  721. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  722. *DAG.getContext(),
  723. CallConv.getValue(), RegVTs[Value])
  724. : RegVTs[Value];
  725. Parts.resize(NumRegs);
  726. for (unsigned i = 0; i != NumRegs; ++i) {
  727. SDValue P;
  728. if (!Flag) {
  729. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  730. } else {
  731. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  732. *Flag = P.getValue(2);
  733. }
  734. Chain = P.getValue(1);
  735. Parts[i] = P;
  736. // If the source register was virtual and if we know something about it,
  737. // add an assert node.
  738. if (!Register::isVirtualRegister(Regs[Part + i]) ||
  739. !RegisterVT.isInteger())
  740. continue;
  741. const FunctionLoweringInfo::LiveOutInfo *LOI =
  742. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  743. if (!LOI)
  744. continue;
  745. unsigned RegSize = RegisterVT.getScalarSizeInBits();
  746. unsigned NumSignBits = LOI->NumSignBits;
  747. unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
  748. if (NumZeroBits == RegSize) {
  749. // The current value is a zero.
  750. // Explicitly express that as it would be easier for
  751. // optimizations to kick in.
  752. Parts[i] = DAG.getConstant(0, dl, RegisterVT);
  753. continue;
  754. }
  755. // FIXME: We capture more information than the dag can represent. For
  756. // now, just use the tightest assertzext/assertsext possible.
  757. bool isSExt;
  758. EVT FromVT(MVT::Other);
  759. if (NumZeroBits) {
  760. FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
  761. isSExt = false;
  762. } else if (NumSignBits > 1) {
  763. FromVT =
  764. EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
  765. isSExt = true;
  766. } else {
  767. continue;
  768. }
  769. // Add an assertion node.
  770. assert(FromVT != MVT::Other);
  771. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  772. RegisterVT, P, DAG.getValueType(FromVT));
  773. }
  774. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
  775. RegisterVT, ValueVT, V, CallConv);
  776. Part += NumRegs;
  777. Parts.clear();
  778. }
  779. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
  780. }
  781. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
  782. const SDLoc &dl, SDValue &Chain, SDValue *Flag,
  783. const Value *V,
  784. ISD::NodeType PreferredExtendType) const {
  785. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  786. ISD::NodeType ExtendKind = PreferredExtendType;
  787. // Get the list of the values's legal parts.
  788. unsigned NumRegs = Regs.size();
  789. SmallVector<SDValue, 8> Parts(NumRegs);
  790. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  791. unsigned NumParts = RegCount[Value];
  792. MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
  793. *DAG.getContext(),
  794. CallConv.getValue(), RegVTs[Value])
  795. : RegVTs[Value];
  796. if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
  797. ExtendKind = ISD::ZERO_EXTEND;
  798. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
  799. NumParts, RegisterVT, V, CallConv, ExtendKind);
  800. Part += NumParts;
  801. }
  802. // Copy the parts into the registers.
  803. SmallVector<SDValue, 8> Chains(NumRegs);
  804. for (unsigned i = 0; i != NumRegs; ++i) {
  805. SDValue Part;
  806. if (!Flag) {
  807. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  808. } else {
  809. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  810. *Flag = Part.getValue(1);
  811. }
  812. Chains[i] = Part.getValue(0);
  813. }
  814. if (NumRegs == 1 || Flag)
  815. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  816. // flagged to it. That is the CopyToReg nodes and the user are considered
  817. // a single scheduling unit. If we create a TokenFactor and return it as
  818. // chain, then the TokenFactor is both a predecessor (operand) of the
  819. // user as well as a successor (the TF operands are flagged to the user).
  820. // c1, f1 = CopyToReg
  821. // c2, f2 = CopyToReg
  822. // c3 = TokenFactor c1, c2
  823. // ...
  824. // = op c3, ..., f2
  825. Chain = Chains[NumRegs-1];
  826. else
  827. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  828. }
  829. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  830. unsigned MatchingIdx, const SDLoc &dl,
  831. SelectionDAG &DAG,
  832. std::vector<SDValue> &Ops) const {
  833. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  834. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  835. if (HasMatching)
  836. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  837. else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
  838. // Put the register class of the virtual registers in the flag word. That
  839. // way, later passes can recompute register class constraints for inline
  840. // assembly as well as normal instructions.
  841. // Don't do this for tied operands that can use the regclass information
  842. // from the def.
  843. const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
  844. const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
  845. Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
  846. }
  847. SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
  848. Ops.push_back(Res);
  849. if (Code == InlineAsm::Kind_Clobber) {
  850. // Clobbers should always have a 1:1 mapping with registers, and may
  851. // reference registers that have illegal (e.g. vector) types. Hence, we
  852. // shouldn't try to apply any sort of splitting logic to them.
  853. assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
  854. "No 1:1 mapping from clobbers to regs?");
  855. unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
  856. (void)SP;
  857. for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
  858. Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
  859. assert(
  860. (Regs[I] != SP ||
  861. DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
  862. "If we clobbered the stack pointer, MFI should know about it.");
  863. }
  864. return;
  865. }
  866. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  867. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  868. MVT RegisterVT = RegVTs[Value];
  869. for (unsigned i = 0; i != NumRegs; ++i) {
  870. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  871. unsigned TheReg = Regs[Reg++];
  872. Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
  873. }
  874. }
  875. }
  876. SmallVector<std::pair<unsigned, unsigned>, 4>
  877. RegsForValue::getRegsAndSizes() const {
  878. SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
  879. unsigned I = 0;
  880. for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
  881. unsigned RegCount = std::get<0>(CountAndVT);
  882. MVT RegisterVT = std::get<1>(CountAndVT);
  883. unsigned RegisterSize = RegisterVT.getSizeInBits();
  884. for (unsigned E = I + RegCount; I != E; ++I)
  885. OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
  886. }
  887. return OutVec;
  888. }
  889. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
  890. const TargetLibraryInfo *li) {
  891. AA = aa;
  892. GFI = gfi;
  893. LibInfo = li;
  894. DL = &DAG.getDataLayout();
  895. Context = DAG.getContext();
  896. LPadToCallSiteMap.clear();
  897. SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
  898. }
  899. void SelectionDAGBuilder::clear() {
  900. NodeMap.clear();
  901. UnusedArgNodeMap.clear();
  902. PendingLoads.clear();
  903. PendingExports.clear();
  904. CurInst = nullptr;
  905. HasTailCall = false;
  906. SDNodeOrder = LowestSDNodeOrder;
  907. StatepointLowering.clear();
  908. }
  909. void SelectionDAGBuilder::clearDanglingDebugInfo() {
  910. DanglingDebugInfoMap.clear();
  911. }
  912. SDValue SelectionDAGBuilder::getRoot() {
  913. if (PendingLoads.empty())
  914. return DAG.getRoot();
  915. if (PendingLoads.size() == 1) {
  916. SDValue Root = PendingLoads[0];
  917. DAG.setRoot(Root);
  918. PendingLoads.clear();
  919. return Root;
  920. }
  921. // Otherwise, we have to make a token factor node.
  922. SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
  923. PendingLoads.clear();
  924. DAG.setRoot(Root);
  925. return Root;
  926. }
  927. SDValue SelectionDAGBuilder::getControlRoot() {
  928. SDValue Root = DAG.getRoot();
  929. if (PendingExports.empty())
  930. return Root;
  931. // Turn all of the CopyToReg chains into one factored node.
  932. if (Root.getOpcode() != ISD::EntryToken) {
  933. unsigned i = 0, e = PendingExports.size();
  934. for (; i != e; ++i) {
  935. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  936. if (PendingExports[i].getNode()->getOperand(0) == Root)
  937. break; // Don't add the root if we already indirectly depend on it.
  938. }
  939. if (i == e)
  940. PendingExports.push_back(Root);
  941. }
  942. Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
  943. PendingExports);
  944. PendingExports.clear();
  945. DAG.setRoot(Root);
  946. return Root;
  947. }
  948. void SelectionDAGBuilder::visit(const Instruction &I) {
  949. // Set up outgoing PHI node register values before emitting the terminator.
  950. if (I.isTerminator()) {
  951. HandlePHINodesInSuccessorBlocks(I.getParent());
  952. }
  953. // Increase the SDNodeOrder if dealing with a non-debug instruction.
  954. if (!isa<DbgInfoIntrinsic>(I))
  955. ++SDNodeOrder;
  956. CurInst = &I;
  957. visit(I.getOpcode(), I);
  958. if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
  959. // Propagate the fast-math-flags of this IR instruction to the DAG node that
  960. // maps to this instruction.
  961. // TODO: We could handle all flags (nsw, etc) here.
  962. // TODO: If an IR instruction maps to >1 node, only the final node will have
  963. // flags set.
  964. if (SDNode *Node = getNodeForIRValue(&I)) {
  965. SDNodeFlags IncomingFlags;
  966. IncomingFlags.copyFMF(*FPMO);
  967. if (!Node->getFlags().isDefined())
  968. Node->setFlags(IncomingFlags);
  969. else
  970. Node->intersectFlagsWith(IncomingFlags);
  971. }
  972. }
  973. if (!I.isTerminator() && !HasTailCall &&
  974. !isStatepoint(&I)) // statepoints handle their exports internally
  975. CopyToExportRegsIfNeeded(&I);
  976. CurInst = nullptr;
  977. }
  978. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  979. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  980. }
  981. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  982. // Note: this doesn't use InstVisitor, because it has to work with
  983. // ConstantExpr's in addition to instructions.
  984. switch (Opcode) {
  985. default: llvm_unreachable("Unknown instruction type encountered!");
  986. // Build the switch statement using the Instruction.def file.
  987. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  988. case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
  989. #include "llvm/IR/Instruction.def"
  990. }
  991. }
  992. void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
  993. const DIExpression *Expr) {
  994. auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
  995. const DbgValueInst *DI = DDI.getDI();
  996. DIVariable *DanglingVariable = DI->getVariable();
  997. DIExpression *DanglingExpr = DI->getExpression();
  998. if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
  999. LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
  1000. return true;
  1001. }
  1002. return false;
  1003. };
  1004. for (auto &DDIMI : DanglingDebugInfoMap) {
  1005. DanglingDebugInfoVector &DDIV = DDIMI.second;
  1006. // If debug info is to be dropped, run it through final checks to see
  1007. // whether it can be salvaged.
  1008. for (auto &DDI : DDIV)
  1009. if (isMatchingDbgValue(DDI))
  1010. salvageUnresolvedDbgValue(DDI);
  1011. DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
  1012. }
  1013. }
  1014. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  1015. // generate the debug data structures now that we've seen its definition.
  1016. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  1017. SDValue Val) {
  1018. auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
  1019. if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
  1020. return;
  1021. DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
  1022. for (auto &DDI : DDIV) {
  1023. const DbgValueInst *DI = DDI.getDI();
  1024. assert(DI && "Ill-formed DanglingDebugInfo");
  1025. DebugLoc dl = DDI.getdl();
  1026. unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
  1027. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  1028. DILocalVariable *Variable = DI->getVariable();
  1029. DIExpression *Expr = DI->getExpression();
  1030. assert(Variable->isValidLocationForIntrinsic(dl) &&
  1031. "Expected inlined-at fields to agree");
  1032. SDDbgValue *SDV;
  1033. if (Val.getNode()) {
  1034. // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
  1035. // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
  1036. // we couldn't resolve it directly when examining the DbgValue intrinsic
  1037. // in the first place we should not be more successful here). Unless we
  1038. // have some test case that prove this to be correct we should avoid
  1039. // calling EmitFuncArgumentDbgValue here.
  1040. if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
  1041. LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
  1042. << DbgSDNodeOrder << "] for:\n " << *DI << "\n");
  1043. LLVM_DEBUG(dbgs() << " By mapping to:\n "; Val.dump());
  1044. // Increase the SDNodeOrder for the DbgValue here to make sure it is
  1045. // inserted after the definition of Val when emitting the instructions
  1046. // after ISel. An alternative could be to teach
  1047. // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
  1048. LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
  1049. << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
  1050. << ValSDNodeOrder << "\n");
  1051. SDV = getDbgValue(Val, Variable, Expr, dl,
  1052. std::max(DbgSDNodeOrder, ValSDNodeOrder));
  1053. DAG.AddDbgValue(SDV, Val.getNode(), false);
  1054. } else
  1055. LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
  1056. << "in EmitFuncArgumentDbgValue\n");
  1057. } else {
  1058. LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
  1059. auto Undef =
  1060. UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1061. auto SDV =
  1062. DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
  1063. DAG.AddDbgValue(SDV, nullptr, false);
  1064. }
  1065. }
  1066. DDIV.clear();
  1067. }
  1068. void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
  1069. Value *V = DDI.getDI()->getValue();
  1070. DILocalVariable *Var = DDI.getDI()->getVariable();
  1071. DIExpression *Expr = DDI.getDI()->getExpression();
  1072. DebugLoc DL = DDI.getdl();
  1073. DebugLoc InstDL = DDI.getDI()->getDebugLoc();
  1074. unsigned SDOrder = DDI.getSDNodeOrder();
  1075. // Currently we consider only dbg.value intrinsics -- we tell the salvager
  1076. // that DW_OP_stack_value is desired.
  1077. assert(isa<DbgValueInst>(DDI.getDI()));
  1078. bool StackValue = true;
  1079. // Can this Value can be encoded without any further work?
  1080. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
  1081. return;
  1082. // Attempt to salvage back through as many instructions as possible. Bail if
  1083. // a non-instruction is seen, such as a constant expression or global
  1084. // variable. FIXME: Further work could recover those too.
  1085. while (isa<Instruction>(V)) {
  1086. Instruction &VAsInst = *cast<Instruction>(V);
  1087. DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
  1088. // If we cannot salvage any further, and haven't yet found a suitable debug
  1089. // expression, bail out.
  1090. if (!NewExpr)
  1091. break;
  1092. // New value and expr now represent this debuginfo.
  1093. V = VAsInst.getOperand(0);
  1094. Expr = NewExpr;
  1095. // Some kind of simplification occurred: check whether the operand of the
  1096. // salvaged debug expression can be encoded in this DAG.
  1097. if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
  1098. LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n "
  1099. << DDI.getDI() << "\nBy stripping back to:\n " << V);
  1100. return;
  1101. }
  1102. }
  1103. // This was the final opportunity to salvage this debug information, and it
  1104. // couldn't be done. Place an undef DBG_VALUE at this location to terminate
  1105. // any earlier variable location.
  1106. auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
  1107. auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
  1108. DAG.AddDbgValue(SDV, nullptr, false);
  1109. LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n " << DDI.getDI()
  1110. << "\n");
  1111. LLVM_DEBUG(dbgs() << " Last seen at:\n " << *DDI.getDI()->getOperand(0)
  1112. << "\n");
  1113. }
  1114. bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
  1115. DIExpression *Expr, DebugLoc dl,
  1116. DebugLoc InstDL, unsigned Order) {
  1117. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1118. SDDbgValue *SDV;
  1119. if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
  1120. isa<ConstantPointerNull>(V)) {
  1121. SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
  1122. DAG.AddDbgValue(SDV, nullptr, false);
  1123. return true;
  1124. }
  1125. // If the Value is a frame index, we can create a FrameIndex debug value
  1126. // without relying on the DAG at all.
  1127. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1128. auto SI = FuncInfo.StaticAllocaMap.find(AI);
  1129. if (SI != FuncInfo.StaticAllocaMap.end()) {
  1130. auto SDV =
  1131. DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
  1132. /*IsIndirect*/ false, dl, SDNodeOrder);
  1133. // Do not attach the SDNodeDbgValue to an SDNode: this variable location
  1134. // is still available even if the SDNode gets optimized out.
  1135. DAG.AddDbgValue(SDV, nullptr, false);
  1136. return true;
  1137. }
  1138. }
  1139. // Do not use getValue() in here; we don't want to generate code at
  1140. // this point if it hasn't been done yet.
  1141. SDValue N = NodeMap[V];
  1142. if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
  1143. N = UnusedArgNodeMap[V];
  1144. if (N.getNode()) {
  1145. if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
  1146. return true;
  1147. SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
  1148. DAG.AddDbgValue(SDV, N.getNode(), false);
  1149. return true;
  1150. }
  1151. // Special rules apply for the first dbg.values of parameter variables in a
  1152. // function. Identify them by the fact they reference Argument Values, that
  1153. // they're parameters, and they are parameters of the current function. We
  1154. // need to let them dangle until they get an SDNode.
  1155. bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
  1156. !InstDL.getInlinedAt();
  1157. if (!IsParamOfFunc) {
  1158. // The value is not used in this block yet (or it would have an SDNode).
  1159. // We still want the value to appear for the user if possible -- if it has
  1160. // an associated VReg, we can refer to that instead.
  1161. auto VMI = FuncInfo.ValueMap.find(V);
  1162. if (VMI != FuncInfo.ValueMap.end()) {
  1163. unsigned Reg = VMI->second;
  1164. // If this is a PHI node, it may be split up into several MI PHI nodes
  1165. // (in FunctionLoweringInfo::set).
  1166. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
  1167. V->getType(), None);
  1168. if (RFV.occupiesMultipleRegs()) {
  1169. unsigned Offset = 0;
  1170. unsigned BitsToDescribe = 0;
  1171. if (auto VarSize = Var->getSizeInBits())
  1172. BitsToDescribe = *VarSize;
  1173. if (auto Fragment = Expr->getFragmentInfo())
  1174. BitsToDescribe = Fragment->SizeInBits;
  1175. for (auto RegAndSize : RFV.getRegsAndSizes()) {
  1176. unsigned RegisterSize = RegAndSize.second;
  1177. // Bail out if all bits are described already.
  1178. if (Offset >= BitsToDescribe)
  1179. break;
  1180. unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
  1181. ? BitsToDescribe - Offset
  1182. : RegisterSize;
  1183. auto FragmentExpr = DIExpression::createFragmentExpression(
  1184. Expr, Offset, FragmentSize);
  1185. if (!FragmentExpr)
  1186. continue;
  1187. SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
  1188. false, dl, SDNodeOrder);
  1189. DAG.AddDbgValue(SDV, nullptr, false);
  1190. Offset += RegisterSize;
  1191. }
  1192. } else {
  1193. SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
  1194. DAG.AddDbgValue(SDV, nullptr, false);
  1195. }
  1196. return true;
  1197. }
  1198. }
  1199. return false;
  1200. }
  1201. void SelectionDAGBuilder::resolveOrClearDbgInfo() {
  1202. // Try to fixup any remaining dangling debug info -- and drop it if we can't.
  1203. for (auto &Pair : DanglingDebugInfoMap)
  1204. for (auto &DDI : Pair.second)
  1205. salvageUnresolvedDbgValue(DDI);
  1206. clearDanglingDebugInfo();
  1207. }
  1208. /// getCopyFromRegs - If there was virtual register allocated for the value V
  1209. /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
  1210. SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
  1211. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  1212. SDValue Result;
  1213. if (It != FuncInfo.ValueMap.end()) {
  1214. unsigned InReg = It->second;
  1215. RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
  1216. DAG.getDataLayout(), InReg, Ty,
  1217. None); // This is not an ABI copy.
  1218. SDValue Chain = DAG.getEntryNode();
  1219. Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
  1220. V);
  1221. resolveDanglingDebugInfo(V, Result);
  1222. }
  1223. return Result;
  1224. }
  1225. /// getValue - Return an SDValue for the given Value.
  1226. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  1227. // If we already have an SDValue for this value, use it. It's important
  1228. // to do this first, so that we don't create a CopyFromReg if we already
  1229. // have a regular SDValue.
  1230. SDValue &N = NodeMap[V];
  1231. if (N.getNode()) return N;
  1232. // If there's a virtual register allocated and initialized for this
  1233. // value, use it.
  1234. if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
  1235. return copyFromReg;
  1236. // Otherwise create a new SDValue and remember it.
  1237. SDValue Val = getValueImpl(V);
  1238. NodeMap[V] = Val;
  1239. resolveDanglingDebugInfo(V, Val);
  1240. return Val;
  1241. }
  1242. // Return true if SDValue exists for the given Value
  1243. bool SelectionDAGBuilder::findValue(const Value *V) const {
  1244. return (NodeMap.find(V) != NodeMap.end()) ||
  1245. (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
  1246. }
  1247. /// getNonRegisterValue - Return an SDValue for the given Value, but
  1248. /// don't look in FuncInfo.ValueMap for a virtual register.
  1249. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  1250. // If we already have an SDValue for this value, use it.
  1251. SDValue &N = NodeMap[V];
  1252. if (N.getNode()) {
  1253. if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
  1254. // Remove the debug location from the node as the node is about to be used
  1255. // in a location which may differ from the original debug location. This
  1256. // is relevant to Constant and ConstantFP nodes because they can appear
  1257. // as constant expressions inside PHI nodes.
  1258. N->setDebugLoc(DebugLoc());
  1259. }
  1260. return N;
  1261. }
  1262. // Otherwise create a new SDValue and remember it.
  1263. SDValue Val = getValueImpl(V);
  1264. NodeMap[V] = Val;
  1265. resolveDanglingDebugInfo(V, Val);
  1266. return Val;
  1267. }
  1268. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  1269. /// Create an SDValue for the given value.
  1270. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  1271. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1272. if (const Constant *C = dyn_cast<Constant>(V)) {
  1273. EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
  1274. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  1275. return DAG.getConstant(*CI, getCurSDLoc(), VT);
  1276. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  1277. return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
  1278. if (isa<ConstantPointerNull>(C)) {
  1279. unsigned AS = V->getType()->getPointerAddressSpace();
  1280. return DAG.getConstant(0, getCurSDLoc(),
  1281. TLI.getPointerTy(DAG.getDataLayout(), AS));
  1282. }
  1283. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  1284. return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
  1285. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  1286. return DAG.getUNDEF(VT);
  1287. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1288. visit(CE->getOpcode(), *CE);
  1289. SDValue N1 = NodeMap[V];
  1290. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  1291. return N1;
  1292. }
  1293. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  1294. SmallVector<SDValue, 4> Constants;
  1295. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  1296. OI != OE; ++OI) {
  1297. SDNode *Val = getValue(*OI).getNode();
  1298. // If the operand is an empty aggregate, there are no values.
  1299. if (!Val) continue;
  1300. // Add each leaf value from the operand to the Constants list
  1301. // to form a flattened list of all the values.
  1302. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1303. Constants.push_back(SDValue(Val, i));
  1304. }
  1305. return DAG.getMergeValues(Constants, getCurSDLoc());
  1306. }
  1307. if (const ConstantDataSequential *CDS =
  1308. dyn_cast<ConstantDataSequential>(C)) {
  1309. SmallVector<SDValue, 4> Ops;
  1310. for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
  1311. SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
  1312. // Add each leaf value from the operand to the Constants list
  1313. // to form a flattened list of all the values.
  1314. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  1315. Ops.push_back(SDValue(Val, i));
  1316. }
  1317. if (isa<ArrayType>(CDS->getType()))
  1318. return DAG.getMergeValues(Ops, getCurSDLoc());
  1319. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1320. }
  1321. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  1322. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  1323. "Unknown struct or array constant!");
  1324. SmallVector<EVT, 4> ValueVTs;
  1325. ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
  1326. unsigned NumElts = ValueVTs.size();
  1327. if (NumElts == 0)
  1328. return SDValue(); // empty struct
  1329. SmallVector<SDValue, 4> Constants(NumElts);
  1330. for (unsigned i = 0; i != NumElts; ++i) {
  1331. EVT EltVT = ValueVTs[i];
  1332. if (isa<UndefValue>(C))
  1333. Constants[i] = DAG.getUNDEF(EltVT);
  1334. else if (EltVT.isFloatingPoint())
  1335. Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1336. else
  1337. Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1338. }
  1339. return DAG.getMergeValues(Constants, getCurSDLoc());
  1340. }
  1341. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  1342. return DAG.getBlockAddress(BA, VT);
  1343. VectorType *VecTy = cast<VectorType>(V->getType());
  1344. unsigned NumElements = VecTy->getNumElements();
  1345. // Now that we know the number and type of the elements, get that number of
  1346. // elements into the Ops array based on what kind of constant it is.
  1347. SmallVector<SDValue, 16> Ops;
  1348. if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
  1349. for (unsigned i = 0; i != NumElements; ++i)
  1350. Ops.push_back(getValue(CV->getOperand(i)));
  1351. } else {
  1352. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  1353. EVT EltVT =
  1354. TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
  1355. SDValue Op;
  1356. if (EltVT.isFloatingPoint())
  1357. Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
  1358. else
  1359. Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
  1360. Ops.assign(NumElements, Op);
  1361. }
  1362. // Create a BUILD_VECTOR node.
  1363. return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
  1364. }
  1365. // If this is a static alloca, generate it as the frameindex instead of
  1366. // computation.
  1367. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  1368. DenseMap<const AllocaInst*, int>::iterator SI =
  1369. FuncInfo.StaticAllocaMap.find(AI);
  1370. if (SI != FuncInfo.StaticAllocaMap.end())
  1371. return DAG.getFrameIndex(SI->second,
  1372. TLI.getFrameIndexTy(DAG.getDataLayout()));
  1373. }
  1374. // If this is an instruction which fast-isel has deferred, select it now.
  1375. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  1376. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  1377. RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
  1378. Inst->getType(), getABIRegCopyCC(V));
  1379. SDValue Chain = DAG.getEntryNode();
  1380. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
  1381. }
  1382. llvm_unreachable("Can't get register for value!");
  1383. }
  1384. void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
  1385. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1386. bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
  1387. bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
  1388. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1389. bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
  1390. MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
  1391. if (!IsSEH)
  1392. CatchPadMBB->setIsEHScopeEntry();
  1393. // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
  1394. if (IsMSVCCXX || IsCoreCLR)
  1395. CatchPadMBB->setIsEHFuncletEntry();
  1396. // Wasm does not need catchpads anymore
  1397. if (!IsWasmCXX)
  1398. DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
  1399. getControlRoot()));
  1400. }
  1401. void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
  1402. // Update machine-CFG edge.
  1403. MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
  1404. FuncInfo.MBB->addSuccessor(TargetMBB);
  1405. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1406. bool IsSEH = isAsynchronousEHPersonality(Pers);
  1407. if (IsSEH) {
  1408. // If this is not a fall-through branch or optimizations are switched off,
  1409. // emit the branch.
  1410. if (TargetMBB != NextBlock(FuncInfo.MBB) ||
  1411. TM.getOptLevel() == CodeGenOpt::None)
  1412. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  1413. getControlRoot(), DAG.getBasicBlock(TargetMBB)));
  1414. return;
  1415. }
  1416. // Figure out the funclet membership for the catchret's successor.
  1417. // This will be used by the FuncletLayout pass to determine how to order the
  1418. // BB's.
  1419. // A 'catchret' returns to the outer scope's color.
  1420. Value *ParentPad = I.getCatchSwitchParentPad();
  1421. const BasicBlock *SuccessorColor;
  1422. if (isa<ConstantTokenNone>(ParentPad))
  1423. SuccessorColor = &FuncInfo.Fn->getEntryBlock();
  1424. else
  1425. SuccessorColor = cast<Instruction>(ParentPad)->getParent();
  1426. assert(SuccessorColor && "No parent funclet for catchret!");
  1427. MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
  1428. assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
  1429. // Create the terminator node.
  1430. SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
  1431. getControlRoot(), DAG.getBasicBlock(TargetMBB),
  1432. DAG.getBasicBlock(SuccessorColorMBB));
  1433. DAG.setRoot(Ret);
  1434. }
  1435. void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
  1436. // Don't emit any special code for the cleanuppad instruction. It just marks
  1437. // the start of an EH scope/funclet.
  1438. FuncInfo.MBB->setIsEHScopeEntry();
  1439. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1440. if (Pers != EHPersonality::Wasm_CXX) {
  1441. FuncInfo.MBB->setIsEHFuncletEntry();
  1442. FuncInfo.MBB->setIsCleanupFuncletEntry();
  1443. }
  1444. }
  1445. // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
  1446. // the control flow always stops at the single catch pad, as it does for a
  1447. // cleanup pad. In case the exception caught is not of the types the catch pad
  1448. // catches, it will be rethrown by a rethrow.
  1449. static void findWasmUnwindDestinations(
  1450. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1451. BranchProbability Prob,
  1452. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1453. &UnwindDests) {
  1454. while (EHPadBB) {
  1455. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1456. if (isa<CleanupPadInst>(Pad)) {
  1457. // Stop on cleanup pads.
  1458. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1459. UnwindDests.back().first->setIsEHScopeEntry();
  1460. break;
  1461. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1462. // Add the catchpad handlers to the possible destinations. We don't
  1463. // continue to the unwind destination of the catchswitch for wasm.
  1464. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1465. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1466. UnwindDests.back().first->setIsEHScopeEntry();
  1467. }
  1468. break;
  1469. } else {
  1470. continue;
  1471. }
  1472. }
  1473. }
  1474. /// When an invoke or a cleanupret unwinds to the next EH pad, there are
  1475. /// many places it could ultimately go. In the IR, we have a single unwind
  1476. /// destination, but in the machine CFG, we enumerate all the possible blocks.
  1477. /// This function skips over imaginary basic blocks that hold catchswitch
  1478. /// instructions, and finds all the "real" machine
  1479. /// basic block destinations. As those destinations may not be successors of
  1480. /// EHPadBB, here we also calculate the edge probability to those destinations.
  1481. /// The passed-in Prob is the edge probability to EHPadBB.
  1482. static void findUnwindDestinations(
  1483. FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
  1484. BranchProbability Prob,
  1485. SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
  1486. &UnwindDests) {
  1487. EHPersonality Personality =
  1488. classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  1489. bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
  1490. bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
  1491. bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
  1492. bool IsSEH = isAsynchronousEHPersonality(Personality);
  1493. if (IsWasmCXX) {
  1494. findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
  1495. assert(UnwindDests.size() <= 1 &&
  1496. "There should be at most one unwind destination for wasm");
  1497. return;
  1498. }
  1499. while (EHPadBB) {
  1500. const Instruction *Pad = EHPadBB->getFirstNonPHI();
  1501. BasicBlock *NewEHPadBB = nullptr;
  1502. if (isa<LandingPadInst>(Pad)) {
  1503. // Stop on landingpads. They are not funclets.
  1504. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1505. break;
  1506. } else if (isa<CleanupPadInst>(Pad)) {
  1507. // Stop on cleanup pads. Cleanups are always funclet entries for all known
  1508. // personalities.
  1509. UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
  1510. UnwindDests.back().first->setIsEHScopeEntry();
  1511. UnwindDests.back().first->setIsEHFuncletEntry();
  1512. break;
  1513. } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
  1514. // Add the catchpad handlers to the possible destinations.
  1515. for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
  1516. UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
  1517. // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
  1518. if (IsMSVCCXX || IsCoreCLR)
  1519. UnwindDests.back().first->setIsEHFuncletEntry();
  1520. if (!IsSEH)
  1521. UnwindDests.back().first->setIsEHScopeEntry();
  1522. }
  1523. NewEHPadBB = CatchSwitch->getUnwindDest();
  1524. } else {
  1525. continue;
  1526. }
  1527. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1528. if (BPI && NewEHPadBB)
  1529. Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
  1530. EHPadBB = NewEHPadBB;
  1531. }
  1532. }
  1533. void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
  1534. // Update successor info.
  1535. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  1536. auto UnwindDest = I.getUnwindDest();
  1537. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1538. BranchProbability UnwindDestProb =
  1539. (BPI && UnwindDest)
  1540. ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
  1541. : BranchProbability::getZero();
  1542. findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
  1543. for (auto &UnwindDest : UnwindDests) {
  1544. UnwindDest.first->setIsEHPad();
  1545. addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
  1546. }
  1547. FuncInfo.MBB->normalizeSuccProbs();
  1548. // Create the terminator node.
  1549. SDValue Ret =
  1550. DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
  1551. DAG.setRoot(Ret);
  1552. }
  1553. void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
  1554. report_fatal_error("visitCatchSwitch not yet implemented!");
  1555. }
  1556. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  1557. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1558. auto &DL = DAG.getDataLayout();
  1559. SDValue Chain = getControlRoot();
  1560. SmallVector<ISD::OutputArg, 8> Outs;
  1561. SmallVector<SDValue, 8> OutVals;
  1562. // Calls to @llvm.experimental.deoptimize don't generate a return value, so
  1563. // lower
  1564. //
  1565. // %val = call <ty> @llvm.experimental.deoptimize()
  1566. // ret <ty> %val
  1567. //
  1568. // differently.
  1569. if (I.getParent()->getTerminatingDeoptimizeCall()) {
  1570. LowerDeoptimizingReturn();
  1571. return;
  1572. }
  1573. if (!FuncInfo.CanLowerReturn) {
  1574. unsigned DemoteReg = FuncInfo.DemoteRegister;
  1575. const Function *F = I.getParent()->getParent();
  1576. // Emit a store of the return value through the virtual register.
  1577. // Leave Outs empty so that LowerReturn won't try to load return
  1578. // registers the usual way.
  1579. SmallVector<EVT, 1> PtrValueVTs;
  1580. ComputeValueVTs(TLI, DL,
  1581. F->getReturnType()->getPointerTo(
  1582. DAG.getDataLayout().getAllocaAddrSpace()),
  1583. PtrValueVTs);
  1584. SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
  1585. DemoteReg, PtrValueVTs[0]);
  1586. SDValue RetOp = getValue(I.getOperand(0));
  1587. SmallVector<EVT, 4> ValueVTs, MemVTs;
  1588. SmallVector<uint64_t, 4> Offsets;
  1589. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
  1590. &Offsets);
  1591. unsigned NumValues = ValueVTs.size();
  1592. SmallVector<SDValue, 4> Chains(NumValues);
  1593. for (unsigned i = 0; i != NumValues; ++i) {
  1594. // An aggregate return value cannot wrap around the address space, so
  1595. // offsets to its parts don't wrap either.
  1596. SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
  1597. SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
  1598. if (MemVTs[i] != ValueVTs[i])
  1599. Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
  1600. Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
  1601. // FIXME: better loc info would be nice.
  1602. Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
  1603. }
  1604. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
  1605. MVT::Other, Chains);
  1606. } else if (I.getNumOperands() != 0) {
  1607. SmallVector<EVT, 4> ValueVTs;
  1608. ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
  1609. unsigned NumValues = ValueVTs.size();
  1610. if (NumValues) {
  1611. SDValue RetOp = getValue(I.getOperand(0));
  1612. const Function *F = I.getParent()->getParent();
  1613. bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
  1614. I.getOperand(0)->getType(), F->getCallingConv(),
  1615. /*IsVarArg*/ false);
  1616. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  1617. if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1618. Attribute::SExt))
  1619. ExtendKind = ISD::SIGN_EXTEND;
  1620. else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
  1621. Attribute::ZExt))
  1622. ExtendKind = ISD::ZERO_EXTEND;
  1623. LLVMContext &Context = F->getContext();
  1624. bool RetInReg = F->getAttributes().hasAttribute(
  1625. AttributeList::ReturnIndex, Attribute::InReg);
  1626. for (unsigned j = 0; j != NumValues; ++j) {
  1627. EVT VT = ValueVTs[j];
  1628. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  1629. VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
  1630. CallingConv::ID CC = F->getCallingConv();
  1631. unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
  1632. MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
  1633. SmallVector<SDValue, 4> Parts(NumParts);
  1634. getCopyToParts(DAG, getCurSDLoc(),
  1635. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  1636. &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
  1637. // 'inreg' on function refers to return value
  1638. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1639. if (RetInReg)
  1640. Flags.setInReg();
  1641. if (I.getOperand(0)->getType()->isPointerTy()) {
  1642. Flags.setPointer();
  1643. Flags.setPointerAddrSpace(
  1644. cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
  1645. }
  1646. if (NeedsRegBlock) {
  1647. Flags.setInConsecutiveRegs();
  1648. if (j == NumValues - 1)
  1649. Flags.setInConsecutiveRegsLast();
  1650. }
  1651. // Propagate extension type if any
  1652. if (ExtendKind == ISD::SIGN_EXTEND)
  1653. Flags.setSExt();
  1654. else if (ExtendKind == ISD::ZERO_EXTEND)
  1655. Flags.setZExt();
  1656. for (unsigned i = 0; i < NumParts; ++i) {
  1657. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  1658. VT, /*isfixed=*/true, 0, 0));
  1659. OutVals.push_back(Parts[i]);
  1660. }
  1661. }
  1662. }
  1663. }
  1664. // Push in swifterror virtual register as the last element of Outs. This makes
  1665. // sure swifterror virtual register will be returned in the swifterror
  1666. // physical register.
  1667. const Function *F = I.getParent()->getParent();
  1668. if (TLI.supportSwiftError() &&
  1669. F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
  1670. assert(SwiftError.getFunctionArg() && "Need a swift error argument");
  1671. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  1672. Flags.setSwiftError();
  1673. Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
  1674. EVT(TLI.getPointerTy(DL)) /*argvt*/,
  1675. true /*isfixed*/, 1 /*origidx*/,
  1676. 0 /*partOffs*/));
  1677. // Create SDNode for the swifterror virtual register.
  1678. OutVals.push_back(
  1679. DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
  1680. &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
  1681. EVT(TLI.getPointerTy(DL))));
  1682. }
  1683. bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
  1684. CallingConv::ID CallConv =
  1685. DAG.getMachineFunction().getFunction().getCallingConv();
  1686. Chain = DAG.getTargetLoweringInfo().LowerReturn(
  1687. Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
  1688. // Verify that the target's LowerReturn behaved as expected.
  1689. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1690. "LowerReturn didn't return a valid chain!");
  1691. // Update the DAG with the new chain value resulting from return lowering.
  1692. DAG.setRoot(Chain);
  1693. }
  1694. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1695. /// created for it, emit nodes to copy the value into the virtual
  1696. /// registers.
  1697. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1698. // Skip empty types
  1699. if (V->getType()->isEmptyTy())
  1700. return;
  1701. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1702. if (VMI != FuncInfo.ValueMap.end()) {
  1703. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1704. CopyValueToVirtualRegister(V, VMI->second);
  1705. }
  1706. }
  1707. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1708. /// the current basic block, add it to ValueMap now so that we'll get a
  1709. /// CopyTo/FromReg.
  1710. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1711. // No need to export constants.
  1712. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1713. // Already exported?
  1714. if (FuncInfo.isExportedInst(V)) return;
  1715. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1716. CopyValueToVirtualRegister(V, Reg);
  1717. }
  1718. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1719. const BasicBlock *FromBB) {
  1720. // The operands of the setcc have to be in this block. We don't know
  1721. // how to export them from some other block.
  1722. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1723. // Can export from current BB.
  1724. if (VI->getParent() == FromBB)
  1725. return true;
  1726. // Is already exported, noop.
  1727. return FuncInfo.isExportedInst(V);
  1728. }
  1729. // If this is an argument, we can export it if the BB is the entry block or
  1730. // if it is already exported.
  1731. if (isa<Argument>(V)) {
  1732. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1733. return true;
  1734. // Otherwise, can only export this if it is already exported.
  1735. return FuncInfo.isExportedInst(V);
  1736. }
  1737. // Otherwise, constants can always be exported.
  1738. return true;
  1739. }
  1740. /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
  1741. BranchProbability
  1742. SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
  1743. const MachineBasicBlock *Dst) const {
  1744. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  1745. const BasicBlock *SrcBB = Src->getBasicBlock();
  1746. const BasicBlock *DstBB = Dst->getBasicBlock();
  1747. if (!BPI) {
  1748. // If BPI is not available, set the default probability as 1 / N, where N is
  1749. // the number of successors.
  1750. auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
  1751. return BranchProbability(1, SuccSize);
  1752. }
  1753. return BPI->getEdgeProbability(SrcBB, DstBB);
  1754. }
  1755. void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
  1756. MachineBasicBlock *Dst,
  1757. BranchProbability Prob) {
  1758. if (!FuncInfo.BPI)
  1759. Src->addSuccessorWithoutProb(Dst);
  1760. else {
  1761. if (Prob.isUnknown())
  1762. Prob = getEdgeProbability(Src, Dst);
  1763. Src->addSuccessor(Dst, Prob);
  1764. }
  1765. }
  1766. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1767. if (const Instruction *I = dyn_cast<Instruction>(V))
  1768. return I->getParent() == BB;
  1769. return true;
  1770. }
  1771. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1772. /// This function emits a branch and is used at the leaves of an OR or an
  1773. /// AND operator tree.
  1774. void
  1775. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1776. MachineBasicBlock *TBB,
  1777. MachineBasicBlock *FBB,
  1778. MachineBasicBlock *CurBB,
  1779. MachineBasicBlock *SwitchBB,
  1780. BranchProbability TProb,
  1781. BranchProbability FProb,
  1782. bool InvertCond) {
  1783. const BasicBlock *BB = CurBB->getBasicBlock();
  1784. // If the leaf of the tree is a comparison, merge the condition into
  1785. // the caseblock.
  1786. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1787. // The operands of the cmp have to be in this block. We don't know
  1788. // how to export them from some other block. If this is the first block
  1789. // of the sequence, no exporting is needed.
  1790. if (CurBB == SwitchBB ||
  1791. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1792. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1793. ISD::CondCode Condition;
  1794. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1795. ICmpInst::Predicate Pred =
  1796. InvertCond ? IC->getInversePredicate() : IC->getPredicate();
  1797. Condition = getICmpCondCode(Pred);
  1798. } else {
  1799. const FCmpInst *FC = cast<FCmpInst>(Cond);
  1800. FCmpInst::Predicate Pred =
  1801. InvertCond ? FC->getInversePredicate() : FC->getPredicate();
  1802. Condition = getFCmpCondCode(Pred);
  1803. if (TM.Options.NoNaNsFPMath)
  1804. Condition = getFCmpCodeWithoutNaN(Condition);
  1805. }
  1806. CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
  1807. TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1808. SL->SwitchCases.push_back(CB);
  1809. return;
  1810. }
  1811. }
  1812. // Create a CaseBlock record representing this branch.
  1813. ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
  1814. CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1815. nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
  1816. SL->SwitchCases.push_back(CB);
  1817. }
  1818. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1819. MachineBasicBlock *TBB,
  1820. MachineBasicBlock *FBB,
  1821. MachineBasicBlock *CurBB,
  1822. MachineBasicBlock *SwitchBB,
  1823. Instruction::BinaryOps Opc,
  1824. BranchProbability TProb,
  1825. BranchProbability FProb,
  1826. bool InvertCond) {
  1827. // Skip over not part of the tree and remember to invert op and operands at
  1828. // next level.
  1829. Value *NotCond;
  1830. if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
  1831. InBlock(NotCond, CurBB->getBasicBlock())) {
  1832. FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
  1833. !InvertCond);
  1834. return;
  1835. }
  1836. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1837. // Compute the effective opcode for Cond, taking into account whether it needs
  1838. // to be inverted, e.g.
  1839. // and (not (or A, B)), C
  1840. // gets lowered as
  1841. // and (and (not A, not B), C)
  1842. unsigned BOpc = 0;
  1843. if (BOp) {
  1844. BOpc = BOp->getOpcode();
  1845. if (InvertCond) {
  1846. if (BOpc == Instruction::And)
  1847. BOpc = Instruction::Or;
  1848. else if (BOpc == Instruction::Or)
  1849. BOpc = Instruction::And;
  1850. }
  1851. }
  1852. // If this node is not part of the or/and tree, emit it as a branch.
  1853. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1854. BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
  1855. BOp->getParent() != CurBB->getBasicBlock() ||
  1856. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1857. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1858. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
  1859. TProb, FProb, InvertCond);
  1860. return;
  1861. }
  1862. // Create TmpBB after CurBB.
  1863. MachineFunction::iterator BBI(CurBB);
  1864. MachineFunction &MF = DAG.getMachineFunction();
  1865. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1866. CurBB->getParent()->insert(++BBI, TmpBB);
  1867. if (Opc == Instruction::Or) {
  1868. // Codegen X | Y as:
  1869. // BB1:
  1870. // jmp_if_X TBB
  1871. // jmp TmpBB
  1872. // TmpBB:
  1873. // jmp_if_Y TBB
  1874. // jmp FBB
  1875. //
  1876. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1877. // The requirement is that
  1878. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  1879. // = TrueProb for original BB.
  1880. // Assuming the original probabilities are A and B, one choice is to set
  1881. // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
  1882. // A/(1+B) and 2B/(1+B). This choice assumes that
  1883. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  1884. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  1885. // TmpBB, but the math is more complicated.
  1886. auto NewTrueProb = TProb / 2;
  1887. auto NewFalseProb = TProb / 2 + FProb;
  1888. // Emit the LHS condition.
  1889. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
  1890. NewTrueProb, NewFalseProb, InvertCond);
  1891. // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
  1892. SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
  1893. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1894. // Emit the RHS condition into TmpBB.
  1895. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1896. Probs[0], Probs[1], InvertCond);
  1897. } else {
  1898. assert(Opc == Instruction::And && "Unknown merge op!");
  1899. // Codegen X & Y as:
  1900. // BB1:
  1901. // jmp_if_X TmpBB
  1902. // jmp FBB
  1903. // TmpBB:
  1904. // jmp_if_Y TBB
  1905. // jmp FBB
  1906. //
  1907. // This requires creation of TmpBB after CurBB.
  1908. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  1909. // The requirement is that
  1910. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  1911. // = FalseProb for original BB.
  1912. // Assuming the original probabilities are A and B, one choice is to set
  1913. // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
  1914. // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
  1915. // TrueProb for BB1 * FalseProb for TmpBB.
  1916. auto NewTrueProb = TProb + FProb / 2;
  1917. auto NewFalseProb = FProb / 2;
  1918. // Emit the LHS condition.
  1919. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
  1920. NewTrueProb, NewFalseProb, InvertCond);
  1921. // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
  1922. SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
  1923. BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
  1924. // Emit the RHS condition into TmpBB.
  1925. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
  1926. Probs[0], Probs[1], InvertCond);
  1927. }
  1928. }
  1929. /// If the set of cases should be emitted as a series of branches, return true.
  1930. /// If we should emit this as a bunch of and/or'd together conditions, return
  1931. /// false.
  1932. bool
  1933. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
  1934. if (Cases.size() != 2) return true;
  1935. // If this is two comparisons of the same values or'd or and'd together, they
  1936. // will get folded into a single comparison, so don't emit two blocks.
  1937. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1938. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1939. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1940. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1941. return false;
  1942. }
  1943. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1944. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1945. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1946. Cases[0].CC == Cases[1].CC &&
  1947. isa<Constant>(Cases[0].CmpRHS) &&
  1948. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1949. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1950. return false;
  1951. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1952. return false;
  1953. }
  1954. return true;
  1955. }
  1956. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1957. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1958. // Update machine-CFG edges.
  1959. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1960. if (I.isUnconditional()) {
  1961. // Update machine-CFG edges.
  1962. BrMBB->addSuccessor(Succ0MBB);
  1963. // If this is not a fall-through branch or optimizations are switched off,
  1964. // emit the branch.
  1965. if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
  1966. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  1967. MVT::Other, getControlRoot(),
  1968. DAG.getBasicBlock(Succ0MBB)));
  1969. return;
  1970. }
  1971. // If this condition is one of the special cases we handle, do special stuff
  1972. // now.
  1973. const Value *CondVal = I.getCondition();
  1974. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1975. // If this is a series of conditions that are or'd or and'd together, emit
  1976. // this as a sequence of branches instead of setcc's with and/or operations.
  1977. // As long as jumps are not expensive, this should improve performance.
  1978. // For example, instead of something like:
  1979. // cmp A, B
  1980. // C = seteq
  1981. // cmp D, E
  1982. // F = setle
  1983. // or C, F
  1984. // jnz foo
  1985. // Emit:
  1986. // cmp A, B
  1987. // je foo
  1988. // cmp D, E
  1989. // jle foo
  1990. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1991. Instruction::BinaryOps Opcode = BOp->getOpcode();
  1992. if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
  1993. !I.hasMetadata(LLVMContext::MD_unpredictable) &&
  1994. (Opcode == Instruction::And || Opcode == Instruction::Or)) {
  1995. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1996. Opcode,
  1997. getEdgeProbability(BrMBB, Succ0MBB),
  1998. getEdgeProbability(BrMBB, Succ1MBB),
  1999. /*InvertCond=*/false);
  2000. // If the compares in later blocks need to use values not currently
  2001. // exported from this block, export them now. This block should always
  2002. // be the first entry.
  2003. assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  2004. // Allow some cases to be rejected.
  2005. if (ShouldEmitAsBranches(SL->SwitchCases)) {
  2006. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
  2007. ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
  2008. ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
  2009. }
  2010. // Emit the branch for this block.
  2011. visitSwitchCase(SL->SwitchCases[0], BrMBB);
  2012. SL->SwitchCases.erase(SL->SwitchCases.begin());
  2013. return;
  2014. }
  2015. // Okay, we decided not to do this, remove any inserted MBB's and clear
  2016. // SwitchCases.
  2017. for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
  2018. FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
  2019. SL->SwitchCases.clear();
  2020. }
  2021. }
  2022. // Create a CaseBlock record representing this branch.
  2023. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  2024. nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
  2025. // Use visitSwitchCase to actually insert the fast branch sequence for this
  2026. // cond branch.
  2027. visitSwitchCase(CB, BrMBB);
  2028. }
  2029. /// visitSwitchCase - Emits the necessary code to represent a single node in
  2030. /// the binary search tree resulting from lowering a switch instruction.
  2031. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  2032. MachineBasicBlock *SwitchBB) {
  2033. SDValue Cond;
  2034. SDValue CondLHS = getValue(CB.CmpLHS);
  2035. SDLoc dl = CB.DL;
  2036. if (CB.CC == ISD::SETTRUE) {
  2037. // Branch or fall through to TrueBB.
  2038. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2039. SwitchBB->normalizeSuccProbs();
  2040. if (CB.TrueBB != NextBlock(SwitchBB)) {
  2041. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
  2042. DAG.getBasicBlock(CB.TrueBB)));
  2043. }
  2044. return;
  2045. }
  2046. auto &TLI = DAG.getTargetLoweringInfo();
  2047. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
  2048. // Build the setcc now.
  2049. if (!CB.CmpMHS) {
  2050. // Fold "(X == true)" to X and "(X == false)" to !X to
  2051. // handle common cases produced by branch lowering.
  2052. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  2053. CB.CC == ISD::SETEQ)
  2054. Cond = CondLHS;
  2055. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  2056. CB.CC == ISD::SETEQ) {
  2057. SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
  2058. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  2059. } else {
  2060. SDValue CondRHS = getValue(CB.CmpRHS);
  2061. // If a pointer's DAG type is larger than its memory type then the DAG
  2062. // values are zero-extended. This breaks signed comparisons so truncate
  2063. // back to the underlying type before doing the compare.
  2064. if (CondLHS.getValueType() != MemVT) {
  2065. CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
  2066. CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
  2067. }
  2068. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
  2069. }
  2070. } else {
  2071. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  2072. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  2073. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  2074. SDValue CmpOp = getValue(CB.CmpMHS);
  2075. EVT VT = CmpOp.getValueType();
  2076. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  2077. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
  2078. ISD::SETLE);
  2079. } else {
  2080. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  2081. VT, CmpOp, DAG.getConstant(Low, dl, VT));
  2082. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  2083. DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
  2084. }
  2085. }
  2086. // Update successor info
  2087. addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
  2088. // TrueBB and FalseBB are always different unless the incoming IR is
  2089. // degenerate. This only happens when running llc on weird IR.
  2090. if (CB.TrueBB != CB.FalseBB)
  2091. addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
  2092. SwitchBB->normalizeSuccProbs();
  2093. // If the lhs block is the next block, invert the condition so that we can
  2094. // fall through to the lhs instead of the rhs block.
  2095. if (CB.TrueBB == NextBlock(SwitchBB)) {
  2096. std::swap(CB.TrueBB, CB.FalseBB);
  2097. SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
  2098. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  2099. }
  2100. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2101. MVT::Other, getControlRoot(), Cond,
  2102. DAG.getBasicBlock(CB.TrueBB));
  2103. // Insert the false branch. Do this even if it's a fall through branch,
  2104. // this makes it easier to do DAG optimizations which require inverting
  2105. // the branch condition.
  2106. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2107. DAG.getBasicBlock(CB.FalseBB));
  2108. DAG.setRoot(BrCond);
  2109. }
  2110. /// visitJumpTable - Emit JumpTable node in the current MBB
  2111. void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
  2112. // Emit the code for the jump table
  2113. assert(JT.Reg != -1U && "Should lower JT Header first!");
  2114. EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
  2115. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
  2116. JT.Reg, PTy);
  2117. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  2118. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
  2119. MVT::Other, Index.getValue(1),
  2120. Table, Index);
  2121. DAG.setRoot(BrJumpTable);
  2122. }
  2123. /// visitJumpTableHeader - This function emits necessary code to produce index
  2124. /// in the JumpTable from switch case.
  2125. void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
  2126. JumpTableHeader &JTH,
  2127. MachineBasicBlock *SwitchBB) {
  2128. SDLoc dl = getCurSDLoc();
  2129. // Subtract the lowest switch case value from the value being switched on.
  2130. SDValue SwitchOp = getValue(JTH.SValue);
  2131. EVT VT = SwitchOp.getValueType();
  2132. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2133. DAG.getConstant(JTH.First, dl, VT));
  2134. // The SDNode we just created, which holds the value being switched on minus
  2135. // the smallest case value, needs to be copied to a virtual register so it
  2136. // can be used as an index into the jump table in a subsequent basic block.
  2137. // This value may be smaller or larger than the target's pointer type, and
  2138. // therefore require extension or truncating.
  2139. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2140. SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2141. unsigned JumpTableReg =
  2142. FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
  2143. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
  2144. JumpTableReg, SwitchOp);
  2145. JT.Reg = JumpTableReg;
  2146. if (!JTH.OmitRangeCheck) {
  2147. // Emit the range check for the jump table, and branch to the default block
  2148. // for the switch statement if the value being switched on exceeds the
  2149. // largest case in the switch.
  2150. SDValue CMP = DAG.getSetCC(
  2151. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2152. Sub.getValueType()),
  2153. Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
  2154. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2155. MVT::Other, CopyTo, CMP,
  2156. DAG.getBasicBlock(JT.Default));
  2157. // Avoid emitting unnecessary branches to the next block.
  2158. if (JT.MBB != NextBlock(SwitchBB))
  2159. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  2160. DAG.getBasicBlock(JT.MBB));
  2161. DAG.setRoot(BrCond);
  2162. } else {
  2163. // Avoid emitting unnecessary branches to the next block.
  2164. if (JT.MBB != NextBlock(SwitchBB))
  2165. DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
  2166. DAG.getBasicBlock(JT.MBB)));
  2167. else
  2168. DAG.setRoot(CopyTo);
  2169. }
  2170. }
  2171. /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
  2172. /// variable if there exists one.
  2173. static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
  2174. SDValue &Chain) {
  2175. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2176. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2177. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2178. MachineFunction &MF = DAG.getMachineFunction();
  2179. Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
  2180. MachineSDNode *Node =
  2181. DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
  2182. if (Global) {
  2183. MachinePointerInfo MPInfo(Global);
  2184. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
  2185. MachineMemOperand::MODereferenceable;
  2186. MachineMemOperand *MemRef = MF.getMachineMemOperand(
  2187. MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
  2188. DAG.setNodeMemRefs(Node, {MemRef});
  2189. }
  2190. if (PtrTy != PtrMemTy)
  2191. return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
  2192. return SDValue(Node, 0);
  2193. }
  2194. /// Codegen a new tail for a stack protector check ParentMBB which has had its
  2195. /// tail spliced into a stack protector check success bb.
  2196. ///
  2197. /// For a high level explanation of how this fits into the stack protector
  2198. /// generation see the comment on the declaration of class
  2199. /// StackProtectorDescriptor.
  2200. void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
  2201. MachineBasicBlock *ParentBB) {
  2202. // First create the loads to the guard/stack slot for the comparison.
  2203. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2204. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  2205. EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
  2206. MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
  2207. int FI = MFI.getStackProtectorIndex();
  2208. SDValue Guard;
  2209. SDLoc dl = getCurSDLoc();
  2210. SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
  2211. const Module &M = *ParentBB->getParent()->getFunction().getParent();
  2212. unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
  2213. // Generate code to load the content of the guard slot.
  2214. SDValue GuardVal = DAG.getLoad(
  2215. PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
  2216. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
  2217. MachineMemOperand::MOVolatile);
  2218. if (TLI.useStackGuardXorFP())
  2219. GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
  2220. // Retrieve guard check function, nullptr if instrumentation is inlined.
  2221. if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
  2222. // The target provides a guard check function to validate the guard value.
  2223. // Generate a call to that function with the content of the guard slot as
  2224. // argument.
  2225. FunctionType *FnTy = GuardCheckFn->getFunctionType();
  2226. assert(FnTy->getNumParams() == 1 && "Invalid function signature");
  2227. TargetLowering::ArgListTy Args;
  2228. TargetLowering::ArgListEntry Entry;
  2229. Entry.Node = GuardVal;
  2230. Entry.Ty = FnTy->getParamType(0);
  2231. if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
  2232. Entry.IsInReg = true;
  2233. Args.push_back(Entry);
  2234. TargetLowering::CallLoweringInfo CLI(DAG);
  2235. CLI.setDebugLoc(getCurSDLoc())
  2236. .setChain(DAG.getEntryNode())
  2237. .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
  2238. getValue(GuardCheckFn), std::move(Args));
  2239. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  2240. DAG.setRoot(Result.second);
  2241. return;
  2242. }
  2243. // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
  2244. // Otherwise, emit a volatile load to retrieve the stack guard value.
  2245. SDValue Chain = DAG.getEntryNode();
  2246. if (TLI.useLoadStackGuardNode()) {
  2247. Guard = getLoadStackGuard(DAG, dl, Chain);
  2248. } else {
  2249. const Value *IRGuard = TLI.getSDagStackGuard(M);
  2250. SDValue GuardPtr = getValue(IRGuard);
  2251. Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
  2252. MachinePointerInfo(IRGuard, 0), Align,
  2253. MachineMemOperand::MOVolatile);
  2254. }
  2255. // Perform the comparison via a subtract/getsetcc.
  2256. EVT VT = Guard.getValueType();
  2257. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
  2258. SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
  2259. *DAG.getContext(),
  2260. Sub.getValueType()),
  2261. Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2262. // If the sub is not 0, then we know the guard/stackslot do not equal, so
  2263. // branch to failure MBB.
  2264. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  2265. MVT::Other, GuardVal.getOperand(0),
  2266. Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
  2267. // Otherwise branch to success MBB.
  2268. SDValue Br = DAG.getNode(ISD::BR, dl,
  2269. MVT::Other, BrCond,
  2270. DAG.getBasicBlock(SPD.getSuccessMBB()));
  2271. DAG.setRoot(Br);
  2272. }
  2273. /// Codegen the failure basic block for a stack protector check.
  2274. ///
  2275. /// A failure stack protector machine basic block consists simply of a call to
  2276. /// __stack_chk_fail().
  2277. ///
  2278. /// For a high level explanation of how this fits into the stack protector
  2279. /// generation see the comment on the declaration of class
  2280. /// StackProtectorDescriptor.
  2281. void
  2282. SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
  2283. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2284. TargetLowering::MakeLibCallOptions CallOptions;
  2285. CallOptions.setDiscardResult(true);
  2286. SDValue Chain =
  2287. TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
  2288. None, CallOptions, getCurSDLoc()).second;
  2289. // On PS4, the "return address" must still be within the calling function,
  2290. // even if it's at the very end, so emit an explicit TRAP here.
  2291. // Passing 'true' for doesNotReturn above won't generate the trap for us.
  2292. if (TM.getTargetTriple().isPS4CPU())
  2293. Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
  2294. DAG.setRoot(Chain);
  2295. }
  2296. /// visitBitTestHeader - This function emits necessary code to produce value
  2297. /// suitable for "bit tests"
  2298. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  2299. MachineBasicBlock *SwitchBB) {
  2300. SDLoc dl = getCurSDLoc();
  2301. // Subtract the minimum value
  2302. SDValue SwitchOp = getValue(B.SValue);
  2303. EVT VT = SwitchOp.getValueType();
  2304. SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
  2305. DAG.getConstant(B.First, dl, VT));
  2306. // Check range
  2307. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2308. SDValue RangeCmp = DAG.getSetCC(
  2309. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
  2310. Sub.getValueType()),
  2311. Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
  2312. // Determine the type of the test operands.
  2313. bool UsePtrType = false;
  2314. if (!TLI.isTypeLegal(VT))
  2315. UsePtrType = true;
  2316. else {
  2317. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  2318. if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
  2319. // Switch table case range are encoded into series of masks.
  2320. // Just use pointer type, it's guaranteed to fit.
  2321. UsePtrType = true;
  2322. break;
  2323. }
  2324. }
  2325. if (UsePtrType) {
  2326. VT = TLI.getPointerTy(DAG.getDataLayout());
  2327. Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
  2328. }
  2329. B.RegVT = VT.getSimpleVT();
  2330. B.Reg = FuncInfo.CreateReg(B.RegVT);
  2331. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
  2332. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  2333. addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
  2334. addSuccessorWithProb(SwitchBB, MBB, B.Prob);
  2335. SwitchBB->normalizeSuccProbs();
  2336. SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
  2337. MVT::Other, CopyTo, RangeCmp,
  2338. DAG.getBasicBlock(B.Default));
  2339. // Avoid emitting unnecessary branches to the next block.
  2340. if (MBB != NextBlock(SwitchBB))
  2341. BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
  2342. DAG.getBasicBlock(MBB));
  2343. DAG.setRoot(BrRange);
  2344. }
  2345. /// visitBitTestCase - this function produces one "bit test"
  2346. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  2347. MachineBasicBlock* NextMBB,
  2348. BranchProbability BranchProbToNext,
  2349. unsigned Reg,
  2350. BitTestCase &B,
  2351. MachineBasicBlock *SwitchBB) {
  2352. SDLoc dl = getCurSDLoc();
  2353. MVT VT = BB.RegVT;
  2354. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
  2355. SDValue Cmp;
  2356. unsigned PopCount = countPopulation(B.Mask);
  2357. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2358. if (PopCount == 1) {
  2359. // Testing for a single bit; just compare the shift count with what it
  2360. // would need to be to shift a 1 bit in that position.
  2361. Cmp = DAG.getSetCC(
  2362. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2363. ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
  2364. ISD::SETEQ);
  2365. } else if (PopCount == BB.Range) {
  2366. // There is only one zero bit in the range, test for it directly.
  2367. Cmp = DAG.getSetCC(
  2368. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2369. ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
  2370. ISD::SETNE);
  2371. } else {
  2372. // Make desired shift
  2373. SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
  2374. DAG.getConstant(1, dl, VT), ShiftOp);
  2375. // Emit bit tests and jumps
  2376. SDValue AndOp = DAG.getNode(ISD::AND, dl,
  2377. VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
  2378. Cmp = DAG.getSetCC(
  2379. dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
  2380. AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
  2381. }
  2382. // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
  2383. addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
  2384. // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
  2385. addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
  2386. // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
  2387. // one as they are relative probabilities (and thus work more like weights),
  2388. // and hence we need to normalize them to let the sum of them become one.
  2389. SwitchBB->normalizeSuccProbs();
  2390. SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
  2391. MVT::Other, getControlRoot(),
  2392. Cmp, DAG.getBasicBlock(B.TargetBB));
  2393. // Avoid emitting unnecessary branches to the next block.
  2394. if (NextMBB != NextBlock(SwitchBB))
  2395. BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
  2396. DAG.getBasicBlock(NextMBB));
  2397. DAG.setRoot(BrAnd);
  2398. }
  2399. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  2400. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  2401. // Retrieve successors. Look through artificial IR level blocks like
  2402. // catchswitch for successors.
  2403. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  2404. const BasicBlock *EHPadBB = I.getSuccessor(1);
  2405. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2406. // have to do anything here to lower funclet bundles.
  2407. assert(!I.hasOperandBundlesOtherThan(
  2408. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2409. "Cannot lower invokes with arbitrary operand bundles yet!");
  2410. const Value *Callee(I.getCalledValue());
  2411. const Function *Fn = dyn_cast<Function>(Callee);
  2412. if (isa<InlineAsm>(Callee))
  2413. visitInlineAsm(&I);
  2414. else if (Fn && Fn->isIntrinsic()) {
  2415. switch (Fn->getIntrinsicID()) {
  2416. default:
  2417. llvm_unreachable("Cannot invoke this intrinsic");
  2418. case Intrinsic::donothing:
  2419. // Ignore invokes to @llvm.donothing: jump directly to the next BB.
  2420. break;
  2421. case Intrinsic::experimental_patchpoint_void:
  2422. case Intrinsic::experimental_patchpoint_i64:
  2423. visitPatchpoint(&I, EHPadBB);
  2424. break;
  2425. case Intrinsic::experimental_gc_statepoint:
  2426. LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
  2427. break;
  2428. case Intrinsic::wasm_rethrow_in_catch: {
  2429. // This is usually done in visitTargetIntrinsic, but this intrinsic is
  2430. // special because it can be invoked, so we manually lower it to a DAG
  2431. // node here.
  2432. SmallVector<SDValue, 8> Ops;
  2433. Ops.push_back(getRoot()); // inchain
  2434. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2435. Ops.push_back(
  2436. DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
  2437. TLI.getPointerTy(DAG.getDataLayout())));
  2438. SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
  2439. DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
  2440. break;
  2441. }
  2442. }
  2443. } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
  2444. // Currently we do not lower any intrinsic calls with deopt operand bundles.
  2445. // Eventually we will support lowering the @llvm.experimental.deoptimize
  2446. // intrinsic, and right now there are no plans to support other intrinsics
  2447. // with deopt state.
  2448. LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
  2449. } else {
  2450. LowerCallTo(&I, getValue(Callee), false, EHPadBB);
  2451. }
  2452. // If the value of the invoke is used outside of its defining block, make it
  2453. // available as a virtual register.
  2454. // We already took care of the exported value for the statepoint instruction
  2455. // during call to the LowerStatepoint.
  2456. if (!isStatepoint(I)) {
  2457. CopyToExportRegsIfNeeded(&I);
  2458. }
  2459. SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
  2460. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  2461. BranchProbability EHPadBBProb =
  2462. BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
  2463. : BranchProbability::getZero();
  2464. findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
  2465. // Update successor info.
  2466. addSuccessorWithProb(InvokeMBB, Return);
  2467. for (auto &UnwindDest : UnwindDests) {
  2468. UnwindDest.first->setIsEHPad();
  2469. addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
  2470. }
  2471. InvokeMBB->normalizeSuccProbs();
  2472. // Drop into normal successor.
  2473. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
  2474. DAG.getBasicBlock(Return)));
  2475. }
  2476. void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
  2477. MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
  2478. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  2479. // have to do anything here to lower funclet bundles.
  2480. assert(!I.hasOperandBundlesOtherThan(
  2481. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  2482. "Cannot lower callbrs with arbitrary operand bundles yet!");
  2483. assert(isa<InlineAsm>(I.getCalledValue()) &&
  2484. "Only know how to handle inlineasm callbr");
  2485. visitInlineAsm(&I);
  2486. // Retrieve successors.
  2487. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
  2488. // Update successor info.
  2489. addSuccessorWithProb(CallBrMBB, Return);
  2490. for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
  2491. MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
  2492. addSuccessorWithProb(CallBrMBB, Target);
  2493. }
  2494. CallBrMBB->normalizeSuccProbs();
  2495. // Drop into default successor.
  2496. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
  2497. MVT::Other, getControlRoot(),
  2498. DAG.getBasicBlock(Return)));
  2499. }
  2500. void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
  2501. llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
  2502. }
  2503. void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
  2504. assert(FuncInfo.MBB->isEHPad() &&
  2505. "Call to landingpad not in landing pad!");
  2506. // If there aren't registers to copy the values into (e.g., during SjLj
  2507. // exceptions), then don't bother to create these DAG nodes.
  2508. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2509. const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
  2510. if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
  2511. TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
  2512. return;
  2513. // If landingpad's return type is token type, we don't create DAG nodes
  2514. // for its exception pointer and selector value. The extraction of exception
  2515. // pointer or selector value from token type landingpads is not currently
  2516. // supported.
  2517. if (LP.getType()->isTokenTy())
  2518. return;
  2519. SmallVector<EVT, 2> ValueVTs;
  2520. SDLoc dl = getCurSDLoc();
  2521. ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
  2522. assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
  2523. // Get the two live-in registers as SDValues. The physregs have already been
  2524. // copied into virtual registers.
  2525. SDValue Ops[2];
  2526. if (FuncInfo.ExceptionPointerVirtReg) {
  2527. Ops[0] = DAG.getZExtOrTrunc(
  2528. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2529. FuncInfo.ExceptionPointerVirtReg,
  2530. TLI.getPointerTy(DAG.getDataLayout())),
  2531. dl, ValueVTs[0]);
  2532. } else {
  2533. Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
  2534. }
  2535. Ops[1] = DAG.getZExtOrTrunc(
  2536. DAG.getCopyFromReg(DAG.getEntryNode(), dl,
  2537. FuncInfo.ExceptionSelectorVirtReg,
  2538. TLI.getPointerTy(DAG.getDataLayout())),
  2539. dl, ValueVTs[1]);
  2540. // Merge into one.
  2541. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  2542. DAG.getVTList(ValueVTs), Ops);
  2543. setValue(&LP, Res);
  2544. }
  2545. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  2546. MachineBasicBlock *Last) {
  2547. // Update JTCases.
  2548. for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
  2549. if (SL->JTCases[i].first.HeaderBB == First)
  2550. SL->JTCases[i].first.HeaderBB = Last;
  2551. // Update BitTestCases.
  2552. for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
  2553. if (SL->BitTestCases[i].Parent == First)
  2554. SL->BitTestCases[i].Parent = Last;
  2555. }
  2556. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2557. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2558. // Update machine-CFG edges with unique successors.
  2559. SmallSet<BasicBlock*, 32> Done;
  2560. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
  2561. BasicBlock *BB = I.getSuccessor(i);
  2562. bool Inserted = Done.insert(BB).second;
  2563. if (!Inserted)
  2564. continue;
  2565. MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
  2566. addSuccessorWithProb(IndirectBrMBB, Succ);
  2567. }
  2568. IndirectBrMBB->normalizeSuccProbs();
  2569. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
  2570. MVT::Other, getControlRoot(),
  2571. getValue(I.getAddress())));
  2572. }
  2573. void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
  2574. if (!DAG.getTarget().Options.TrapUnreachable)
  2575. return;
  2576. // We may be able to ignore unreachable behind a noreturn call.
  2577. if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
  2578. const BasicBlock &BB = *I.getParent();
  2579. if (&I != &BB.front()) {
  2580. BasicBlock::const_iterator PredI =
  2581. std::prev(BasicBlock::const_iterator(&I));
  2582. if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
  2583. if (Call->doesNotReturn())
  2584. return;
  2585. }
  2586. }
  2587. }
  2588. DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
  2589. }
  2590. void SelectionDAGBuilder::visitFSub(const User &I) {
  2591. // -0.0 - X --> fneg
  2592. Type *Ty = I.getType();
  2593. if (isa<Constant>(I.getOperand(0)) &&
  2594. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2595. SDValue Op2 = getValue(I.getOperand(1));
  2596. setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
  2597. Op2.getValueType(), Op2));
  2598. return;
  2599. }
  2600. visitBinary(I, ISD::FSUB);
  2601. }
  2602. /// Checks if the given instruction performs a vector reduction, in which case
  2603. /// we have the freedom to alter the elements in the result as long as the
  2604. /// reduction of them stays unchanged.
  2605. static bool isVectorReductionOp(const User *I) {
  2606. const Instruction *Inst = dyn_cast<Instruction>(I);
  2607. if (!Inst || !Inst->getType()->isVectorTy())
  2608. return false;
  2609. auto OpCode = Inst->getOpcode();
  2610. switch (OpCode) {
  2611. case Instruction::Add:
  2612. case Instruction::Mul:
  2613. case Instruction::And:
  2614. case Instruction::Or:
  2615. case Instruction::Xor:
  2616. break;
  2617. case Instruction::FAdd:
  2618. case Instruction::FMul:
  2619. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2620. if (FPOp->getFastMathFlags().isFast())
  2621. break;
  2622. LLVM_FALLTHROUGH;
  2623. default:
  2624. return false;
  2625. }
  2626. unsigned ElemNum = Inst->getType()->getVectorNumElements();
  2627. // Ensure the reduction size is a power of 2.
  2628. if (!isPowerOf2_32(ElemNum))
  2629. return false;
  2630. unsigned ElemNumToReduce = ElemNum;
  2631. // Do DFS search on the def-use chain from the given instruction. We only
  2632. // allow four kinds of operations during the search until we reach the
  2633. // instruction that extracts the first element from the vector:
  2634. //
  2635. // 1. The reduction operation of the same opcode as the given instruction.
  2636. //
  2637. // 2. PHI node.
  2638. //
  2639. // 3. ShuffleVector instruction together with a reduction operation that
  2640. // does a partial reduction.
  2641. //
  2642. // 4. ExtractElement that extracts the first element from the vector, and we
  2643. // stop searching the def-use chain here.
  2644. //
  2645. // 3 & 4 above perform a reduction on all elements of the vector. We push defs
  2646. // from 1-3 to the stack to continue the DFS. The given instruction is not
  2647. // a reduction operation if we meet any other instructions other than those
  2648. // listed above.
  2649. SmallVector<const User *, 16> UsersToVisit{Inst};
  2650. SmallPtrSet<const User *, 16> Visited;
  2651. bool ReduxExtracted = false;
  2652. while (!UsersToVisit.empty()) {
  2653. auto User = UsersToVisit.back();
  2654. UsersToVisit.pop_back();
  2655. if (!Visited.insert(User).second)
  2656. continue;
  2657. for (const auto &U : User->users()) {
  2658. auto Inst = dyn_cast<Instruction>(U);
  2659. if (!Inst)
  2660. return false;
  2661. if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
  2662. if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
  2663. if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
  2664. return false;
  2665. UsersToVisit.push_back(U);
  2666. } else if (const ShuffleVectorInst *ShufInst =
  2667. dyn_cast<ShuffleVectorInst>(U)) {
  2668. // Detect the following pattern: A ShuffleVector instruction together
  2669. // with a reduction that do partial reduction on the first and second
  2670. // ElemNumToReduce / 2 elements, and store the result in
  2671. // ElemNumToReduce / 2 elements in another vector.
  2672. unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
  2673. if (ResultElements < ElemNum)
  2674. return false;
  2675. if (ElemNumToReduce == 1)
  2676. return false;
  2677. if (!isa<UndefValue>(U->getOperand(1)))
  2678. return false;
  2679. for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
  2680. if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
  2681. return false;
  2682. for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
  2683. if (ShufInst->getMaskValue(i) != -1)
  2684. return false;
  2685. // There is only one user of this ShuffleVector instruction, which
  2686. // must be a reduction operation.
  2687. if (!U->hasOneUse())
  2688. return false;
  2689. auto U2 = dyn_cast<Instruction>(*U->user_begin());
  2690. if (!U2 || U2->getOpcode() != OpCode)
  2691. return false;
  2692. // Check operands of the reduction operation.
  2693. if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
  2694. (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
  2695. UsersToVisit.push_back(U2);
  2696. ElemNumToReduce /= 2;
  2697. } else
  2698. return false;
  2699. } else if (isa<ExtractElementInst>(U)) {
  2700. // At this moment we should have reduced all elements in the vector.
  2701. if (ElemNumToReduce != 1)
  2702. return false;
  2703. const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
  2704. if (!Val || !Val->isZero())
  2705. return false;
  2706. ReduxExtracted = true;
  2707. } else
  2708. return false;
  2709. }
  2710. }
  2711. return ReduxExtracted;
  2712. }
  2713. void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
  2714. SDNodeFlags Flags;
  2715. SDValue Op = getValue(I.getOperand(0));
  2716. SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
  2717. Op, Flags);
  2718. setValue(&I, UnNodeValue);
  2719. }
  2720. void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
  2721. SDNodeFlags Flags;
  2722. if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
  2723. Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
  2724. Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
  2725. }
  2726. if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
  2727. Flags.setExact(ExactOp->isExact());
  2728. }
  2729. if (isVectorReductionOp(&I)) {
  2730. Flags.setVectorReduction(true);
  2731. LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
  2732. }
  2733. SDValue Op1 = getValue(I.getOperand(0));
  2734. SDValue Op2 = getValue(I.getOperand(1));
  2735. SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
  2736. Op1, Op2, Flags);
  2737. setValue(&I, BinNodeValue);
  2738. }
  2739. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2740. SDValue Op1 = getValue(I.getOperand(0));
  2741. SDValue Op2 = getValue(I.getOperand(1));
  2742. EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
  2743. Op1.getValueType(), DAG.getDataLayout());
  2744. // Coerce the shift amount to the right type if we can.
  2745. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2746. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2747. unsigned Op2Size = Op2.getValueSizeInBits();
  2748. SDLoc DL = getCurSDLoc();
  2749. // If the operand is smaller than the shift count type, promote it.
  2750. if (ShiftSize > Op2Size)
  2751. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2752. // If the operand is larger than the shift count type but the shift
  2753. // count type has enough bits to represent any shift value, truncate
  2754. // it now. This is a common case and it exposes the truncate to
  2755. // optimization early.
  2756. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
  2757. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2758. // Otherwise we'll need to temporarily settle for some other convenient
  2759. // type. Type legalization will make adjustments once the shiftee is split.
  2760. else
  2761. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2762. }
  2763. bool nuw = false;
  2764. bool nsw = false;
  2765. bool exact = false;
  2766. if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
  2767. if (const OverflowingBinaryOperator *OFBinOp =
  2768. dyn_cast<const OverflowingBinaryOperator>(&I)) {
  2769. nuw = OFBinOp->hasNoUnsignedWrap();
  2770. nsw = OFBinOp->hasNoSignedWrap();
  2771. }
  2772. if (const PossiblyExactOperator *ExactOp =
  2773. dyn_cast<const PossiblyExactOperator>(&I))
  2774. exact = ExactOp->isExact();
  2775. }
  2776. SDNodeFlags Flags;
  2777. Flags.setExact(exact);
  2778. Flags.setNoSignedWrap(nsw);
  2779. Flags.setNoUnsignedWrap(nuw);
  2780. SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
  2781. Flags);
  2782. setValue(&I, Res);
  2783. }
  2784. void SelectionDAGBuilder::visitSDiv(const User &I) {
  2785. SDValue Op1 = getValue(I.getOperand(0));
  2786. SDValue Op2 = getValue(I.getOperand(1));
  2787. SDNodeFlags Flags;
  2788. Flags.setExact(isa<PossiblyExactOperator>(&I) &&
  2789. cast<PossiblyExactOperator>(&I)->isExact());
  2790. setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
  2791. Op2, Flags));
  2792. }
  2793. void SelectionDAGBuilder::visitICmp(const User &I) {
  2794. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2795. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2796. predicate = IC->getPredicate();
  2797. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2798. predicate = ICmpInst::Predicate(IC->getPredicate());
  2799. SDValue Op1 = getValue(I.getOperand(0));
  2800. SDValue Op2 = getValue(I.getOperand(1));
  2801. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2802. auto &TLI = DAG.getTargetLoweringInfo();
  2803. EVT MemVT =
  2804. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  2805. // If a pointer's DAG type is larger than its memory type then the DAG values
  2806. // are zero-extended. This breaks signed comparisons so truncate back to the
  2807. // underlying type before doing the compare.
  2808. if (Op1.getValueType() != MemVT) {
  2809. Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
  2810. Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
  2811. }
  2812. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2813. I.getType());
  2814. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
  2815. }
  2816. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2817. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2818. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2819. predicate = FC->getPredicate();
  2820. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2821. predicate = FCmpInst::Predicate(FC->getPredicate());
  2822. SDValue Op1 = getValue(I.getOperand(0));
  2823. SDValue Op2 = getValue(I.getOperand(1));
  2824. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2825. auto *FPMO = dyn_cast<FPMathOperator>(&I);
  2826. if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
  2827. Condition = getFCmpCodeWithoutNaN(Condition);
  2828. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2829. I.getType());
  2830. setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
  2831. }
  2832. // Check if the condition of the select has one use or two users that are both
  2833. // selects with the same condition.
  2834. static bool hasOnlySelectUsers(const Value *Cond) {
  2835. return llvm::all_of(Cond->users(), [](const Value *V) {
  2836. return isa<SelectInst>(V);
  2837. });
  2838. }
  2839. void SelectionDAGBuilder::visitSelect(const User &I) {
  2840. SmallVector<EVT, 4> ValueVTs;
  2841. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
  2842. ValueVTs);
  2843. unsigned NumValues = ValueVTs.size();
  2844. if (NumValues == 0) return;
  2845. SmallVector<SDValue, 4> Values(NumValues);
  2846. SDValue Cond = getValue(I.getOperand(0));
  2847. SDValue LHSVal = getValue(I.getOperand(1));
  2848. SDValue RHSVal = getValue(I.getOperand(2));
  2849. auto BaseOps = {Cond};
  2850. ISD::NodeType OpCode = Cond.getValueType().isVector() ?
  2851. ISD::VSELECT : ISD::SELECT;
  2852. bool IsUnaryAbs = false;
  2853. // Min/max matching is only viable if all output VTs are the same.
  2854. if (is_splat(ValueVTs)) {
  2855. EVT VT = ValueVTs[0];
  2856. LLVMContext &Ctx = *DAG.getContext();
  2857. auto &TLI = DAG.getTargetLoweringInfo();
  2858. // We care about the legality of the operation after it has been type
  2859. // legalized.
  2860. while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
  2861. VT != TLI.getTypeToTransformTo(Ctx, VT))
  2862. VT = TLI.getTypeToTransformTo(Ctx, VT);
  2863. // If the vselect is legal, assume we want to leave this as a vector setcc +
  2864. // vselect. Otherwise, if this is going to be scalarized, we want to see if
  2865. // min/max is legal on the scalar type.
  2866. bool UseScalarMinMax = VT.isVector() &&
  2867. !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
  2868. Value *LHS, *RHS;
  2869. auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
  2870. ISD::NodeType Opc = ISD::DELETED_NODE;
  2871. switch (SPR.Flavor) {
  2872. case SPF_UMAX: Opc = ISD::UMAX; break;
  2873. case SPF_UMIN: Opc = ISD::UMIN; break;
  2874. case SPF_SMAX: Opc = ISD::SMAX; break;
  2875. case SPF_SMIN: Opc = ISD::SMIN; break;
  2876. case SPF_FMINNUM:
  2877. switch (SPR.NaNBehavior) {
  2878. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2879. case SPNB_RETURNS_NAN: Opc = ISD::FMINIMUM; break;
  2880. case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
  2881. case SPNB_RETURNS_ANY: {
  2882. if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
  2883. Opc = ISD::FMINNUM;
  2884. else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
  2885. Opc = ISD::FMINIMUM;
  2886. else if (UseScalarMinMax)
  2887. Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
  2888. ISD::FMINNUM : ISD::FMINIMUM;
  2889. break;
  2890. }
  2891. }
  2892. break;
  2893. case SPF_FMAXNUM:
  2894. switch (SPR.NaNBehavior) {
  2895. case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
  2896. case SPNB_RETURNS_NAN: Opc = ISD::FMAXIMUM; break;
  2897. case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
  2898. case SPNB_RETURNS_ANY:
  2899. if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
  2900. Opc = ISD::FMAXNUM;
  2901. else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
  2902. Opc = ISD::FMAXIMUM;
  2903. else if (UseScalarMinMax)
  2904. Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
  2905. ISD::FMAXNUM : ISD::FMAXIMUM;
  2906. break;
  2907. }
  2908. break;
  2909. case SPF_ABS:
  2910. IsUnaryAbs = true;
  2911. Opc = ISD::ABS;
  2912. break;
  2913. case SPF_NABS:
  2914. // TODO: we need to produce sub(0, abs(X)).
  2915. default: break;
  2916. }
  2917. if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
  2918. (TLI.isOperationLegalOrCustom(Opc, VT) ||
  2919. (UseScalarMinMax &&
  2920. TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
  2921. // If the underlying comparison instruction is used by any other
  2922. // instruction, the consumed instructions won't be destroyed, so it is
  2923. // not profitable to convert to a min/max.
  2924. hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
  2925. OpCode = Opc;
  2926. LHSVal = getValue(LHS);
  2927. RHSVal = getValue(RHS);
  2928. BaseOps = {};
  2929. }
  2930. if (IsUnaryAbs) {
  2931. OpCode = Opc;
  2932. LHSVal = getValue(LHS);
  2933. BaseOps = {};
  2934. }
  2935. }
  2936. if (IsUnaryAbs) {
  2937. for (unsigned i = 0; i != NumValues; ++i) {
  2938. Values[i] =
  2939. DAG.getNode(OpCode, getCurSDLoc(),
  2940. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
  2941. SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2942. }
  2943. } else {
  2944. for (unsigned i = 0; i != NumValues; ++i) {
  2945. SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
  2946. Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
  2947. Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
  2948. Values[i] = DAG.getNode(
  2949. OpCode, getCurSDLoc(),
  2950. LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
  2951. }
  2952. }
  2953. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  2954. DAG.getVTList(ValueVTs), Values));
  2955. }
  2956. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2957. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2958. SDValue N = getValue(I.getOperand(0));
  2959. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2960. I.getType());
  2961. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
  2962. }
  2963. void SelectionDAGBuilder::visitZExt(const User &I) {
  2964. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2965. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2966. SDValue N = getValue(I.getOperand(0));
  2967. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2968. I.getType());
  2969. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
  2970. }
  2971. void SelectionDAGBuilder::visitSExt(const User &I) {
  2972. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2973. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2974. SDValue N = getValue(I.getOperand(0));
  2975. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2976. I.getType());
  2977. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
  2978. }
  2979. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2980. // FPTrunc is never a no-op cast, no need to check
  2981. SDValue N = getValue(I.getOperand(0));
  2982. SDLoc dl = getCurSDLoc();
  2983. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2984. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  2985. setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
  2986. DAG.getTargetConstant(
  2987. 0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
  2988. }
  2989. void SelectionDAGBuilder::visitFPExt(const User &I) {
  2990. // FPExt is never a no-op cast, no need to check
  2991. SDValue N = getValue(I.getOperand(0));
  2992. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  2993. I.getType());
  2994. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
  2995. }
  2996. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2997. // FPToUI is never a no-op cast, no need to check
  2998. SDValue N = getValue(I.getOperand(0));
  2999. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3000. I.getType());
  3001. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
  3002. }
  3003. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  3004. // FPToSI is never a no-op cast, no need to check
  3005. SDValue N = getValue(I.getOperand(0));
  3006. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3007. I.getType());
  3008. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
  3009. }
  3010. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  3011. // UIToFP is never a no-op cast, no need to check
  3012. SDValue N = getValue(I.getOperand(0));
  3013. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3014. I.getType());
  3015. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
  3016. }
  3017. void SelectionDAGBuilder::visitSIToFP(const User &I) {
  3018. // SIToFP is never a no-op cast, no need to check
  3019. SDValue N = getValue(I.getOperand(0));
  3020. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3021. I.getType());
  3022. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
  3023. }
  3024. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  3025. // What to do depends on the size of the integer and the size of the pointer.
  3026. // We can either truncate, zero extend, or no-op, accordingly.
  3027. SDValue N = getValue(I.getOperand(0));
  3028. auto &TLI = DAG.getTargetLoweringInfo();
  3029. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3030. I.getType());
  3031. EVT PtrMemVT =
  3032. TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
  3033. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3034. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
  3035. setValue(&I, N);
  3036. }
  3037. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  3038. // What to do depends on the size of the integer and the size of the pointer.
  3039. // We can either truncate, zero extend, or no-op, accordingly.
  3040. SDValue N = getValue(I.getOperand(0));
  3041. auto &TLI = DAG.getTargetLoweringInfo();
  3042. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3043. EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  3044. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
  3045. N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
  3046. setValue(&I, N);
  3047. }
  3048. void SelectionDAGBuilder::visitBitCast(const User &I) {
  3049. SDValue N = getValue(I.getOperand(0));
  3050. SDLoc dl = getCurSDLoc();
  3051. EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  3052. I.getType());
  3053. // BitCast assures us that source and destination are the same size so this is
  3054. // either a BITCAST or a no-op.
  3055. if (DestVT != N.getValueType())
  3056. setValue(&I, DAG.getNode(ISD::BITCAST, dl,
  3057. DestVT, N)); // convert types.
  3058. // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
  3059. // might fold any kind of constant expression to an integer constant and that
  3060. // is not what we are looking for. Only recognize a bitcast of a genuine
  3061. // constant integer as an opaque constant.
  3062. else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
  3063. setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
  3064. /*isOpaque*/true));
  3065. else
  3066. setValue(&I, N); // noop cast.
  3067. }
  3068. void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
  3069. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3070. const Value *SV = I.getOperand(0);
  3071. SDValue N = getValue(SV);
  3072. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3073. unsigned SrcAS = SV->getType()->getPointerAddressSpace();
  3074. unsigned DestAS = I.getType()->getPointerAddressSpace();
  3075. if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3076. N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
  3077. setValue(&I, N);
  3078. }
  3079. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  3080. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3081. SDValue InVec = getValue(I.getOperand(0));
  3082. SDValue InVal = getValue(I.getOperand(1));
  3083. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
  3084. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3085. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
  3086. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3087. InVec, InVal, InIdx));
  3088. }
  3089. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  3090. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3091. SDValue InVec = getValue(I.getOperand(0));
  3092. SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
  3093. TLI.getVectorIdxTy(DAG.getDataLayout()));
  3094. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
  3095. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  3096. InVec, InIdx));
  3097. }
  3098. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  3099. SDValue Src1 = getValue(I.getOperand(0));
  3100. SDValue Src2 = getValue(I.getOperand(1));
  3101. SDLoc DL = getCurSDLoc();
  3102. SmallVector<int, 8> Mask;
  3103. ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
  3104. unsigned MaskNumElts = Mask.size();
  3105. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3106. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3107. EVT SrcVT = Src1.getValueType();
  3108. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  3109. if (SrcNumElts == MaskNumElts) {
  3110. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
  3111. return;
  3112. }
  3113. // Normalize the shuffle vector since mask and vector length don't match.
  3114. if (SrcNumElts < MaskNumElts) {
  3115. // Mask is longer than the source vectors. We can use concatenate vector to
  3116. // make the mask and vectors lengths match.
  3117. if (MaskNumElts % SrcNumElts == 0) {
  3118. // Mask length is a multiple of the source vector length.
  3119. // Check if the shuffle is some kind of concatenation of the input
  3120. // vectors.
  3121. unsigned NumConcat = MaskNumElts / SrcNumElts;
  3122. bool IsConcat = true;
  3123. SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
  3124. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3125. int Idx = Mask[i];
  3126. if (Idx < 0)
  3127. continue;
  3128. // Ensure the indices in each SrcVT sized piece are sequential and that
  3129. // the same source is used for the whole piece.
  3130. if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
  3131. (ConcatSrcs[i / SrcNumElts] >= 0 &&
  3132. ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
  3133. IsConcat = false;
  3134. break;
  3135. }
  3136. // Remember which source this index came from.
  3137. ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
  3138. }
  3139. // The shuffle is concatenating multiple vectors together. Just emit
  3140. // a CONCAT_VECTORS operation.
  3141. if (IsConcat) {
  3142. SmallVector<SDValue, 8> ConcatOps;
  3143. for (auto Src : ConcatSrcs) {
  3144. if (Src < 0)
  3145. ConcatOps.push_back(DAG.getUNDEF(SrcVT));
  3146. else if (Src == 0)
  3147. ConcatOps.push_back(Src1);
  3148. else
  3149. ConcatOps.push_back(Src2);
  3150. }
  3151. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
  3152. return;
  3153. }
  3154. }
  3155. unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
  3156. unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
  3157. EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  3158. PaddedMaskNumElts);
  3159. // Pad both vectors with undefs to make them the same length as the mask.
  3160. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  3161. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  3162. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  3163. MOps1[0] = Src1;
  3164. MOps2[0] = Src2;
  3165. Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
  3166. Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
  3167. // Readjust mask for new input vector length.
  3168. SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
  3169. for (unsigned i = 0; i != MaskNumElts; ++i) {
  3170. int Idx = Mask[i];
  3171. if (Idx >= (int)SrcNumElts)
  3172. Idx -= SrcNumElts - PaddedMaskNumElts;
  3173. MappedOps[i] = Idx;
  3174. }
  3175. SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
  3176. // If the concatenated vector was padded, extract a subvector with the
  3177. // correct number of elements.
  3178. if (MaskNumElts != PaddedMaskNumElts)
  3179. Result = DAG.getNode(
  3180. ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
  3181. DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3182. setValue(&I, Result);
  3183. return;
  3184. }
  3185. if (SrcNumElts > MaskNumElts) {
  3186. // Analyze the access pattern of the vector to see if we can extract
  3187. // two subvectors and do the shuffle.
  3188. int StartIdx[2] = { -1, -1 }; // StartIdx to extract from
  3189. bool CanExtract = true;
  3190. for (int Idx : Mask) {
  3191. unsigned Input = 0;
  3192. if (Idx < 0)
  3193. continue;
  3194. if (Idx >= (int)SrcNumElts) {
  3195. Input = 1;
  3196. Idx -= SrcNumElts;
  3197. }
  3198. // If all the indices come from the same MaskNumElts sized portion of
  3199. // the sources we can use extract. Also make sure the extract wouldn't
  3200. // extract past the end of the source.
  3201. int NewStartIdx = alignDown(Idx, MaskNumElts);
  3202. if (NewStartIdx + MaskNumElts > SrcNumElts ||
  3203. (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
  3204. CanExtract = false;
  3205. // Make sure we always update StartIdx as we use it to track if all
  3206. // elements are undef.
  3207. StartIdx[Input] = NewStartIdx;
  3208. }
  3209. if (StartIdx[0] < 0 && StartIdx[1] < 0) {
  3210. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  3211. return;
  3212. }
  3213. if (CanExtract) {
  3214. // Extract appropriate subvector and generate a vector shuffle
  3215. for (unsigned Input = 0; Input < 2; ++Input) {
  3216. SDValue &Src = Input == 0 ? Src1 : Src2;
  3217. if (StartIdx[Input] < 0)
  3218. Src = DAG.getUNDEF(VT);
  3219. else {
  3220. Src = DAG.getNode(
  3221. ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
  3222. DAG.getConstant(StartIdx[Input], DL,
  3223. TLI.getVectorIdxTy(DAG.getDataLayout())));
  3224. }
  3225. }
  3226. // Calculate new mask.
  3227. SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
  3228. for (int &Idx : MappedOps) {
  3229. if (Idx >= (int)SrcNumElts)
  3230. Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
  3231. else if (Idx >= 0)
  3232. Idx -= StartIdx[0];
  3233. }
  3234. setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
  3235. return;
  3236. }
  3237. }
  3238. // We can't use either concat vectors or extract subvectors so fall back to
  3239. // replacing the shuffle with extract and build vector.
  3240. // to insert and build vector.
  3241. EVT EltVT = VT.getVectorElementType();
  3242. EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
  3243. SmallVector<SDValue,8> Ops;
  3244. for (int Idx : Mask) {
  3245. SDValue Res;
  3246. if (Idx < 0) {
  3247. Res = DAG.getUNDEF(EltVT);
  3248. } else {
  3249. SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
  3250. if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
  3251. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  3252. EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
  3253. }
  3254. Ops.push_back(Res);
  3255. }
  3256. setValue(&I, DAG.getBuildVector(VT, DL, Ops));
  3257. }
  3258. void SelectionDAGBuilder::visitInsertValue(const User &I) {
  3259. ArrayRef<unsigned> Indices;
  3260. if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
  3261. Indices = IV->getIndices();
  3262. else
  3263. Indices = cast<ConstantExpr>(&I)->getIndices();
  3264. const Value *Op0 = I.getOperand(0);
  3265. const Value *Op1 = I.getOperand(1);
  3266. Type *AggTy = I.getType();
  3267. Type *ValTy = Op1->getType();
  3268. bool IntoUndef = isa<UndefValue>(Op0);
  3269. bool FromUndef = isa<UndefValue>(Op1);
  3270. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3271. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3272. SmallVector<EVT, 4> AggValueVTs;
  3273. ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
  3274. SmallVector<EVT, 4> ValValueVTs;
  3275. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3276. unsigned NumAggValues = AggValueVTs.size();
  3277. unsigned NumValValues = ValValueVTs.size();
  3278. SmallVector<SDValue, 4> Values(NumAggValues);
  3279. // Ignore an insertvalue that produces an empty object
  3280. if (!NumAggValues) {
  3281. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3282. return;
  3283. }
  3284. SDValue Agg = getValue(Op0);
  3285. unsigned i = 0;
  3286. // Copy the beginning value(s) from the original aggregate.
  3287. for (; i != LinearIndex; ++i)
  3288. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3289. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3290. // Copy values from the inserted value(s).
  3291. if (NumValValues) {
  3292. SDValue Val = getValue(Op1);
  3293. for (; i != LinearIndex + NumValValues; ++i)
  3294. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3295. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  3296. }
  3297. // Copy remaining value(s) from the original aggregate.
  3298. for (; i != NumAggValues; ++i)
  3299. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  3300. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3301. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3302. DAG.getVTList(AggValueVTs), Values));
  3303. }
  3304. void SelectionDAGBuilder::visitExtractValue(const User &I) {
  3305. ArrayRef<unsigned> Indices;
  3306. if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
  3307. Indices = EV->getIndices();
  3308. else
  3309. Indices = cast<ConstantExpr>(&I)->getIndices();
  3310. const Value *Op0 = I.getOperand(0);
  3311. Type *AggTy = Op0->getType();
  3312. Type *ValTy = I.getType();
  3313. bool OutOfUndef = isa<UndefValue>(Op0);
  3314. unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
  3315. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3316. SmallVector<EVT, 4> ValValueVTs;
  3317. ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
  3318. unsigned NumValValues = ValValueVTs.size();
  3319. // Ignore a extractvalue that produces an empty object
  3320. if (!NumValValues) {
  3321. setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
  3322. return;
  3323. }
  3324. SmallVector<SDValue, 4> Values(NumValValues);
  3325. SDValue Agg = getValue(Op0);
  3326. // Copy out the selected value(s).
  3327. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  3328. Values[i - LinearIndex] =
  3329. OutOfUndef ?
  3330. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  3331. SDValue(Agg.getNode(), Agg.getResNo() + i);
  3332. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  3333. DAG.getVTList(ValValueVTs), Values));
  3334. }
  3335. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  3336. Value *Op0 = I.getOperand(0);
  3337. // Note that the pointer operand may be a vector of pointers. Take the scalar
  3338. // element which holds a pointer.
  3339. unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
  3340. SDValue N = getValue(Op0);
  3341. SDLoc dl = getCurSDLoc();
  3342. auto &TLI = DAG.getTargetLoweringInfo();
  3343. MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
  3344. MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
  3345. // Normalize Vector GEP - all scalar operands should be converted to the
  3346. // splat vector.
  3347. unsigned VectorWidth = I.getType()->isVectorTy() ?
  3348. I.getType()->getVectorNumElements() : 0;
  3349. if (VectorWidth && !N.getValueType().isVector()) {
  3350. LLVMContext &Context = *DAG.getContext();
  3351. EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
  3352. N = DAG.getSplatBuildVector(VT, dl, N);
  3353. }
  3354. for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
  3355. GTI != E; ++GTI) {
  3356. const Value *Idx = GTI.getOperand();
  3357. if (StructType *StTy = GTI.getStructTypeOrNull()) {
  3358. unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
  3359. if (Field) {
  3360. // N = N + Offset
  3361. uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
  3362. // In an inbounds GEP with an offset that is nonnegative even when
  3363. // interpreted as signed, assume there is no unsigned overflow.
  3364. SDNodeFlags Flags;
  3365. if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
  3366. Flags.setNoUnsignedWrap(true);
  3367. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
  3368. DAG.getConstant(Offset, dl, N.getValueType()), Flags);
  3369. }
  3370. } else {
  3371. unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
  3372. MVT IdxTy = MVT::getIntegerVT(IdxSize);
  3373. APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
  3374. // If this is a scalar constant or a splat vector of constants,
  3375. // handle it quickly.
  3376. const auto *C = dyn_cast<Constant>(Idx);
  3377. if (C && isa<VectorType>(C->getType()))
  3378. C = C->getSplatValue();
  3379. if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
  3380. if (CI->isZero())
  3381. continue;
  3382. APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
  3383. LLVMContext &Context = *DAG.getContext();
  3384. SDValue OffsVal = VectorWidth ?
  3385. DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
  3386. DAG.getConstant(Offs, dl, IdxTy);
  3387. // In an inbounds GEP with an offset that is nonnegative even when
  3388. // interpreted as signed, assume there is no unsigned overflow.
  3389. SDNodeFlags Flags;
  3390. if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
  3391. Flags.setNoUnsignedWrap(true);
  3392. OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
  3393. N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
  3394. continue;
  3395. }
  3396. // N = N + Idx * ElementSize;
  3397. SDValue IdxN = getValue(Idx);
  3398. if (!IdxN.getValueType().isVector() && VectorWidth) {
  3399. EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
  3400. IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
  3401. }
  3402. // If the index is smaller or larger than intptr_t, truncate or extend
  3403. // it.
  3404. IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
  3405. // If this is a multiply by a power of two, turn it into a shl
  3406. // immediately. This is a very common case.
  3407. if (ElementSize != 1) {
  3408. if (ElementSize.isPowerOf2()) {
  3409. unsigned Amt = ElementSize.logBase2();
  3410. IdxN = DAG.getNode(ISD::SHL, dl,
  3411. N.getValueType(), IdxN,
  3412. DAG.getConstant(Amt, dl, IdxN.getValueType()));
  3413. } else {
  3414. SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
  3415. IdxN.getValueType());
  3416. IdxN = DAG.getNode(ISD::MUL, dl,
  3417. N.getValueType(), IdxN, Scale);
  3418. }
  3419. }
  3420. N = DAG.getNode(ISD::ADD, dl,
  3421. N.getValueType(), N, IdxN);
  3422. }
  3423. }
  3424. if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
  3425. N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
  3426. setValue(&I, N);
  3427. }
  3428. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  3429. // If this is a fixed sized alloca in the entry block of the function,
  3430. // allocate it statically on the stack.
  3431. if (FuncInfo.StaticAllocaMap.count(&I))
  3432. return; // getValue will auto-populate this.
  3433. SDLoc dl = getCurSDLoc();
  3434. Type *Ty = I.getAllocatedType();
  3435. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3436. auto &DL = DAG.getDataLayout();
  3437. uint64_t TySize = DL.getTypeAllocSize(Ty);
  3438. unsigned Align =
  3439. std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
  3440. SDValue AllocSize = getValue(I.getArraySize());
  3441. EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
  3442. if (AllocSize.getValueType() != IntPtr)
  3443. AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
  3444. AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
  3445. AllocSize,
  3446. DAG.getConstant(TySize, dl, IntPtr));
  3447. // Handle alignment. If the requested alignment is less than or equal to
  3448. // the stack alignment, ignore it. If the size is greater than or equal to
  3449. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  3450. unsigned StackAlign =
  3451. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  3452. if (Align <= StackAlign)
  3453. Align = 0;
  3454. // Round the size of the allocation up to the stack alignment size
  3455. // by add SA-1 to the size. This doesn't overflow because we're computing
  3456. // an address inside an alloca.
  3457. SDNodeFlags Flags;
  3458. Flags.setNoUnsignedWrap(true);
  3459. AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
  3460. DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
  3461. // Mask out the low bits for alignment purposes.
  3462. AllocSize =
  3463. DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
  3464. DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
  3465. SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
  3466. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  3467. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
  3468. setValue(&I, DSA);
  3469. DAG.setRoot(DSA.getValue(1));
  3470. assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
  3471. }
  3472. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  3473. if (I.isAtomic())
  3474. return visitAtomicLoad(I);
  3475. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3476. const Value *SV = I.getOperand(0);
  3477. if (TLI.supportSwiftError()) {
  3478. // Swifterror values can come from either a function parameter with
  3479. // swifterror attribute or an alloca with swifterror attribute.
  3480. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  3481. if (Arg->hasSwiftErrorAttr())
  3482. return visitLoadFromSwiftError(I);
  3483. }
  3484. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  3485. if (Alloca->isSwiftError())
  3486. return visitLoadFromSwiftError(I);
  3487. }
  3488. }
  3489. SDValue Ptr = getValue(SV);
  3490. Type *Ty = I.getType();
  3491. bool isVolatile = I.isVolatile();
  3492. bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
  3493. bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
  3494. bool isDereferenceable =
  3495. isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
  3496. unsigned Alignment = I.getAlignment();
  3497. AAMDNodes AAInfo;
  3498. I.getAAMetadata(AAInfo);
  3499. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3500. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3501. SmallVector<uint64_t, 4> Offsets;
  3502. ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
  3503. unsigned NumValues = ValueVTs.size();
  3504. if (NumValues == 0)
  3505. return;
  3506. SDValue Root;
  3507. bool ConstantMemory = false;
  3508. if (isVolatile || NumValues > MaxParallelChains)
  3509. // Serialize volatile loads with other side effects.
  3510. Root = getRoot();
  3511. else if (AA &&
  3512. AA->pointsToConstantMemory(MemoryLocation(
  3513. SV,
  3514. LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3515. AAInfo))) {
  3516. // Do not serialize (non-volatile) loads of constant memory with anything.
  3517. Root = DAG.getEntryNode();
  3518. ConstantMemory = true;
  3519. } else {
  3520. // Do not serialize non-volatile loads against each other.
  3521. Root = DAG.getRoot();
  3522. }
  3523. SDLoc dl = getCurSDLoc();
  3524. if (isVolatile)
  3525. Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
  3526. // An aggregate load cannot wrap around the address space, so offsets to its
  3527. // parts don't wrap either.
  3528. SDNodeFlags Flags;
  3529. Flags.setNoUnsignedWrap(true);
  3530. SmallVector<SDValue, 4> Values(NumValues);
  3531. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3532. EVT PtrVT = Ptr.getValueType();
  3533. unsigned ChainI = 0;
  3534. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3535. // Serializing loads here may result in excessive register pressure, and
  3536. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  3537. // could recover a bit by hoisting nodes upward in the chain by recognizing
  3538. // they are side-effect free or do not alias. The optimizer should really
  3539. // avoid this case by converting large object/array copies to llvm.memcpy
  3540. // (MaxParallelChains should always remain as failsafe).
  3541. if (ChainI == MaxParallelChains) {
  3542. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  3543. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3544. makeArrayRef(Chains.data(), ChainI));
  3545. Root = Chain;
  3546. ChainI = 0;
  3547. }
  3548. SDValue A = DAG.getNode(ISD::ADD, dl,
  3549. PtrVT, Ptr,
  3550. DAG.getConstant(Offsets[i], dl, PtrVT),
  3551. Flags);
  3552. auto MMOFlags = MachineMemOperand::MONone;
  3553. if (isVolatile)
  3554. MMOFlags |= MachineMemOperand::MOVolatile;
  3555. if (isNonTemporal)
  3556. MMOFlags |= MachineMemOperand::MONonTemporal;
  3557. if (isInvariant)
  3558. MMOFlags |= MachineMemOperand::MOInvariant;
  3559. if (isDereferenceable)
  3560. MMOFlags |= MachineMemOperand::MODereferenceable;
  3561. MMOFlags |= TLI.getMMOFlags(I);
  3562. SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
  3563. MachinePointerInfo(SV, Offsets[i]), Alignment,
  3564. MMOFlags, AAInfo, Ranges);
  3565. Chains[ChainI] = L.getValue(1);
  3566. if (MemVTs[i] != ValueVTs[i])
  3567. L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
  3568. Values[i] = L;
  3569. }
  3570. if (!ConstantMemory) {
  3571. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3572. makeArrayRef(Chains.data(), ChainI));
  3573. if (isVolatile)
  3574. DAG.setRoot(Chain);
  3575. else
  3576. PendingLoads.push_back(Chain);
  3577. }
  3578. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
  3579. DAG.getVTList(ValueVTs), Values));
  3580. }
  3581. void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
  3582. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3583. "call visitStoreToSwiftError when backend supports swifterror");
  3584. SmallVector<EVT, 4> ValueVTs;
  3585. SmallVector<uint64_t, 4> Offsets;
  3586. const Value *SrcV = I.getOperand(0);
  3587. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3588. SrcV->getType(), ValueVTs, &Offsets);
  3589. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3590. "expect a single EVT for swifterror");
  3591. SDValue Src = getValue(SrcV);
  3592. // Create a virtual register, then update the virtual register.
  3593. Register VReg =
  3594. SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
  3595. // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
  3596. // Chain can be getRoot or getControlRoot.
  3597. SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
  3598. SDValue(Src.getNode(), Src.getResNo()));
  3599. DAG.setRoot(CopyNode);
  3600. }
  3601. void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
  3602. assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
  3603. "call visitLoadFromSwiftError when backend supports swifterror");
  3604. assert(!I.isVolatile() &&
  3605. !I.hasMetadata(LLVMContext::MD_nontemporal) &&
  3606. !I.hasMetadata(LLVMContext::MD_invariant_load) &&
  3607. "Support volatile, non temporal, invariant for load_from_swift_error");
  3608. const Value *SV = I.getOperand(0);
  3609. Type *Ty = I.getType();
  3610. AAMDNodes AAInfo;
  3611. I.getAAMetadata(AAInfo);
  3612. assert(
  3613. (!AA ||
  3614. !AA->pointsToConstantMemory(MemoryLocation(
  3615. SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
  3616. AAInfo))) &&
  3617. "load_from_swift_error should not be constant memory");
  3618. SmallVector<EVT, 4> ValueVTs;
  3619. SmallVector<uint64_t, 4> Offsets;
  3620. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
  3621. ValueVTs, &Offsets);
  3622. assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
  3623. "expect a single EVT for swifterror");
  3624. // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
  3625. SDValue L = DAG.getCopyFromReg(
  3626. getRoot(), getCurSDLoc(),
  3627. SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
  3628. setValue(&I, L);
  3629. }
  3630. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  3631. if (I.isAtomic())
  3632. return visitAtomicStore(I);
  3633. const Value *SrcV = I.getOperand(0);
  3634. const Value *PtrV = I.getOperand(1);
  3635. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3636. if (TLI.supportSwiftError()) {
  3637. // Swifterror values can come from either a function parameter with
  3638. // swifterror attribute or an alloca with swifterror attribute.
  3639. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  3640. if (Arg->hasSwiftErrorAttr())
  3641. return visitStoreToSwiftError(I);
  3642. }
  3643. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  3644. if (Alloca->isSwiftError())
  3645. return visitStoreToSwiftError(I);
  3646. }
  3647. }
  3648. SmallVector<EVT, 4> ValueVTs, MemVTs;
  3649. SmallVector<uint64_t, 4> Offsets;
  3650. ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
  3651. SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
  3652. unsigned NumValues = ValueVTs.size();
  3653. if (NumValues == 0)
  3654. return;
  3655. // Get the lowered operands. Note that we do this after
  3656. // checking if NumResults is zero, because with zero results
  3657. // the operands won't have values in the map.
  3658. SDValue Src = getValue(SrcV);
  3659. SDValue Ptr = getValue(PtrV);
  3660. SDValue Root = getRoot();
  3661. SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
  3662. SDLoc dl = getCurSDLoc();
  3663. EVT PtrVT = Ptr.getValueType();
  3664. unsigned Alignment = I.getAlignment();
  3665. AAMDNodes AAInfo;
  3666. I.getAAMetadata(AAInfo);
  3667. auto MMOFlags = MachineMemOperand::MONone;
  3668. if (I.isVolatile())
  3669. MMOFlags |= MachineMemOperand::MOVolatile;
  3670. if (I.hasMetadata(LLVMContext::MD_nontemporal))
  3671. MMOFlags |= MachineMemOperand::MONonTemporal;
  3672. MMOFlags |= TLI.getMMOFlags(I);
  3673. // An aggregate load cannot wrap around the address space, so offsets to its
  3674. // parts don't wrap either.
  3675. SDNodeFlags Flags;
  3676. Flags.setNoUnsignedWrap(true);
  3677. unsigned ChainI = 0;
  3678. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  3679. // See visitLoad comments.
  3680. if (ChainI == MaxParallelChains) {
  3681. SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3682. makeArrayRef(Chains.data(), ChainI));
  3683. Root = Chain;
  3684. ChainI = 0;
  3685. }
  3686. SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
  3687. DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
  3688. SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
  3689. if (MemVTs[i] != ValueVTs[i])
  3690. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
  3691. SDValue St =
  3692. DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
  3693. Alignment, MMOFlags, AAInfo);
  3694. Chains[ChainI] = St;
  3695. }
  3696. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3697. makeArrayRef(Chains.data(), ChainI));
  3698. DAG.setRoot(StoreNode);
  3699. }
  3700. void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
  3701. bool IsCompressing) {
  3702. SDLoc sdl = getCurSDLoc();
  3703. auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3704. unsigned& Alignment) {
  3705. // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
  3706. Src0 = I.getArgOperand(0);
  3707. Ptr = I.getArgOperand(1);
  3708. Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
  3709. Mask = I.getArgOperand(3);
  3710. };
  3711. auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3712. unsigned& Alignment) {
  3713. // llvm.masked.compressstore.*(Src0, Ptr, Mask)
  3714. Src0 = I.getArgOperand(0);
  3715. Ptr = I.getArgOperand(1);
  3716. Mask = I.getArgOperand(2);
  3717. Alignment = 0;
  3718. };
  3719. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3720. unsigned Alignment;
  3721. if (IsCompressing)
  3722. getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3723. else
  3724. getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3725. SDValue Ptr = getValue(PtrOperand);
  3726. SDValue Src0 = getValue(Src0Operand);
  3727. SDValue Mask = getValue(MaskOperand);
  3728. EVT VT = Src0.getValueType();
  3729. if (!Alignment)
  3730. Alignment = DAG.getEVTAlignment(VT);
  3731. AAMDNodes AAInfo;
  3732. I.getAAMetadata(AAInfo);
  3733. MachineMemOperand *MMO =
  3734. DAG.getMachineFunction().
  3735. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3736. MachineMemOperand::MOStore, VT.getStoreSize(),
  3737. Alignment, AAInfo);
  3738. SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
  3739. MMO, false /* Truncating */,
  3740. IsCompressing);
  3741. DAG.setRoot(StoreNode);
  3742. setValue(&I, StoreNode);
  3743. }
  3744. // Get a uniform base for the Gather/Scatter intrinsic.
  3745. // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
  3746. // We try to represent it as a base pointer + vector of indices.
  3747. // Usually, the vector of pointers comes from a 'getelementptr' instruction.
  3748. // The first operand of the GEP may be a single pointer or a vector of pointers
  3749. // Example:
  3750. // %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
  3751. // or
  3752. // %gep.ptr = getelementptr i32, i32* %ptr, <8 x i32> %ind
  3753. // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
  3754. //
  3755. // When the first GEP operand is a single pointer - it is the uniform base we
  3756. // are looking for. If first operand of the GEP is a splat vector - we
  3757. // extract the splat value and use it as a uniform base.
  3758. // In all other cases the function returns 'false'.
  3759. static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
  3760. ISD::MemIndexType &IndexType, SDValue &Scale,
  3761. SelectionDAGBuilder *SDB) {
  3762. SelectionDAG& DAG = SDB->DAG;
  3763. LLVMContext &Context = *DAG.getContext();
  3764. assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
  3765. const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  3766. if (!GEP)
  3767. return false;
  3768. const Value *GEPPtr = GEP->getPointerOperand();
  3769. if (!GEPPtr->getType()->isVectorTy())
  3770. Ptr = GEPPtr;
  3771. else if (!(Ptr = getSplatValue(GEPPtr)))
  3772. return false;
  3773. unsigned FinalIndex = GEP->getNumOperands() - 1;
  3774. Value *IndexVal = GEP->getOperand(FinalIndex);
  3775. // Ensure all the other indices are 0.
  3776. for (unsigned i = 1; i < FinalIndex; ++i) {
  3777. auto *C = dyn_cast<Constant>(GEP->getOperand(i));
  3778. if (!C)
  3779. return false;
  3780. if (isa<VectorType>(C->getType()))
  3781. C = C->getSplatValue();
  3782. auto *CI = dyn_cast_or_null<ConstantInt>(C);
  3783. if (!CI || !CI->isZero())
  3784. return false;
  3785. }
  3786. // The operands of the GEP may be defined in another basic block.
  3787. // In this case we'll not find nodes for the operands.
  3788. if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
  3789. return false;
  3790. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3791. const DataLayout &DL = DAG.getDataLayout();
  3792. Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
  3793. SDB->getCurSDLoc(), TLI.getPointerTy(DL));
  3794. Base = SDB->getValue(Ptr);
  3795. Index = SDB->getValue(IndexVal);
  3796. IndexType = ISD::SIGNED_SCALED;
  3797. if (!Index.getValueType().isVector()) {
  3798. unsigned GEPWidth = GEP->getType()->getVectorNumElements();
  3799. EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
  3800. Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
  3801. }
  3802. return true;
  3803. }
  3804. void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
  3805. SDLoc sdl = getCurSDLoc();
  3806. // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
  3807. const Value *Ptr = I.getArgOperand(1);
  3808. SDValue Src0 = getValue(I.getArgOperand(0));
  3809. SDValue Mask = getValue(I.getArgOperand(3));
  3810. EVT VT = Src0.getValueType();
  3811. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
  3812. if (!Alignment)
  3813. Alignment = DAG.getEVTAlignment(VT);
  3814. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3815. AAMDNodes AAInfo;
  3816. I.getAAMetadata(AAInfo);
  3817. SDValue Base;
  3818. SDValue Index;
  3819. ISD::MemIndexType IndexType;
  3820. SDValue Scale;
  3821. const Value *BasePtr = Ptr;
  3822. bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
  3823. this);
  3824. const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
  3825. MachineMemOperand *MMO = DAG.getMachineFunction().
  3826. getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
  3827. MachineMemOperand::MOStore, VT.getStoreSize(),
  3828. Alignment, AAInfo);
  3829. if (!UniformBase) {
  3830. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3831. Index = getValue(Ptr);
  3832. IndexType = ISD::SIGNED_SCALED;
  3833. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3834. }
  3835. SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
  3836. SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
  3837. Ops, MMO, IndexType);
  3838. DAG.setRoot(Scatter);
  3839. setValue(&I, Scatter);
  3840. }
  3841. void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
  3842. SDLoc sdl = getCurSDLoc();
  3843. auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3844. unsigned& Alignment) {
  3845. // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
  3846. Ptr = I.getArgOperand(0);
  3847. Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  3848. Mask = I.getArgOperand(2);
  3849. Src0 = I.getArgOperand(3);
  3850. };
  3851. auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
  3852. unsigned& Alignment) {
  3853. // @llvm.masked.expandload.*(Ptr, Mask, Src0)
  3854. Ptr = I.getArgOperand(0);
  3855. Alignment = 0;
  3856. Mask = I.getArgOperand(1);
  3857. Src0 = I.getArgOperand(2);
  3858. };
  3859. Value *PtrOperand, *MaskOperand, *Src0Operand;
  3860. unsigned Alignment;
  3861. if (IsExpanding)
  3862. getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3863. else
  3864. getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
  3865. SDValue Ptr = getValue(PtrOperand);
  3866. SDValue Src0 = getValue(Src0Operand);
  3867. SDValue Mask = getValue(MaskOperand);
  3868. EVT VT = Src0.getValueType();
  3869. if (!Alignment)
  3870. Alignment = DAG.getEVTAlignment(VT);
  3871. AAMDNodes AAInfo;
  3872. I.getAAMetadata(AAInfo);
  3873. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3874. // Do not serialize masked loads of constant memory with anything.
  3875. bool AddToChain =
  3876. !AA || !AA->pointsToConstantMemory(MemoryLocation(
  3877. PtrOperand,
  3878. LocationSize::precise(
  3879. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3880. AAInfo));
  3881. SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
  3882. MachineMemOperand *MMO =
  3883. DAG.getMachineFunction().
  3884. getMachineMemOperand(MachinePointerInfo(PtrOperand),
  3885. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3886. Alignment, AAInfo, Ranges);
  3887. SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
  3888. ISD::NON_EXTLOAD, IsExpanding);
  3889. if (AddToChain)
  3890. PendingLoads.push_back(Load.getValue(1));
  3891. setValue(&I, Load);
  3892. }
  3893. void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
  3894. SDLoc sdl = getCurSDLoc();
  3895. // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
  3896. const Value *Ptr = I.getArgOperand(0);
  3897. SDValue Src0 = getValue(I.getArgOperand(3));
  3898. SDValue Mask = getValue(I.getArgOperand(2));
  3899. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  3900. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  3901. unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
  3902. if (!Alignment)
  3903. Alignment = DAG.getEVTAlignment(VT);
  3904. AAMDNodes AAInfo;
  3905. I.getAAMetadata(AAInfo);
  3906. const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
  3907. SDValue Root = DAG.getRoot();
  3908. SDValue Base;
  3909. SDValue Index;
  3910. ISD::MemIndexType IndexType;
  3911. SDValue Scale;
  3912. const Value *BasePtr = Ptr;
  3913. bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
  3914. this);
  3915. bool ConstantMemory = false;
  3916. if (UniformBase && AA &&
  3917. AA->pointsToConstantMemory(
  3918. MemoryLocation(BasePtr,
  3919. LocationSize::precise(
  3920. DAG.getDataLayout().getTypeStoreSize(I.getType())),
  3921. AAInfo))) {
  3922. // Do not serialize (non-volatile) loads of constant memory with anything.
  3923. Root = DAG.getEntryNode();
  3924. ConstantMemory = true;
  3925. }
  3926. MachineMemOperand *MMO =
  3927. DAG.getMachineFunction().
  3928. getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
  3929. MachineMemOperand::MOLoad, VT.getStoreSize(),
  3930. Alignment, AAInfo, Ranges);
  3931. if (!UniformBase) {
  3932. Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3933. Index = getValue(Ptr);
  3934. IndexType = ISD::SIGNED_SCALED;
  3935. Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
  3936. }
  3937. SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
  3938. SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
  3939. Ops, MMO, IndexType);
  3940. SDValue OutChain = Gather.getValue(1);
  3941. if (!ConstantMemory)
  3942. PendingLoads.push_back(OutChain);
  3943. setValue(&I, Gather);
  3944. }
  3945. void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
  3946. SDLoc dl = getCurSDLoc();
  3947. AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
  3948. AtomicOrdering FailureOrdering = I.getFailureOrdering();
  3949. SyncScope::ID SSID = I.getSyncScopeID();
  3950. SDValue InChain = getRoot();
  3951. MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
  3952. SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
  3953. auto Alignment = DAG.getEVTAlignment(MemVT);
  3954. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3955. if (I.isVolatile())
  3956. Flags |= MachineMemOperand::MOVolatile;
  3957. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  3958. MachineFunction &MF = DAG.getMachineFunction();
  3959. MachineMemOperand *MMO =
  3960. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  3961. Flags, MemVT.getStoreSize(), Alignment,
  3962. AAMDNodes(), nullptr, SSID, SuccessOrdering,
  3963. FailureOrdering);
  3964. SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
  3965. dl, MemVT, VTs, InChain,
  3966. getValue(I.getPointerOperand()),
  3967. getValue(I.getCompareOperand()),
  3968. getValue(I.getNewValOperand()), MMO);
  3969. SDValue OutChain = L.getValue(2);
  3970. setValue(&I, L);
  3971. DAG.setRoot(OutChain);
  3972. }
  3973. void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
  3974. SDLoc dl = getCurSDLoc();
  3975. ISD::NodeType NT;
  3976. switch (I.getOperation()) {
  3977. default: llvm_unreachable("Unknown atomicrmw operation");
  3978. case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
  3979. case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
  3980. case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
  3981. case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
  3982. case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
  3983. case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
  3984. case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
  3985. case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
  3986. case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
  3987. case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
  3988. case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
  3989. case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
  3990. case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
  3991. }
  3992. AtomicOrdering Ordering = I.getOrdering();
  3993. SyncScope::ID SSID = I.getSyncScopeID();
  3994. SDValue InChain = getRoot();
  3995. auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
  3996. auto Alignment = DAG.getEVTAlignment(MemVT);
  3997. auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  3998. if (I.isVolatile())
  3999. Flags |= MachineMemOperand::MOVolatile;
  4000. Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
  4001. MachineFunction &MF = DAG.getMachineFunction();
  4002. MachineMemOperand *MMO =
  4003. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4004. MemVT.getStoreSize(), Alignment, AAMDNodes(),
  4005. nullptr, SSID, Ordering);
  4006. SDValue L =
  4007. DAG.getAtomic(NT, dl, MemVT, InChain,
  4008. getValue(I.getPointerOperand()), getValue(I.getValOperand()),
  4009. MMO);
  4010. SDValue OutChain = L.getValue(1);
  4011. setValue(&I, L);
  4012. DAG.setRoot(OutChain);
  4013. }
  4014. void SelectionDAGBuilder::visitFence(const FenceInst &I) {
  4015. SDLoc dl = getCurSDLoc();
  4016. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4017. SDValue Ops[3];
  4018. Ops[0] = getRoot();
  4019. Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
  4020. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4021. Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
  4022. TLI.getFenceOperandTy(DAG.getDataLayout()));
  4023. DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
  4024. }
  4025. void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
  4026. SDLoc dl = getCurSDLoc();
  4027. AtomicOrdering Order = I.getOrdering();
  4028. SyncScope::ID SSID = I.getSyncScopeID();
  4029. SDValue InChain = getRoot();
  4030. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4031. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4032. EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
  4033. if (!TLI.supportsUnalignedAtomics() &&
  4034. I.getAlignment() < MemVT.getSizeInBits() / 8)
  4035. report_fatal_error("Cannot generate unaligned atomic load");
  4036. auto Flags = MachineMemOperand::MOLoad;
  4037. if (I.isVolatile())
  4038. Flags |= MachineMemOperand::MOVolatile;
  4039. if (I.hasMetadata(LLVMContext::MD_invariant_load))
  4040. Flags |= MachineMemOperand::MOInvariant;
  4041. if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
  4042. DAG.getDataLayout()))
  4043. Flags |= MachineMemOperand::MODereferenceable;
  4044. Flags |= TLI.getMMOFlags(I);
  4045. MachineMemOperand *MMO =
  4046. DAG.getMachineFunction().
  4047. getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
  4048. Flags, MemVT.getStoreSize(),
  4049. I.getAlignment() ? I.getAlignment() :
  4050. DAG.getEVTAlignment(MemVT),
  4051. AAMDNodes(), nullptr, SSID, Order);
  4052. InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
  4053. SDValue L =
  4054. DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
  4055. getValue(I.getPointerOperand()), MMO);
  4056. SDValue OutChain = L.getValue(1);
  4057. if (MemVT != VT)
  4058. L = DAG.getPtrExtOrTrunc(L, dl, VT);
  4059. setValue(&I, L);
  4060. DAG.setRoot(OutChain);
  4061. }
  4062. void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
  4063. SDLoc dl = getCurSDLoc();
  4064. AtomicOrdering Ordering = I.getOrdering();
  4065. SyncScope::ID SSID = I.getSyncScopeID();
  4066. SDValue InChain = getRoot();
  4067. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4068. EVT MemVT =
  4069. TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
  4070. if (I.getAlignment() < MemVT.getSizeInBits() / 8)
  4071. report_fatal_error("Cannot generate unaligned atomic store");
  4072. auto Flags = MachineMemOperand::MOStore;
  4073. if (I.isVolatile())
  4074. Flags |= MachineMemOperand::MOVolatile;
  4075. Flags |= TLI.getMMOFlags(I);
  4076. MachineFunction &MF = DAG.getMachineFunction();
  4077. MachineMemOperand *MMO =
  4078. MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
  4079. MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
  4080. nullptr, SSID, Ordering);
  4081. SDValue Val = getValue(I.getValueOperand());
  4082. if (Val.getValueType() != MemVT)
  4083. Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
  4084. SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
  4085. getValue(I.getPointerOperand()), Val, MMO);
  4086. DAG.setRoot(OutChain);
  4087. }
  4088. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  4089. /// node.
  4090. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  4091. unsigned Intrinsic) {
  4092. // Ignore the callsite's attributes. A specific call site may be marked with
  4093. // readnone, but the lowering code will expect the chain based on the
  4094. // definition.
  4095. const Function *F = I.getCalledFunction();
  4096. bool HasChain = !F->doesNotAccessMemory();
  4097. bool OnlyLoad = HasChain && F->onlyReadsMemory();
  4098. // Build the operand list.
  4099. SmallVector<SDValue, 8> Ops;
  4100. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  4101. if (OnlyLoad) {
  4102. // We don't need to serialize loads against other loads.
  4103. Ops.push_back(DAG.getRoot());
  4104. } else {
  4105. Ops.push_back(getRoot());
  4106. }
  4107. }
  4108. // Info is set by getTgtMemInstrinsic
  4109. TargetLowering::IntrinsicInfo Info;
  4110. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4111. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
  4112. DAG.getMachineFunction(),
  4113. Intrinsic);
  4114. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  4115. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  4116. Info.opc == ISD::INTRINSIC_W_CHAIN)
  4117. Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
  4118. TLI.getPointerTy(DAG.getDataLayout())));
  4119. // Add all operands of the call to the operand list.
  4120. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4121. SDValue Op = getValue(I.getArgOperand(i));
  4122. Ops.push_back(Op);
  4123. }
  4124. SmallVector<EVT, 4> ValueVTs;
  4125. ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
  4126. if (HasChain)
  4127. ValueVTs.push_back(MVT::Other);
  4128. SDVTList VTs = DAG.getVTList(ValueVTs);
  4129. // Create the node.
  4130. SDValue Result;
  4131. if (IsTgtIntrinsic) {
  4132. // This is target intrinsic that touches memory
  4133. AAMDNodes AAInfo;
  4134. I.getAAMetadata(AAInfo);
  4135. Result = DAG.getMemIntrinsicNode(
  4136. Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
  4137. MachinePointerInfo(Info.ptrVal, Info.offset),
  4138. Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
  4139. } else if (!HasChain) {
  4140. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
  4141. } else if (!I.getType()->isVoidTy()) {
  4142. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
  4143. } else {
  4144. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
  4145. }
  4146. if (HasChain) {
  4147. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  4148. if (OnlyLoad)
  4149. PendingLoads.push_back(Chain);
  4150. else
  4151. DAG.setRoot(Chain);
  4152. }
  4153. if (!I.getType()->isVoidTy()) {
  4154. if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  4155. EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
  4156. Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
  4157. } else
  4158. Result = lowerRangeToAssertZExt(DAG, I, Result);
  4159. setValue(&I, Result);
  4160. }
  4161. }
  4162. /// GetSignificand - Get the significand and build it into a floating-point
  4163. /// number with exponent of 1:
  4164. ///
  4165. /// Op = (Op & 0x007fffff) | 0x3f800000;
  4166. ///
  4167. /// where Op is the hexadecimal representation of floating point value.
  4168. static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
  4169. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4170. DAG.getConstant(0x007fffff, dl, MVT::i32));
  4171. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  4172. DAG.getConstant(0x3f800000, dl, MVT::i32));
  4173. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  4174. }
  4175. /// GetExponent - Get the exponent:
  4176. ///
  4177. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  4178. ///
  4179. /// where Op is the hexadecimal representation of floating point value.
  4180. static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
  4181. const TargetLowering &TLI, const SDLoc &dl) {
  4182. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  4183. DAG.getConstant(0x7f800000, dl, MVT::i32));
  4184. SDValue t1 = DAG.getNode(
  4185. ISD::SRL, dl, MVT::i32, t0,
  4186. DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
  4187. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  4188. DAG.getConstant(127, dl, MVT::i32));
  4189. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  4190. }
  4191. /// getF32Constant - Get 32-bit floating point constant.
  4192. static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
  4193. const SDLoc &dl) {
  4194. return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
  4195. MVT::f32);
  4196. }
  4197. static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
  4198. SelectionDAG &DAG) {
  4199. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4200. // IntegerPartOfX = ((int32_t)(t0);
  4201. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  4202. // FractionalPartOfX = t0 - (float)IntegerPartOfX;
  4203. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  4204. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  4205. // IntegerPartOfX <<= 23;
  4206. IntegerPartOfX = DAG.getNode(
  4207. ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  4208. DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
  4209. DAG.getDataLayout())));
  4210. SDValue TwoToFractionalPartOfX;
  4211. if (LimitFloatPrecision <= 6) {
  4212. // For floating-point precision of 6:
  4213. //
  4214. // TwoToFractionalPartOfX =
  4215. // 0.997535578f +
  4216. // (0.735607626f + 0.252464424f * x) * x;
  4217. //
  4218. // error 0.0144103317, which is 6 bits
  4219. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4220. getF32Constant(DAG, 0x3e814304, dl));
  4221. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4222. getF32Constant(DAG, 0x3f3c50c8, dl));
  4223. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4224. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4225. getF32Constant(DAG, 0x3f7f5e7e, dl));
  4226. } else if (LimitFloatPrecision <= 12) {
  4227. // For floating-point precision of 12:
  4228. //
  4229. // TwoToFractionalPartOfX =
  4230. // 0.999892986f +
  4231. // (0.696457318f +
  4232. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  4233. //
  4234. // error 0.000107046256, which is 13 to 14 bits
  4235. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4236. getF32Constant(DAG, 0x3da235e3, dl));
  4237. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4238. getF32Constant(DAG, 0x3e65b8f3, dl));
  4239. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4240. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4241. getF32Constant(DAG, 0x3f324b07, dl));
  4242. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4243. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4244. getF32Constant(DAG, 0x3f7ff8fd, dl));
  4245. } else { // LimitFloatPrecision <= 18
  4246. // For floating-point precision of 18:
  4247. //
  4248. // TwoToFractionalPartOfX =
  4249. // 0.999999982f +
  4250. // (0.693148872f +
  4251. // (0.240227044f +
  4252. // (0.554906021e-1f +
  4253. // (0.961591928e-2f +
  4254. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  4255. // error 2.47208000*10^(-7), which is better than 18 bits
  4256. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4257. getF32Constant(DAG, 0x3924b03e, dl));
  4258. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4259. getF32Constant(DAG, 0x3ab24b87, dl));
  4260. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4261. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4262. getF32Constant(DAG, 0x3c1d8c17, dl));
  4263. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4264. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4265. getF32Constant(DAG, 0x3d634a1d, dl));
  4266. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4267. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4268. getF32Constant(DAG, 0x3e75fe14, dl));
  4269. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4270. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  4271. getF32Constant(DAG, 0x3f317234, dl));
  4272. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  4273. TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  4274. getF32Constant(DAG, 0x3f800000, dl));
  4275. }
  4276. // Add the exponent into the result in integer domain.
  4277. SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
  4278. return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
  4279. DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
  4280. }
  4281. /// expandExp - Lower an exp intrinsic. Handles the special sequences for
  4282. /// limited-precision mode.
  4283. static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4284. const TargetLowering &TLI) {
  4285. if (Op.getValueType() == MVT::f32 &&
  4286. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4287. // Put the exponent in the right bit position for later addition to the
  4288. // final result:
  4289. //
  4290. // #define LOG2OFe 1.4426950f
  4291. // t0 = Op * LOG2OFe
  4292. // TODO: What fast-math-flags should be set here?
  4293. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  4294. getF32Constant(DAG, 0x3fb8aa3b, dl));
  4295. return getLimitedPrecisionExp2(t0, dl, DAG);
  4296. }
  4297. // No special expansion.
  4298. return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
  4299. }
  4300. /// expandLog - Lower a log intrinsic. Handles the special sequences for
  4301. /// limited-precision mode.
  4302. static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4303. const TargetLowering &TLI) {
  4304. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4305. if (Op.getValueType() == MVT::f32 &&
  4306. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4307. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4308. // Scale the exponent by log(2) [0.69314718f].
  4309. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4310. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4311. getF32Constant(DAG, 0x3f317218, dl));
  4312. // Get the significand and build it into a floating-point number with
  4313. // exponent of 1.
  4314. SDValue X = GetSignificand(DAG, Op1, dl);
  4315. SDValue LogOfMantissa;
  4316. if (LimitFloatPrecision <= 6) {
  4317. // For floating-point precision of 6:
  4318. //
  4319. // LogofMantissa =
  4320. // -1.1609546f +
  4321. // (1.4034025f - 0.23903021f * x) * x;
  4322. //
  4323. // error 0.0034276066, which is better than 8 bits
  4324. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4325. getF32Constant(DAG, 0xbe74c456, dl));
  4326. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4327. getF32Constant(DAG, 0x3fb3a2b1, dl));
  4328. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4329. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4330. getF32Constant(DAG, 0x3f949a29, dl));
  4331. } else if (LimitFloatPrecision <= 12) {
  4332. // For floating-point precision of 12:
  4333. //
  4334. // LogOfMantissa =
  4335. // -1.7417939f +
  4336. // (2.8212026f +
  4337. // (-1.4699568f +
  4338. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  4339. //
  4340. // error 0.000061011436, which is 14 bits
  4341. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4342. getF32Constant(DAG, 0xbd67b6d6, dl));
  4343. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4344. getF32Constant(DAG, 0x3ee4f4b8, dl));
  4345. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4346. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4347. getF32Constant(DAG, 0x3fbc278b, dl));
  4348. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4349. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4350. getF32Constant(DAG, 0x40348e95, dl));
  4351. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4352. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4353. getF32Constant(DAG, 0x3fdef31a, dl));
  4354. } else { // LimitFloatPrecision <= 18
  4355. // For floating-point precision of 18:
  4356. //
  4357. // LogOfMantissa =
  4358. // -2.1072184f +
  4359. // (4.2372794f +
  4360. // (-3.7029485f +
  4361. // (2.2781945f +
  4362. // (-0.87823314f +
  4363. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  4364. //
  4365. // error 0.0000023660568, which is better than 18 bits
  4366. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4367. getF32Constant(DAG, 0xbc91e5ac, dl));
  4368. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4369. getF32Constant(DAG, 0x3e4350aa, dl));
  4370. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4371. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4372. getF32Constant(DAG, 0x3f60d3e3, dl));
  4373. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4374. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4375. getF32Constant(DAG, 0x4011cdf0, dl));
  4376. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4377. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4378. getF32Constant(DAG, 0x406cfd1c, dl));
  4379. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4380. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4381. getF32Constant(DAG, 0x408797cb, dl));
  4382. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4383. LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4384. getF32Constant(DAG, 0x4006dcab, dl));
  4385. }
  4386. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
  4387. }
  4388. // No special expansion.
  4389. return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
  4390. }
  4391. /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
  4392. /// limited-precision mode.
  4393. static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4394. const TargetLowering &TLI) {
  4395. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4396. if (Op.getValueType() == MVT::f32 &&
  4397. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4398. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4399. // Get the exponent.
  4400. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  4401. // Get the significand and build it into a floating-point number with
  4402. // exponent of 1.
  4403. SDValue X = GetSignificand(DAG, Op1, dl);
  4404. // Different possible minimax approximations of significand in
  4405. // floating-point for various degrees of accuracy over [1,2].
  4406. SDValue Log2ofMantissa;
  4407. if (LimitFloatPrecision <= 6) {
  4408. // For floating-point precision of 6:
  4409. //
  4410. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  4411. //
  4412. // error 0.0049451742, which is more than 7 bits
  4413. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4414. getF32Constant(DAG, 0xbeb08fe0, dl));
  4415. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4416. getF32Constant(DAG, 0x40019463, dl));
  4417. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4418. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4419. getF32Constant(DAG, 0x3fd6633d, dl));
  4420. } else if (LimitFloatPrecision <= 12) {
  4421. // For floating-point precision of 12:
  4422. //
  4423. // Log2ofMantissa =
  4424. // -2.51285454f +
  4425. // (4.07009056f +
  4426. // (-2.12067489f +
  4427. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  4428. //
  4429. // error 0.0000876136000, which is better than 13 bits
  4430. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4431. getF32Constant(DAG, 0xbda7262e, dl));
  4432. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4433. getF32Constant(DAG, 0x3f25280b, dl));
  4434. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4435. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4436. getF32Constant(DAG, 0x4007b923, dl));
  4437. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4438. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4439. getF32Constant(DAG, 0x40823e2f, dl));
  4440. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4441. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4442. getF32Constant(DAG, 0x4020d29c, dl));
  4443. } else { // LimitFloatPrecision <= 18
  4444. // For floating-point precision of 18:
  4445. //
  4446. // Log2ofMantissa =
  4447. // -3.0400495f +
  4448. // (6.1129976f +
  4449. // (-5.3420409f +
  4450. // (3.2865683f +
  4451. // (-1.2669343f +
  4452. // (0.27515199f -
  4453. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  4454. //
  4455. // error 0.0000018516, which is better than 18 bits
  4456. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4457. getF32Constant(DAG, 0xbcd2769e, dl));
  4458. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4459. getF32Constant(DAG, 0x3e8ce0b9, dl));
  4460. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4461. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4462. getF32Constant(DAG, 0x3fa22ae7, dl));
  4463. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4464. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  4465. getF32Constant(DAG, 0x40525723, dl));
  4466. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4467. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  4468. getF32Constant(DAG, 0x40aaf200, dl));
  4469. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4470. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  4471. getF32Constant(DAG, 0x40c39dad, dl));
  4472. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  4473. Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  4474. getF32Constant(DAG, 0x4042902c, dl));
  4475. }
  4476. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
  4477. }
  4478. // No special expansion.
  4479. return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
  4480. }
  4481. /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
  4482. /// limited-precision mode.
  4483. static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4484. const TargetLowering &TLI) {
  4485. // TODO: What fast-math-flags should be set on the floating-point nodes?
  4486. if (Op.getValueType() == MVT::f32 &&
  4487. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4488. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  4489. // Scale the exponent by log10(2) [0.30102999f].
  4490. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  4491. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  4492. getF32Constant(DAG, 0x3e9a209a, dl));
  4493. // Get the significand and build it into a floating-point number with
  4494. // exponent of 1.
  4495. SDValue X = GetSignificand(DAG, Op1, dl);
  4496. SDValue Log10ofMantissa;
  4497. if (LimitFloatPrecision <= 6) {
  4498. // For floating-point precision of 6:
  4499. //
  4500. // Log10ofMantissa =
  4501. // -0.50419619f +
  4502. // (0.60948995f - 0.10380950f * x) * x;
  4503. //
  4504. // error 0.0014886165, which is 6 bits
  4505. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4506. getF32Constant(DAG, 0xbdd49a13, dl));
  4507. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  4508. getF32Constant(DAG, 0x3f1c0789, dl));
  4509. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4510. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  4511. getF32Constant(DAG, 0x3f011300, dl));
  4512. } else if (LimitFloatPrecision <= 12) {
  4513. // For floating-point precision of 12:
  4514. //
  4515. // Log10ofMantissa =
  4516. // -0.64831180f +
  4517. // (0.91751397f +
  4518. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  4519. //
  4520. // error 0.00019228036, which is better than 12 bits
  4521. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4522. getF32Constant(DAG, 0x3d431f31, dl));
  4523. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4524. getF32Constant(DAG, 0x3ea21fb2, dl));
  4525. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4526. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4527. getF32Constant(DAG, 0x3f6ae232, dl));
  4528. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4529. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4530. getF32Constant(DAG, 0x3f25f7c3, dl));
  4531. } else { // LimitFloatPrecision <= 18
  4532. // For floating-point precision of 18:
  4533. //
  4534. // Log10ofMantissa =
  4535. // -0.84299375f +
  4536. // (1.5327582f +
  4537. // (-1.0688956f +
  4538. // (0.49102474f +
  4539. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  4540. //
  4541. // error 0.0000037995730, which is better than 18 bits
  4542. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  4543. getF32Constant(DAG, 0x3c5d51ce, dl));
  4544. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  4545. getF32Constant(DAG, 0x3e00685a, dl));
  4546. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  4547. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  4548. getF32Constant(DAG, 0x3efb6798, dl));
  4549. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  4550. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  4551. getF32Constant(DAG, 0x3f88d192, dl));
  4552. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  4553. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  4554. getF32Constant(DAG, 0x3fc4316c, dl));
  4555. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  4556. Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  4557. getF32Constant(DAG, 0x3f57ce70, dl));
  4558. }
  4559. return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
  4560. }
  4561. // No special expansion.
  4562. return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
  4563. }
  4564. /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  4565. /// limited-precision mode.
  4566. static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
  4567. const TargetLowering &TLI) {
  4568. if (Op.getValueType() == MVT::f32 &&
  4569. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
  4570. return getLimitedPrecisionExp2(Op, dl, DAG);
  4571. // No special expansion.
  4572. return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
  4573. }
  4574. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  4575. /// limited-precision mode with x == 10.0f.
  4576. static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
  4577. SelectionDAG &DAG, const TargetLowering &TLI) {
  4578. bool IsExp10 = false;
  4579. if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
  4580. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  4581. if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
  4582. APFloat Ten(10.0f);
  4583. IsExp10 = LHSC->isExactlyValue(Ten);
  4584. }
  4585. }
  4586. // TODO: What fast-math-flags should be set on the FMUL node?
  4587. if (IsExp10) {
  4588. // Put the exponent in the right bit position for later addition to the
  4589. // final result:
  4590. //
  4591. // #define LOG2OF10 3.3219281f
  4592. // t0 = Op * LOG2OF10;
  4593. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
  4594. getF32Constant(DAG, 0x40549a78, dl));
  4595. return getLimitedPrecisionExp2(t0, dl, DAG);
  4596. }
  4597. // No special expansion.
  4598. return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
  4599. }
  4600. /// ExpandPowI - Expand a llvm.powi intrinsic.
  4601. static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
  4602. SelectionDAG &DAG) {
  4603. // If RHS is a constant, we can expand this out to a multiplication tree,
  4604. // otherwise we end up lowering to a call to __powidf2 (for example). When
  4605. // optimizing for size, we only want to do this if the expansion would produce
  4606. // a small number of multiplies, otherwise we do the full expansion.
  4607. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  4608. // Get the exponent as a positive value.
  4609. unsigned Val = RHSC->getSExtValue();
  4610. if ((int)Val < 0) Val = -Val;
  4611. // powi(x, 0) -> 1.0
  4612. if (Val == 0)
  4613. return DAG.getConstantFP(1.0, DL, LHS.getValueType());
  4614. const Function &F = DAG.getMachineFunction().getFunction();
  4615. if (!F.hasOptSize() ||
  4616. // If optimizing for size, don't insert too many multiplies.
  4617. // This inserts up to 5 multiplies.
  4618. countPopulation(Val) + Log2_32(Val) < 7) {
  4619. // We use the simple binary decomposition method to generate the multiply
  4620. // sequence. There are more optimal ways to do this (for example,
  4621. // powi(x,15) generates one more multiply than it should), but this has
  4622. // the benefit of being both really simple and much better than a libcall.
  4623. SDValue Res; // Logically starts equal to 1.0
  4624. SDValue CurSquare = LHS;
  4625. // TODO: Intrinsics should have fast-math-flags that propagate to these
  4626. // nodes.
  4627. while (Val) {
  4628. if (Val & 1) {
  4629. if (Res.getNode())
  4630. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  4631. else
  4632. Res = CurSquare; // 1.0*CurSquare.
  4633. }
  4634. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  4635. CurSquare, CurSquare);
  4636. Val >>= 1;
  4637. }
  4638. // If the original was negative, invert the result, producing 1/(x*x*x).
  4639. if (RHSC->getSExtValue() < 0)
  4640. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  4641. DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
  4642. return Res;
  4643. }
  4644. }
  4645. // Otherwise, expand to a libcall.
  4646. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  4647. }
  4648. // getUnderlyingArgRegs - Find underlying registers used for a truncated,
  4649. // bitcasted, or split argument. Returns a list of <Register, size in bits>
  4650. static void
  4651. getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
  4652. const SDValue &N) {
  4653. switch (N.getOpcode()) {
  4654. case ISD::CopyFromReg: {
  4655. SDValue Op = N.getOperand(1);
  4656. Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
  4657. Op.getValueType().getSizeInBits());
  4658. return;
  4659. }
  4660. case ISD::BITCAST:
  4661. case ISD::AssertZext:
  4662. case ISD::AssertSext:
  4663. case ISD::TRUNCATE:
  4664. getUnderlyingArgRegs(Regs, N.getOperand(0));
  4665. return;
  4666. case ISD::BUILD_PAIR:
  4667. case ISD::BUILD_VECTOR:
  4668. case ISD::CONCAT_VECTORS:
  4669. for (SDValue Op : N->op_values())
  4670. getUnderlyingArgRegs(Regs, Op);
  4671. return;
  4672. default:
  4673. return;
  4674. }
  4675. }
  4676. /// If the DbgValueInst is a dbg_value of a function argument, create the
  4677. /// corresponding DBG_VALUE machine instruction for it now. At the end of
  4678. /// instruction selection, they will be inserted to the entry BB.
  4679. bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
  4680. const Value *V, DILocalVariable *Variable, DIExpression *Expr,
  4681. DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
  4682. const Argument *Arg = dyn_cast<Argument>(V);
  4683. if (!Arg)
  4684. return false;
  4685. if (!IsDbgDeclare) {
  4686. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4687. // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
  4688. // the entry block.
  4689. bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
  4690. if (!IsInEntryBlock)
  4691. return false;
  4692. // ArgDbgValues are hoisted to the beginning of the entry block. So we
  4693. // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
  4694. // variable that also is a param.
  4695. //
  4696. // Although, if we are at the top of the entry block already, we can still
  4697. // emit using ArgDbgValue. This might catch some situations when the
  4698. // dbg.value refers to an argument that isn't used in the entry block, so
  4699. // any CopyToReg node would be optimized out and the only way to express
  4700. // this DBG_VALUE is by using the physical reg (or FI) as done in this
  4701. // method. ArgDbgValues are hoisted to the beginning of the entry block. So
  4702. // we should only emit as ArgDbgValue if the Variable is an argument to the
  4703. // current function, and the dbg.value intrinsic is found in the entry
  4704. // block.
  4705. bool VariableIsFunctionInputArg = Variable->isParameter() &&
  4706. !DL->getInlinedAt();
  4707. bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
  4708. if (!IsInPrologue && !VariableIsFunctionInputArg)
  4709. return false;
  4710. // Here we assume that a function argument on IR level only can be used to
  4711. // describe one input parameter on source level. If we for example have
  4712. // source code like this
  4713. //
  4714. // struct A { long x, y; };
  4715. // void foo(struct A a, long b) {
  4716. // ...
  4717. // b = a.x;
  4718. // ...
  4719. // }
  4720. //
  4721. // and IR like this
  4722. //
  4723. // define void @foo(i32 %a1, i32 %a2, i32 %b) {
  4724. // entry:
  4725. // call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
  4726. // call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
  4727. // call void @llvm.dbg.value(metadata i32 %b, "b",
  4728. // ...
  4729. // call void @llvm.dbg.value(metadata i32 %a1, "b"
  4730. // ...
  4731. //
  4732. // then the last dbg.value is describing a parameter "b" using a value that
  4733. // is an argument. But since we already has used %a1 to describe a parameter
  4734. // we should not handle that last dbg.value here (that would result in an
  4735. // incorrect hoisting of the DBG_VALUE to the function entry).
  4736. // Notice that we allow one dbg.value per IR level argument, to accomodate
  4737. // for the situation with fragments above.
  4738. if (VariableIsFunctionInputArg) {
  4739. unsigned ArgNo = Arg->getArgNo();
  4740. if (ArgNo >= FuncInfo.DescribedArgs.size())
  4741. FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
  4742. else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
  4743. return false;
  4744. FuncInfo.DescribedArgs.set(ArgNo);
  4745. }
  4746. }
  4747. MachineFunction &MF = DAG.getMachineFunction();
  4748. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  4749. bool IsIndirect = false;
  4750. Optional<MachineOperand> Op;
  4751. // Some arguments' frame index is recorded during argument lowering.
  4752. int FI = FuncInfo.getArgumentFrameIndex(Arg);
  4753. if (FI != std::numeric_limits<int>::max())
  4754. Op = MachineOperand::CreateFI(FI);
  4755. SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
  4756. if (!Op && N.getNode()) {
  4757. getUnderlyingArgRegs(ArgRegsAndSizes, N);
  4758. Register Reg;
  4759. if (ArgRegsAndSizes.size() == 1)
  4760. Reg = ArgRegsAndSizes.front().first;
  4761. if (Reg && Reg.isVirtual()) {
  4762. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4763. Register PR = RegInfo.getLiveInPhysReg(Reg);
  4764. if (PR)
  4765. Reg = PR;
  4766. }
  4767. if (Reg) {
  4768. Op = MachineOperand::CreateReg(Reg, false);
  4769. IsIndirect = IsDbgDeclare;
  4770. }
  4771. }
  4772. if (!Op && N.getNode()) {
  4773. // Check if frame index is available.
  4774. SDValue LCandidate = peekThroughBitcasts(N);
  4775. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
  4776. if (FrameIndexSDNode *FINode =
  4777. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  4778. Op = MachineOperand::CreateFI(FINode->getIndex());
  4779. }
  4780. if (!Op) {
  4781. // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
  4782. auto splitMultiRegDbgValue
  4783. = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
  4784. unsigned Offset = 0;
  4785. for (auto RegAndSize : SplitRegs) {
  4786. auto FragmentExpr = DIExpression::createFragmentExpression(
  4787. Expr, Offset, RegAndSize.second);
  4788. if (!FragmentExpr)
  4789. continue;
  4790. FuncInfo.ArgDbgValues.push_back(
  4791. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
  4792. RegAndSize.first, Variable, *FragmentExpr));
  4793. Offset += RegAndSize.second;
  4794. }
  4795. };
  4796. // Check if ValueMap has reg number.
  4797. DenseMap<const Value *, unsigned>::const_iterator
  4798. VMI = FuncInfo.ValueMap.find(V);
  4799. if (VMI != FuncInfo.ValueMap.end()) {
  4800. const auto &TLI = DAG.getTargetLoweringInfo();
  4801. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
  4802. V->getType(), getABIRegCopyCC(V));
  4803. if (RFV.occupiesMultipleRegs()) {
  4804. splitMultiRegDbgValue(RFV.getRegsAndSizes());
  4805. return true;
  4806. }
  4807. Op = MachineOperand::CreateReg(VMI->second, false);
  4808. IsIndirect = IsDbgDeclare;
  4809. } else if (ArgRegsAndSizes.size() > 1) {
  4810. // This was split due to the calling convention, and no virtual register
  4811. // mapping exists for the value.
  4812. splitMultiRegDbgValue(ArgRegsAndSizes);
  4813. return true;
  4814. }
  4815. }
  4816. if (!Op)
  4817. return false;
  4818. assert(Variable->isValidLocationForIntrinsic(DL) &&
  4819. "Expected inlined-at fields to agree");
  4820. IsIndirect = (Op->isReg()) ? IsIndirect : true;
  4821. FuncInfo.ArgDbgValues.push_back(
  4822. BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
  4823. *Op, Variable, Expr));
  4824. return true;
  4825. }
  4826. /// Return the appropriate SDDbgValue based on N.
  4827. SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
  4828. DILocalVariable *Variable,
  4829. DIExpression *Expr,
  4830. const DebugLoc &dl,
  4831. unsigned DbgSDNodeOrder) {
  4832. if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
  4833. // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
  4834. // stack slot locations.
  4835. //
  4836. // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
  4837. // debug values here after optimization:
  4838. //
  4839. // dbg.value(i32* %px, !"int *px", !DIExpression()), and
  4840. // dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
  4841. //
  4842. // Both describe the direct values of their associated variables.
  4843. return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
  4844. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4845. }
  4846. return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
  4847. /*IsIndirect*/ false, dl, DbgSDNodeOrder);
  4848. }
  4849. // VisualStudio defines setjmp as _setjmp
  4850. #if defined(_MSC_VER) && defined(setjmp) && \
  4851. !defined(setjmp_undefined_for_msvc)
  4852. # pragma push_macro("setjmp")
  4853. # undef setjmp
  4854. # define setjmp_undefined_for_msvc
  4855. #endif
  4856. static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
  4857. switch (Intrinsic) {
  4858. case Intrinsic::smul_fix:
  4859. return ISD::SMULFIX;
  4860. case Intrinsic::umul_fix:
  4861. return ISD::UMULFIX;
  4862. default:
  4863. llvm_unreachable("Unhandled fixed point intrinsic");
  4864. }
  4865. }
  4866. void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
  4867. const char *FunctionName) {
  4868. assert(FunctionName && "FunctionName must not be nullptr");
  4869. SDValue Callee = DAG.getExternalSymbol(
  4870. FunctionName,
  4871. DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  4872. LowerCallTo(&I, Callee, I.isTailCall());
  4873. }
  4874. /// Lower the call to the specified intrinsic function.
  4875. void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
  4876. unsigned Intrinsic) {
  4877. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  4878. SDLoc sdl = getCurSDLoc();
  4879. DebugLoc dl = getCurDebugLoc();
  4880. SDValue Res;
  4881. switch (Intrinsic) {
  4882. default:
  4883. // By default, turn this into a target intrinsic node.
  4884. visitTargetIntrinsic(I, Intrinsic);
  4885. return;
  4886. case Intrinsic::vastart: visitVAStart(I); return;
  4887. case Intrinsic::vaend: visitVAEnd(I); return;
  4888. case Intrinsic::vacopy: visitVACopy(I); return;
  4889. case Intrinsic::returnaddress:
  4890. setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
  4891. TLI.getPointerTy(DAG.getDataLayout()),
  4892. getValue(I.getArgOperand(0))));
  4893. return;
  4894. case Intrinsic::addressofreturnaddress:
  4895. setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
  4896. TLI.getPointerTy(DAG.getDataLayout())));
  4897. return;
  4898. case Intrinsic::sponentry:
  4899. setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
  4900. TLI.getFrameIndexTy(DAG.getDataLayout())));
  4901. return;
  4902. case Intrinsic::frameaddress:
  4903. setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
  4904. TLI.getFrameIndexTy(DAG.getDataLayout()),
  4905. getValue(I.getArgOperand(0))));
  4906. return;
  4907. case Intrinsic::read_register: {
  4908. Value *Reg = I.getArgOperand(0);
  4909. SDValue Chain = getRoot();
  4910. SDValue RegName =
  4911. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4912. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  4913. Res = DAG.getNode(ISD::READ_REGISTER, sdl,
  4914. DAG.getVTList(VT, MVT::Other), Chain, RegName);
  4915. setValue(&I, Res);
  4916. DAG.setRoot(Res.getValue(1));
  4917. return;
  4918. }
  4919. case Intrinsic::write_register: {
  4920. Value *Reg = I.getArgOperand(0);
  4921. Value *RegValue = I.getArgOperand(1);
  4922. SDValue Chain = getRoot();
  4923. SDValue RegName =
  4924. DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
  4925. DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
  4926. RegName, getValue(RegValue)));
  4927. return;
  4928. }
  4929. case Intrinsic::setjmp:
  4930. lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
  4931. return;
  4932. case Intrinsic::longjmp:
  4933. lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
  4934. return;
  4935. case Intrinsic::memcpy: {
  4936. const auto &MCI = cast<MemCpyInst>(I);
  4937. SDValue Op1 = getValue(I.getArgOperand(0));
  4938. SDValue Op2 = getValue(I.getArgOperand(1));
  4939. SDValue Op3 = getValue(I.getArgOperand(2));
  4940. // @llvm.memcpy defines 0 and 1 to both mean no alignment.
  4941. unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
  4942. unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
  4943. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4944. bool isVol = MCI.isVolatile();
  4945. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4946. // FIXME: Support passing different dest/src alignments to the memcpy DAG
  4947. // node.
  4948. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4949. false, isTC,
  4950. MachinePointerInfo(I.getArgOperand(0)),
  4951. MachinePointerInfo(I.getArgOperand(1)));
  4952. updateDAGForMaybeTailCall(MC);
  4953. return;
  4954. }
  4955. case Intrinsic::memset: {
  4956. const auto &MSI = cast<MemSetInst>(I);
  4957. SDValue Op1 = getValue(I.getArgOperand(0));
  4958. SDValue Op2 = getValue(I.getArgOperand(1));
  4959. SDValue Op3 = getValue(I.getArgOperand(2));
  4960. // @llvm.memset defines 0 and 1 to both mean no alignment.
  4961. unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
  4962. bool isVol = MSI.isVolatile();
  4963. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4964. SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4965. isTC, MachinePointerInfo(I.getArgOperand(0)));
  4966. updateDAGForMaybeTailCall(MS);
  4967. return;
  4968. }
  4969. case Intrinsic::memmove: {
  4970. const auto &MMI = cast<MemMoveInst>(I);
  4971. SDValue Op1 = getValue(I.getArgOperand(0));
  4972. SDValue Op2 = getValue(I.getArgOperand(1));
  4973. SDValue Op3 = getValue(I.getArgOperand(2));
  4974. // @llvm.memmove defines 0 and 1 to both mean no alignment.
  4975. unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
  4976. unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
  4977. unsigned Align = MinAlign(DstAlign, SrcAlign);
  4978. bool isVol = MMI.isVolatile();
  4979. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4980. // FIXME: Support passing different dest/src alignments to the memmove DAG
  4981. // node.
  4982. SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
  4983. isTC, MachinePointerInfo(I.getArgOperand(0)),
  4984. MachinePointerInfo(I.getArgOperand(1)));
  4985. updateDAGForMaybeTailCall(MM);
  4986. return;
  4987. }
  4988. case Intrinsic::memcpy_element_unordered_atomic: {
  4989. const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
  4990. SDValue Dst = getValue(MI.getRawDest());
  4991. SDValue Src = getValue(MI.getRawSource());
  4992. SDValue Length = getValue(MI.getLength());
  4993. unsigned DstAlign = MI.getDestAlignment();
  4994. unsigned SrcAlign = MI.getSourceAlignment();
  4995. Type *LengthTy = MI.getLength()->getType();
  4996. unsigned ElemSz = MI.getElementSizeInBytes();
  4997. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  4998. SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
  4999. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5000. MachinePointerInfo(MI.getRawDest()),
  5001. MachinePointerInfo(MI.getRawSource()));
  5002. updateDAGForMaybeTailCall(MC);
  5003. return;
  5004. }
  5005. case Intrinsic::memmove_element_unordered_atomic: {
  5006. auto &MI = cast<AtomicMemMoveInst>(I);
  5007. SDValue Dst = getValue(MI.getRawDest());
  5008. SDValue Src = getValue(MI.getRawSource());
  5009. SDValue Length = getValue(MI.getLength());
  5010. unsigned DstAlign = MI.getDestAlignment();
  5011. unsigned SrcAlign = MI.getSourceAlignment();
  5012. Type *LengthTy = MI.getLength()->getType();
  5013. unsigned ElemSz = MI.getElementSizeInBytes();
  5014. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5015. SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
  5016. SrcAlign, Length, LengthTy, ElemSz, isTC,
  5017. MachinePointerInfo(MI.getRawDest()),
  5018. MachinePointerInfo(MI.getRawSource()));
  5019. updateDAGForMaybeTailCall(MC);
  5020. return;
  5021. }
  5022. case Intrinsic::memset_element_unordered_atomic: {
  5023. auto &MI = cast<AtomicMemSetInst>(I);
  5024. SDValue Dst = getValue(MI.getRawDest());
  5025. SDValue Val = getValue(MI.getValue());
  5026. SDValue Length = getValue(MI.getLength());
  5027. unsigned DstAlign = MI.getDestAlignment();
  5028. Type *LengthTy = MI.getLength()->getType();
  5029. unsigned ElemSz = MI.getElementSizeInBytes();
  5030. bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
  5031. SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
  5032. LengthTy, ElemSz, isTC,
  5033. MachinePointerInfo(MI.getRawDest()));
  5034. updateDAGForMaybeTailCall(MC);
  5035. return;
  5036. }
  5037. case Intrinsic::dbg_addr:
  5038. case Intrinsic::dbg_declare: {
  5039. const auto &DI = cast<DbgVariableIntrinsic>(I);
  5040. DILocalVariable *Variable = DI.getVariable();
  5041. DIExpression *Expression = DI.getExpression();
  5042. dropDanglingDebugInfo(Variable, Expression);
  5043. assert(Variable && "Missing variable");
  5044. // Check if address has undef value.
  5045. const Value *Address = DI.getVariableLocation();
  5046. if (!Address || isa<UndefValue>(Address) ||
  5047. (Address->use_empty() && !isa<Argument>(Address))) {
  5048. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5049. return;
  5050. }
  5051. bool isParameter = Variable->isParameter() || isa<Argument>(Address);
  5052. // Check if this variable can be described by a frame index, typically
  5053. // either as a static alloca or a byval parameter.
  5054. int FI = std::numeric_limits<int>::max();
  5055. if (const auto *AI =
  5056. dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
  5057. if (AI->isStaticAlloca()) {
  5058. auto I = FuncInfo.StaticAllocaMap.find(AI);
  5059. if (I != FuncInfo.StaticAllocaMap.end())
  5060. FI = I->second;
  5061. }
  5062. } else if (const auto *Arg = dyn_cast<Argument>(
  5063. Address->stripInBoundsConstantOffsets())) {
  5064. FI = FuncInfo.getArgumentFrameIndex(Arg);
  5065. }
  5066. // llvm.dbg.addr is control dependent and always generates indirect
  5067. // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
  5068. // the MachineFunction variable table.
  5069. if (FI != std::numeric_limits<int>::max()) {
  5070. if (Intrinsic == Intrinsic::dbg_addr) {
  5071. SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
  5072. Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
  5073. DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
  5074. }
  5075. return;
  5076. }
  5077. SDValue &N = NodeMap[Address];
  5078. if (!N.getNode() && isa<Argument>(Address))
  5079. // Check unused arguments map.
  5080. N = UnusedArgNodeMap[Address];
  5081. SDDbgValue *SDV;
  5082. if (N.getNode()) {
  5083. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  5084. Address = BCI->getOperand(0);
  5085. // Parameters are handled specially.
  5086. auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  5087. if (isParameter && FINode) {
  5088. // Byval parameter. We have a frame index at this point.
  5089. SDV =
  5090. DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
  5091. /*IsIndirect*/ true, dl, SDNodeOrder);
  5092. } else if (isa<Argument>(Address)) {
  5093. // Address is an argument, so try to emit its dbg value using
  5094. // virtual register info from the FuncInfo.ValueMap.
  5095. EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
  5096. return;
  5097. } else {
  5098. SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
  5099. true, dl, SDNodeOrder);
  5100. }
  5101. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  5102. } else {
  5103. // If Address is an argument then try to emit its dbg value using
  5104. // virtual register info from the FuncInfo.ValueMap.
  5105. if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
  5106. N)) {
  5107. LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
  5108. }
  5109. }
  5110. return;
  5111. }
  5112. case Intrinsic::dbg_label: {
  5113. const DbgLabelInst &DI = cast<DbgLabelInst>(I);
  5114. DILabel *Label = DI.getLabel();
  5115. assert(Label && "Missing label");
  5116. SDDbgLabel *SDV;
  5117. SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
  5118. DAG.AddDbgLabel(SDV);
  5119. return;
  5120. }
  5121. case Intrinsic::dbg_value: {
  5122. const DbgValueInst &DI = cast<DbgValueInst>(I);
  5123. assert(DI.getVariable() && "Missing variable");
  5124. DILocalVariable *Variable = DI.getVariable();
  5125. DIExpression *Expression = DI.getExpression();
  5126. dropDanglingDebugInfo(Variable, Expression);
  5127. const Value *V = DI.getValue();
  5128. if (!V)
  5129. return;
  5130. if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
  5131. SDNodeOrder))
  5132. return;
  5133. // TODO: Dangling debug info will eventually either be resolved or produce
  5134. // an Undef DBG_VALUE. However in the resolution case, a gap may appear
  5135. // between the original dbg.value location and its resolved DBG_VALUE, which
  5136. // we should ideally fill with an extra Undef DBG_VALUE.
  5137. DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
  5138. return;
  5139. }
  5140. case Intrinsic::eh_typeid_for: {
  5141. // Find the type id for the given typeinfo.
  5142. GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
  5143. unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
  5144. Res = DAG.getConstant(TypeID, sdl, MVT::i32);
  5145. setValue(&I, Res);
  5146. return;
  5147. }
  5148. case Intrinsic::eh_return_i32:
  5149. case Intrinsic::eh_return_i64:
  5150. DAG.getMachineFunction().setCallsEHReturn(true);
  5151. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
  5152. MVT::Other,
  5153. getControlRoot(),
  5154. getValue(I.getArgOperand(0)),
  5155. getValue(I.getArgOperand(1))));
  5156. return;
  5157. case Intrinsic::eh_unwind_init:
  5158. DAG.getMachineFunction().setCallsUnwindInit(true);
  5159. return;
  5160. case Intrinsic::eh_dwarf_cfa:
  5161. setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
  5162. TLI.getPointerTy(DAG.getDataLayout()),
  5163. getValue(I.getArgOperand(0))));
  5164. return;
  5165. case Intrinsic::eh_sjlj_callsite: {
  5166. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  5167. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  5168. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  5169. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  5170. MMI.setCurrentCallSite(CI->getZExtValue());
  5171. return;
  5172. }
  5173. case Intrinsic::eh_sjlj_functioncontext: {
  5174. // Get and store the index of the function context.
  5175. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5176. AllocaInst *FnCtx =
  5177. cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
  5178. int FI = FuncInfo.StaticAllocaMap[FnCtx];
  5179. MFI.setFunctionContextIndex(FI);
  5180. return;
  5181. }
  5182. case Intrinsic::eh_sjlj_setjmp: {
  5183. SDValue Ops[2];
  5184. Ops[0] = getRoot();
  5185. Ops[1] = getValue(I.getArgOperand(0));
  5186. SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
  5187. DAG.getVTList(MVT::i32, MVT::Other), Ops);
  5188. setValue(&I, Op.getValue(0));
  5189. DAG.setRoot(Op.getValue(1));
  5190. return;
  5191. }
  5192. case Intrinsic::eh_sjlj_longjmp:
  5193. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
  5194. getRoot(), getValue(I.getArgOperand(0))));
  5195. return;
  5196. case Intrinsic::eh_sjlj_setup_dispatch:
  5197. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
  5198. getRoot()));
  5199. return;
  5200. case Intrinsic::masked_gather:
  5201. visitMaskedGather(I);
  5202. return;
  5203. case Intrinsic::masked_load:
  5204. visitMaskedLoad(I);
  5205. return;
  5206. case Intrinsic::masked_scatter:
  5207. visitMaskedScatter(I);
  5208. return;
  5209. case Intrinsic::masked_store:
  5210. visitMaskedStore(I);
  5211. return;
  5212. case Intrinsic::masked_expandload:
  5213. visitMaskedLoad(I, true /* IsExpanding */);
  5214. return;
  5215. case Intrinsic::masked_compressstore:
  5216. visitMaskedStore(I, true /* IsCompressing */);
  5217. return;
  5218. case Intrinsic::x86_mmx_pslli_w:
  5219. case Intrinsic::x86_mmx_pslli_d:
  5220. case Intrinsic::x86_mmx_pslli_q:
  5221. case Intrinsic::x86_mmx_psrli_w:
  5222. case Intrinsic::x86_mmx_psrli_d:
  5223. case Intrinsic::x86_mmx_psrli_q:
  5224. case Intrinsic::x86_mmx_psrai_w:
  5225. case Intrinsic::x86_mmx_psrai_d: {
  5226. SDValue ShAmt = getValue(I.getArgOperand(1));
  5227. if (isa<ConstantSDNode>(ShAmt)) {
  5228. visitTargetIntrinsic(I, Intrinsic);
  5229. return;
  5230. }
  5231. unsigned NewIntrinsic = 0;
  5232. EVT ShAmtVT = MVT::v2i32;
  5233. switch (Intrinsic) {
  5234. case Intrinsic::x86_mmx_pslli_w:
  5235. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  5236. break;
  5237. case Intrinsic::x86_mmx_pslli_d:
  5238. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  5239. break;
  5240. case Intrinsic::x86_mmx_pslli_q:
  5241. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  5242. break;
  5243. case Intrinsic::x86_mmx_psrli_w:
  5244. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  5245. break;
  5246. case Intrinsic::x86_mmx_psrli_d:
  5247. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  5248. break;
  5249. case Intrinsic::x86_mmx_psrli_q:
  5250. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  5251. break;
  5252. case Intrinsic::x86_mmx_psrai_w:
  5253. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  5254. break;
  5255. case Intrinsic::x86_mmx_psrai_d:
  5256. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  5257. break;
  5258. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5259. }
  5260. // The vector shift intrinsics with scalars uses 32b shift amounts but
  5261. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  5262. // to be zero.
  5263. // We must do this early because v2i32 is not a legal type.
  5264. SDValue ShOps[2];
  5265. ShOps[0] = ShAmt;
  5266. ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
  5267. ShAmt = DAG.getBuildVector(ShAmtVT, sdl, ShOps);
  5268. EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5269. ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
  5270. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
  5271. DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
  5272. getValue(I.getArgOperand(0)), ShAmt);
  5273. setValue(&I, Res);
  5274. return;
  5275. }
  5276. case Intrinsic::powi:
  5277. setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
  5278. getValue(I.getArgOperand(1)), DAG));
  5279. return;
  5280. case Intrinsic::log:
  5281. setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5282. return;
  5283. case Intrinsic::log2:
  5284. setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5285. return;
  5286. case Intrinsic::log10:
  5287. setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5288. return;
  5289. case Intrinsic::exp:
  5290. setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5291. return;
  5292. case Intrinsic::exp2:
  5293. setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
  5294. return;
  5295. case Intrinsic::pow:
  5296. setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
  5297. getValue(I.getArgOperand(1)), DAG, TLI));
  5298. return;
  5299. case Intrinsic::sqrt:
  5300. case Intrinsic::fabs:
  5301. case Intrinsic::sin:
  5302. case Intrinsic::cos:
  5303. case Intrinsic::floor:
  5304. case Intrinsic::ceil:
  5305. case Intrinsic::trunc:
  5306. case Intrinsic::rint:
  5307. case Intrinsic::nearbyint:
  5308. case Intrinsic::round:
  5309. case Intrinsic::canonicalize: {
  5310. unsigned Opcode;
  5311. switch (Intrinsic) {
  5312. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5313. case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
  5314. case Intrinsic::fabs: Opcode = ISD::FABS; break;
  5315. case Intrinsic::sin: Opcode = ISD::FSIN; break;
  5316. case Intrinsic::cos: Opcode = ISD::FCOS; break;
  5317. case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
  5318. case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
  5319. case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
  5320. case Intrinsic::rint: Opcode = ISD::FRINT; break;
  5321. case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
  5322. case Intrinsic::round: Opcode = ISD::FROUND; break;
  5323. case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
  5324. }
  5325. setValue(&I, DAG.getNode(Opcode, sdl,
  5326. getValue(I.getArgOperand(0)).getValueType(),
  5327. getValue(I.getArgOperand(0))));
  5328. return;
  5329. }
  5330. case Intrinsic::lround:
  5331. case Intrinsic::llround:
  5332. case Intrinsic::lrint:
  5333. case Intrinsic::llrint: {
  5334. unsigned Opcode;
  5335. switch (Intrinsic) {
  5336. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5337. case Intrinsic::lround: Opcode = ISD::LROUND; break;
  5338. case Intrinsic::llround: Opcode = ISD::LLROUND; break;
  5339. case Intrinsic::lrint: Opcode = ISD::LRINT; break;
  5340. case Intrinsic::llrint: Opcode = ISD::LLRINT; break;
  5341. }
  5342. EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5343. setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
  5344. getValue(I.getArgOperand(0))));
  5345. return;
  5346. }
  5347. case Intrinsic::minnum:
  5348. setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
  5349. getValue(I.getArgOperand(0)).getValueType(),
  5350. getValue(I.getArgOperand(0)),
  5351. getValue(I.getArgOperand(1))));
  5352. return;
  5353. case Intrinsic::maxnum:
  5354. setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
  5355. getValue(I.getArgOperand(0)).getValueType(),
  5356. getValue(I.getArgOperand(0)),
  5357. getValue(I.getArgOperand(1))));
  5358. return;
  5359. case Intrinsic::minimum:
  5360. setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
  5361. getValue(I.getArgOperand(0)).getValueType(),
  5362. getValue(I.getArgOperand(0)),
  5363. getValue(I.getArgOperand(1))));
  5364. return;
  5365. case Intrinsic::maximum:
  5366. setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
  5367. getValue(I.getArgOperand(0)).getValueType(),
  5368. getValue(I.getArgOperand(0)),
  5369. getValue(I.getArgOperand(1))));
  5370. return;
  5371. case Intrinsic::copysign:
  5372. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
  5373. getValue(I.getArgOperand(0)).getValueType(),
  5374. getValue(I.getArgOperand(0)),
  5375. getValue(I.getArgOperand(1))));
  5376. return;
  5377. case Intrinsic::fma:
  5378. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5379. getValue(I.getArgOperand(0)).getValueType(),
  5380. getValue(I.getArgOperand(0)),
  5381. getValue(I.getArgOperand(1)),
  5382. getValue(I.getArgOperand(2))));
  5383. return;
  5384. case Intrinsic::experimental_constrained_fadd:
  5385. case Intrinsic::experimental_constrained_fsub:
  5386. case Intrinsic::experimental_constrained_fmul:
  5387. case Intrinsic::experimental_constrained_fdiv:
  5388. case Intrinsic::experimental_constrained_frem:
  5389. case Intrinsic::experimental_constrained_fma:
  5390. case Intrinsic::experimental_constrained_fptosi:
  5391. case Intrinsic::experimental_constrained_fptoui:
  5392. case Intrinsic::experimental_constrained_fptrunc:
  5393. case Intrinsic::experimental_constrained_fpext:
  5394. case Intrinsic::experimental_constrained_sqrt:
  5395. case Intrinsic::experimental_constrained_pow:
  5396. case Intrinsic::experimental_constrained_powi:
  5397. case Intrinsic::experimental_constrained_sin:
  5398. case Intrinsic::experimental_constrained_cos:
  5399. case Intrinsic::experimental_constrained_exp:
  5400. case Intrinsic::experimental_constrained_exp2:
  5401. case Intrinsic::experimental_constrained_log:
  5402. case Intrinsic::experimental_constrained_log10:
  5403. case Intrinsic::experimental_constrained_log2:
  5404. case Intrinsic::experimental_constrained_rint:
  5405. case Intrinsic::experimental_constrained_nearbyint:
  5406. case Intrinsic::experimental_constrained_maxnum:
  5407. case Intrinsic::experimental_constrained_minnum:
  5408. case Intrinsic::experimental_constrained_ceil:
  5409. case Intrinsic::experimental_constrained_floor:
  5410. case Intrinsic::experimental_constrained_round:
  5411. case Intrinsic::experimental_constrained_trunc:
  5412. visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
  5413. return;
  5414. case Intrinsic::fmuladd: {
  5415. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5416. if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
  5417. TLI.isFMAFasterThanFMulAndFAdd(VT)) {
  5418. setValue(&I, DAG.getNode(ISD::FMA, sdl,
  5419. getValue(I.getArgOperand(0)).getValueType(),
  5420. getValue(I.getArgOperand(0)),
  5421. getValue(I.getArgOperand(1)),
  5422. getValue(I.getArgOperand(2))));
  5423. } else {
  5424. // TODO: Intrinsic calls should have fast-math-flags.
  5425. SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
  5426. getValue(I.getArgOperand(0)).getValueType(),
  5427. getValue(I.getArgOperand(0)),
  5428. getValue(I.getArgOperand(1)));
  5429. SDValue Add = DAG.getNode(ISD::FADD, sdl,
  5430. getValue(I.getArgOperand(0)).getValueType(),
  5431. Mul,
  5432. getValue(I.getArgOperand(2)));
  5433. setValue(&I, Add);
  5434. }
  5435. return;
  5436. }
  5437. case Intrinsic::convert_to_fp16:
  5438. setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
  5439. DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
  5440. getValue(I.getArgOperand(0)),
  5441. DAG.getTargetConstant(0, sdl,
  5442. MVT::i32))));
  5443. return;
  5444. case Intrinsic::convert_from_fp16:
  5445. setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
  5446. TLI.getValueType(DAG.getDataLayout(), I.getType()),
  5447. DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
  5448. getValue(I.getArgOperand(0)))));
  5449. return;
  5450. case Intrinsic::pcmarker: {
  5451. SDValue Tmp = getValue(I.getArgOperand(0));
  5452. DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
  5453. return;
  5454. }
  5455. case Intrinsic::readcyclecounter: {
  5456. SDValue Op = getRoot();
  5457. Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
  5458. DAG.getVTList(MVT::i64, MVT::Other), Op);
  5459. setValue(&I, Res);
  5460. DAG.setRoot(Res.getValue(1));
  5461. return;
  5462. }
  5463. case Intrinsic::bitreverse:
  5464. setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
  5465. getValue(I.getArgOperand(0)).getValueType(),
  5466. getValue(I.getArgOperand(0))));
  5467. return;
  5468. case Intrinsic::bswap:
  5469. setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
  5470. getValue(I.getArgOperand(0)).getValueType(),
  5471. getValue(I.getArgOperand(0))));
  5472. return;
  5473. case Intrinsic::cttz: {
  5474. SDValue Arg = getValue(I.getArgOperand(0));
  5475. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5476. EVT Ty = Arg.getValueType();
  5477. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
  5478. sdl, Ty, Arg));
  5479. return;
  5480. }
  5481. case Intrinsic::ctlz: {
  5482. SDValue Arg = getValue(I.getArgOperand(0));
  5483. ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
  5484. EVT Ty = Arg.getValueType();
  5485. setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
  5486. sdl, Ty, Arg));
  5487. return;
  5488. }
  5489. case Intrinsic::ctpop: {
  5490. SDValue Arg = getValue(I.getArgOperand(0));
  5491. EVT Ty = Arg.getValueType();
  5492. setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
  5493. return;
  5494. }
  5495. case Intrinsic::fshl:
  5496. case Intrinsic::fshr: {
  5497. bool IsFSHL = Intrinsic == Intrinsic::fshl;
  5498. SDValue X = getValue(I.getArgOperand(0));
  5499. SDValue Y = getValue(I.getArgOperand(1));
  5500. SDValue Z = getValue(I.getArgOperand(2));
  5501. EVT VT = X.getValueType();
  5502. SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
  5503. SDValue Zero = DAG.getConstant(0, sdl, VT);
  5504. SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
  5505. auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
  5506. if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
  5507. setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
  5508. return;
  5509. }
  5510. // When X == Y, this is rotate. If the data type has a power-of-2 size, we
  5511. // avoid the select that is necessary in the general case to filter out
  5512. // the 0-shift possibility that leads to UB.
  5513. if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
  5514. auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
  5515. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5516. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
  5517. return;
  5518. }
  5519. // Some targets only rotate one way. Try the opposite direction.
  5520. RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
  5521. if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
  5522. // Negate the shift amount because it is safe to ignore the high bits.
  5523. SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5524. setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
  5525. return;
  5526. }
  5527. // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
  5528. // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
  5529. SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
  5530. SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
  5531. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
  5532. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
  5533. setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
  5534. return;
  5535. }
  5536. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  5537. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  5538. SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
  5539. SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
  5540. SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
  5541. SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
  5542. // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
  5543. // and that is undefined. We must compare and select to avoid UB.
  5544. EVT CCVT = MVT::i1;
  5545. if (VT.isVector())
  5546. CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
  5547. // For fshl, 0-shift returns the 1st arg (X).
  5548. // For fshr, 0-shift returns the 2nd arg (Y).
  5549. SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
  5550. setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
  5551. return;
  5552. }
  5553. case Intrinsic::sadd_sat: {
  5554. SDValue Op1 = getValue(I.getArgOperand(0));
  5555. SDValue Op2 = getValue(I.getArgOperand(1));
  5556. setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5557. return;
  5558. }
  5559. case Intrinsic::uadd_sat: {
  5560. SDValue Op1 = getValue(I.getArgOperand(0));
  5561. SDValue Op2 = getValue(I.getArgOperand(1));
  5562. setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
  5563. return;
  5564. }
  5565. case Intrinsic::ssub_sat: {
  5566. SDValue Op1 = getValue(I.getArgOperand(0));
  5567. SDValue Op2 = getValue(I.getArgOperand(1));
  5568. setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5569. return;
  5570. }
  5571. case Intrinsic::usub_sat: {
  5572. SDValue Op1 = getValue(I.getArgOperand(0));
  5573. SDValue Op2 = getValue(I.getArgOperand(1));
  5574. setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
  5575. return;
  5576. }
  5577. case Intrinsic::smul_fix:
  5578. case Intrinsic::umul_fix: {
  5579. SDValue Op1 = getValue(I.getArgOperand(0));
  5580. SDValue Op2 = getValue(I.getArgOperand(1));
  5581. SDValue Op3 = getValue(I.getArgOperand(2));
  5582. setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
  5583. Op1.getValueType(), Op1, Op2, Op3));
  5584. return;
  5585. }
  5586. case Intrinsic::smul_fix_sat: {
  5587. SDValue Op1 = getValue(I.getArgOperand(0));
  5588. SDValue Op2 = getValue(I.getArgOperand(1));
  5589. SDValue Op3 = getValue(I.getArgOperand(2));
  5590. setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5591. Op3));
  5592. return;
  5593. }
  5594. case Intrinsic::umul_fix_sat: {
  5595. SDValue Op1 = getValue(I.getArgOperand(0));
  5596. SDValue Op2 = getValue(I.getArgOperand(1));
  5597. SDValue Op3 = getValue(I.getArgOperand(2));
  5598. setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
  5599. Op3));
  5600. return;
  5601. }
  5602. case Intrinsic::stacksave: {
  5603. SDValue Op = getRoot();
  5604. Res = DAG.getNode(
  5605. ISD::STACKSAVE, sdl,
  5606. DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
  5607. setValue(&I, Res);
  5608. DAG.setRoot(Res.getValue(1));
  5609. return;
  5610. }
  5611. case Intrinsic::stackrestore:
  5612. Res = getValue(I.getArgOperand(0));
  5613. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
  5614. return;
  5615. case Intrinsic::get_dynamic_area_offset: {
  5616. SDValue Op = getRoot();
  5617. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5618. EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
  5619. // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
  5620. // target.
  5621. if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
  5622. report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
  5623. " intrinsic!");
  5624. Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
  5625. Op);
  5626. DAG.setRoot(Op);
  5627. setValue(&I, Res);
  5628. return;
  5629. }
  5630. case Intrinsic::stackguard: {
  5631. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5632. MachineFunction &MF = DAG.getMachineFunction();
  5633. const Module &M = *MF.getFunction().getParent();
  5634. SDValue Chain = getRoot();
  5635. if (TLI.useLoadStackGuardNode()) {
  5636. Res = getLoadStackGuard(DAG, sdl, Chain);
  5637. } else {
  5638. const Value *Global = TLI.getSDagStackGuard(M);
  5639. unsigned Align = DL->getPrefTypeAlignment(Global->getType());
  5640. Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
  5641. MachinePointerInfo(Global, 0), Align,
  5642. MachineMemOperand::MOVolatile);
  5643. }
  5644. if (TLI.useStackGuardXorFP())
  5645. Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
  5646. DAG.setRoot(Chain);
  5647. setValue(&I, Res);
  5648. return;
  5649. }
  5650. case Intrinsic::stackprotector: {
  5651. // Emit code into the DAG to store the stack guard onto the stack.
  5652. MachineFunction &MF = DAG.getMachineFunction();
  5653. MachineFrameInfo &MFI = MF.getFrameInfo();
  5654. EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
  5655. SDValue Src, Chain = getRoot();
  5656. if (TLI.useLoadStackGuardNode())
  5657. Src = getLoadStackGuard(DAG, sdl, Chain);
  5658. else
  5659. Src = getValue(I.getArgOperand(0)); // The guard's value.
  5660. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  5661. int FI = FuncInfo.StaticAllocaMap[Slot];
  5662. MFI.setStackProtectorIndex(FI);
  5663. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  5664. // Store the stack protector onto the stack.
  5665. Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
  5666. DAG.getMachineFunction(), FI),
  5667. /* Alignment = */ 0, MachineMemOperand::MOVolatile);
  5668. setValue(&I, Res);
  5669. DAG.setRoot(Res);
  5670. return;
  5671. }
  5672. case Intrinsic::objectsize: {
  5673. // If we don't know by now, we're never going to know.
  5674. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  5675. assert(CI && "Non-constant type in __builtin_object_size?");
  5676. SDValue Arg = getValue(I.getCalledValue());
  5677. EVT Ty = Arg.getValueType();
  5678. if (CI->isZero())
  5679. Res = DAG.getConstant(-1ULL, sdl, Ty);
  5680. else
  5681. Res = DAG.getConstant(0, sdl, Ty);
  5682. setValue(&I, Res);
  5683. return;
  5684. }
  5685. case Intrinsic::is_constant:
  5686. // If this wasn't constant-folded away by now, then it's not a
  5687. // constant.
  5688. setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
  5689. return;
  5690. case Intrinsic::annotation:
  5691. case Intrinsic::ptr_annotation:
  5692. case Intrinsic::launder_invariant_group:
  5693. case Intrinsic::strip_invariant_group:
  5694. // Drop the intrinsic, but forward the value
  5695. setValue(&I, getValue(I.getOperand(0)));
  5696. return;
  5697. case Intrinsic::assume:
  5698. case Intrinsic::var_annotation:
  5699. case Intrinsic::sideeffect:
  5700. // Discard annotate attributes, assumptions, and artificial side-effects.
  5701. return;
  5702. case Intrinsic::codeview_annotation: {
  5703. // Emit a label associated with this metadata.
  5704. MachineFunction &MF = DAG.getMachineFunction();
  5705. MCSymbol *Label =
  5706. MF.getMMI().getContext().createTempSymbol("annotation", true);
  5707. Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
  5708. MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
  5709. Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
  5710. DAG.setRoot(Res);
  5711. return;
  5712. }
  5713. case Intrinsic::init_trampoline: {
  5714. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  5715. SDValue Ops[6];
  5716. Ops[0] = getRoot();
  5717. Ops[1] = getValue(I.getArgOperand(0));
  5718. Ops[2] = getValue(I.getArgOperand(1));
  5719. Ops[3] = getValue(I.getArgOperand(2));
  5720. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  5721. Ops[5] = DAG.getSrcValue(F);
  5722. Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
  5723. DAG.setRoot(Res);
  5724. return;
  5725. }
  5726. case Intrinsic::adjust_trampoline:
  5727. setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
  5728. TLI.getPointerTy(DAG.getDataLayout()),
  5729. getValue(I.getArgOperand(0))));
  5730. return;
  5731. case Intrinsic::gcroot: {
  5732. assert(DAG.getMachineFunction().getFunction().hasGC() &&
  5733. "only valid in functions with gc specified, enforced by Verifier");
  5734. assert(GFI && "implied by previous");
  5735. const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
  5736. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  5737. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  5738. GFI->addStackRoot(FI->getIndex(), TypeMap);
  5739. return;
  5740. }
  5741. case Intrinsic::gcread:
  5742. case Intrinsic::gcwrite:
  5743. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  5744. case Intrinsic::flt_rounds:
  5745. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
  5746. return;
  5747. case Intrinsic::expect:
  5748. // Just replace __builtin_expect(exp, c) with EXP.
  5749. setValue(&I, getValue(I.getArgOperand(0)));
  5750. return;
  5751. case Intrinsic::debugtrap:
  5752. case Intrinsic::trap: {
  5753. StringRef TrapFuncName =
  5754. I.getAttributes()
  5755. .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
  5756. .getValueAsString();
  5757. if (TrapFuncName.empty()) {
  5758. ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
  5759. ISD::TRAP : ISD::DEBUGTRAP;
  5760. DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
  5761. return;
  5762. }
  5763. TargetLowering::ArgListTy Args;
  5764. TargetLowering::CallLoweringInfo CLI(DAG);
  5765. CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
  5766. CallingConv::C, I.getType(),
  5767. DAG.getExternalSymbol(TrapFuncName.data(),
  5768. TLI.getPointerTy(DAG.getDataLayout())),
  5769. std::move(Args));
  5770. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  5771. DAG.setRoot(Result.second);
  5772. return;
  5773. }
  5774. case Intrinsic::uadd_with_overflow:
  5775. case Intrinsic::sadd_with_overflow:
  5776. case Intrinsic::usub_with_overflow:
  5777. case Intrinsic::ssub_with_overflow:
  5778. case Intrinsic::umul_with_overflow:
  5779. case Intrinsic::smul_with_overflow: {
  5780. ISD::NodeType Op;
  5781. switch (Intrinsic) {
  5782. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  5783. case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
  5784. case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
  5785. case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
  5786. case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
  5787. case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
  5788. case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
  5789. }
  5790. SDValue Op1 = getValue(I.getArgOperand(0));
  5791. SDValue Op2 = getValue(I.getArgOperand(1));
  5792. EVT ResultVT = Op1.getValueType();
  5793. EVT OverflowVT = MVT::i1;
  5794. if (ResultVT.isVector())
  5795. OverflowVT = EVT::getVectorVT(
  5796. *Context, OverflowVT, ResultVT.getVectorNumElements());
  5797. SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
  5798. setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
  5799. return;
  5800. }
  5801. case Intrinsic::prefetch: {
  5802. SDValue Ops[5];
  5803. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  5804. auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
  5805. Ops[0] = DAG.getRoot();
  5806. Ops[1] = getValue(I.getArgOperand(0));
  5807. Ops[2] = getValue(I.getArgOperand(1));
  5808. Ops[3] = getValue(I.getArgOperand(2));
  5809. Ops[4] = getValue(I.getArgOperand(3));
  5810. SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
  5811. DAG.getVTList(MVT::Other), Ops,
  5812. EVT::getIntegerVT(*Context, 8),
  5813. MachinePointerInfo(I.getArgOperand(0)),
  5814. 0, /* align */
  5815. Flags);
  5816. // Chain the prefetch in parallell with any pending loads, to stay out of
  5817. // the way of later optimizations.
  5818. PendingLoads.push_back(Result);
  5819. Result = getRoot();
  5820. DAG.setRoot(Result);
  5821. return;
  5822. }
  5823. case Intrinsic::lifetime_start:
  5824. case Intrinsic::lifetime_end: {
  5825. bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
  5826. // Stack coloring is not enabled in O0, discard region information.
  5827. if (TM.getOptLevel() == CodeGenOpt::None)
  5828. return;
  5829. const int64_t ObjectSize =
  5830. cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
  5831. Value *const ObjectPtr = I.getArgOperand(1);
  5832. SmallVector<const Value *, 4> Allocas;
  5833. GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
  5834. for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
  5835. E = Allocas.end(); Object != E; ++Object) {
  5836. const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
  5837. // Could not find an Alloca.
  5838. if (!LifetimeObject)
  5839. continue;
  5840. // First check that the Alloca is static, otherwise it won't have a
  5841. // valid frame index.
  5842. auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
  5843. if (SI == FuncInfo.StaticAllocaMap.end())
  5844. return;
  5845. const int FrameIndex = SI->second;
  5846. int64_t Offset;
  5847. if (GetPointerBaseWithConstantOffset(
  5848. ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
  5849. Offset = -1; // Cannot determine offset from alloca to lifetime object.
  5850. Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
  5851. Offset);
  5852. DAG.setRoot(Res);
  5853. }
  5854. return;
  5855. }
  5856. case Intrinsic::invariant_start:
  5857. // Discard region information.
  5858. setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
  5859. return;
  5860. case Intrinsic::invariant_end:
  5861. // Discard region information.
  5862. return;
  5863. case Intrinsic::clear_cache:
  5864. /// FunctionName may be null.
  5865. if (const char *FunctionName = TLI.getClearCacheBuiltinName())
  5866. lowerCallToExternalSymbol(I, FunctionName);
  5867. return;
  5868. case Intrinsic::donothing:
  5869. // ignore
  5870. return;
  5871. case Intrinsic::experimental_stackmap:
  5872. visitStackmap(I);
  5873. return;
  5874. case Intrinsic::experimental_patchpoint_void:
  5875. case Intrinsic::experimental_patchpoint_i64:
  5876. visitPatchpoint(&I);
  5877. return;
  5878. case Intrinsic::experimental_gc_statepoint:
  5879. LowerStatepoint(ImmutableStatepoint(&I));
  5880. return;
  5881. case Intrinsic::experimental_gc_result:
  5882. visitGCResult(cast<GCResultInst>(I));
  5883. return;
  5884. case Intrinsic::experimental_gc_relocate:
  5885. visitGCRelocate(cast<GCRelocateInst>(I));
  5886. return;
  5887. case Intrinsic::instrprof_increment:
  5888. llvm_unreachable("instrprof failed to lower an increment");
  5889. case Intrinsic::instrprof_value_profile:
  5890. llvm_unreachable("instrprof failed to lower a value profiling call");
  5891. case Intrinsic::localescape: {
  5892. MachineFunction &MF = DAG.getMachineFunction();
  5893. const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
  5894. // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
  5895. // is the same on all targets.
  5896. for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
  5897. Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
  5898. if (isa<ConstantPointerNull>(Arg))
  5899. continue; // Skip null pointers. They represent a hole in index space.
  5900. AllocaInst *Slot = cast<AllocaInst>(Arg);
  5901. assert(FuncInfo.StaticAllocaMap.count(Slot) &&
  5902. "can only escape static allocas");
  5903. int FI = FuncInfo.StaticAllocaMap[Slot];
  5904. MCSymbol *FrameAllocSym =
  5905. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5906. GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
  5907. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
  5908. TII->get(TargetOpcode::LOCAL_ESCAPE))
  5909. .addSym(FrameAllocSym)
  5910. .addFrameIndex(FI);
  5911. }
  5912. return;
  5913. }
  5914. case Intrinsic::localrecover: {
  5915. // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
  5916. MachineFunction &MF = DAG.getMachineFunction();
  5917. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
  5918. // Get the symbol that defines the frame offset.
  5919. auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
  5920. auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
  5921. unsigned IdxVal =
  5922. unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
  5923. MCSymbol *FrameAllocSym =
  5924. MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
  5925. GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
  5926. // Create a MCSymbol for the label to avoid any target lowering
  5927. // that would make this PC relative.
  5928. SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
  5929. SDValue OffsetVal =
  5930. DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
  5931. // Add the offset to the FP.
  5932. Value *FP = I.getArgOperand(1);
  5933. SDValue FPVal = getValue(FP);
  5934. SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
  5935. setValue(&I, Add);
  5936. return;
  5937. }
  5938. case Intrinsic::eh_exceptionpointer:
  5939. case Intrinsic::eh_exceptioncode: {
  5940. // Get the exception pointer vreg, copy from it, and resize it to fit.
  5941. const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
  5942. MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  5943. const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
  5944. unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
  5945. SDValue N =
  5946. DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
  5947. if (Intrinsic == Intrinsic::eh_exceptioncode)
  5948. N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
  5949. setValue(&I, N);
  5950. return;
  5951. }
  5952. case Intrinsic::xray_customevent: {
  5953. // Here we want to make sure that the intrinsic behaves as if it has a
  5954. // specific calling convention, and only for x86_64.
  5955. // FIXME: Support other platforms later.
  5956. const auto &Triple = DAG.getTarget().getTargetTriple();
  5957. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5958. return;
  5959. SDLoc DL = getCurSDLoc();
  5960. SmallVector<SDValue, 8> Ops;
  5961. // We want to say that we always want the arguments in registers.
  5962. SDValue LogEntryVal = getValue(I.getArgOperand(0));
  5963. SDValue StrSizeVal = getValue(I.getArgOperand(1));
  5964. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5965. SDValue Chain = getRoot();
  5966. Ops.push_back(LogEntryVal);
  5967. Ops.push_back(StrSizeVal);
  5968. Ops.push_back(Chain);
  5969. // We need to enforce the calling convention for the callsite, so that
  5970. // argument ordering is enforced correctly, and that register allocation can
  5971. // see that some registers may be assumed clobbered and have to preserve
  5972. // them across calls to the intrinsic.
  5973. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
  5974. DL, NodeTys, Ops);
  5975. SDValue patchableNode = SDValue(MN, 0);
  5976. DAG.setRoot(patchableNode);
  5977. setValue(&I, patchableNode);
  5978. return;
  5979. }
  5980. case Intrinsic::xray_typedevent: {
  5981. // Here we want to make sure that the intrinsic behaves as if it has a
  5982. // specific calling convention, and only for x86_64.
  5983. // FIXME: Support other platforms later.
  5984. const auto &Triple = DAG.getTarget().getTargetTriple();
  5985. if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
  5986. return;
  5987. SDLoc DL = getCurSDLoc();
  5988. SmallVector<SDValue, 8> Ops;
  5989. // We want to say that we always want the arguments in registers.
  5990. // It's unclear to me how manipulating the selection DAG here forces callers
  5991. // to provide arguments in registers instead of on the stack.
  5992. SDValue LogTypeId = getValue(I.getArgOperand(0));
  5993. SDValue LogEntryVal = getValue(I.getArgOperand(1));
  5994. SDValue StrSizeVal = getValue(I.getArgOperand(2));
  5995. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5996. SDValue Chain = getRoot();
  5997. Ops.push_back(LogTypeId);
  5998. Ops.push_back(LogEntryVal);
  5999. Ops.push_back(StrSizeVal);
  6000. Ops.push_back(Chain);
  6001. // We need to enforce the calling convention for the callsite, so that
  6002. // argument ordering is enforced correctly, and that register allocation can
  6003. // see that some registers may be assumed clobbered and have to preserve
  6004. // them across calls to the intrinsic.
  6005. MachineSDNode *MN = DAG.getMachineNode(
  6006. TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
  6007. SDValue patchableNode = SDValue(MN, 0);
  6008. DAG.setRoot(patchableNode);
  6009. setValue(&I, patchableNode);
  6010. return;
  6011. }
  6012. case Intrinsic::experimental_deoptimize:
  6013. LowerDeoptimizeCall(&I);
  6014. return;
  6015. case Intrinsic::experimental_vector_reduce_v2_fadd:
  6016. case Intrinsic::experimental_vector_reduce_v2_fmul:
  6017. case Intrinsic::experimental_vector_reduce_add:
  6018. case Intrinsic::experimental_vector_reduce_mul:
  6019. case Intrinsic::experimental_vector_reduce_and:
  6020. case Intrinsic::experimental_vector_reduce_or:
  6021. case Intrinsic::experimental_vector_reduce_xor:
  6022. case Intrinsic::experimental_vector_reduce_smax:
  6023. case Intrinsic::experimental_vector_reduce_smin:
  6024. case Intrinsic::experimental_vector_reduce_umax:
  6025. case Intrinsic::experimental_vector_reduce_umin:
  6026. case Intrinsic::experimental_vector_reduce_fmax:
  6027. case Intrinsic::experimental_vector_reduce_fmin:
  6028. visitVectorReduce(I, Intrinsic);
  6029. return;
  6030. case Intrinsic::icall_branch_funnel: {
  6031. SmallVector<SDValue, 16> Ops;
  6032. Ops.push_back(getValue(I.getArgOperand(0)));
  6033. int64_t Offset;
  6034. auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6035. I.getArgOperand(1), Offset, DAG.getDataLayout()));
  6036. if (!Base)
  6037. report_fatal_error(
  6038. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6039. Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
  6040. struct BranchFunnelTarget {
  6041. int64_t Offset;
  6042. SDValue Target;
  6043. };
  6044. SmallVector<BranchFunnelTarget, 8> Targets;
  6045. for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
  6046. auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
  6047. I.getArgOperand(Op), Offset, DAG.getDataLayout()));
  6048. if (ElemBase != Base)
  6049. report_fatal_error("all llvm.icall.branch.funnel operands must refer "
  6050. "to the same GlobalValue");
  6051. SDValue Val = getValue(I.getArgOperand(Op + 1));
  6052. auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
  6053. if (!GA)
  6054. report_fatal_error(
  6055. "llvm.icall.branch.funnel operand must be a GlobalValue");
  6056. Targets.push_back({Offset, DAG.getTargetGlobalAddress(
  6057. GA->getGlobal(), getCurSDLoc(),
  6058. Val.getValueType(), GA->getOffset())});
  6059. }
  6060. llvm::sort(Targets,
  6061. [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
  6062. return T1.Offset < T2.Offset;
  6063. });
  6064. for (auto &T : Targets) {
  6065. Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
  6066. Ops.push_back(T.Target);
  6067. }
  6068. Ops.push_back(DAG.getRoot()); // Chain
  6069. SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
  6070. getCurSDLoc(), MVT::Other, Ops),
  6071. 0);
  6072. DAG.setRoot(N);
  6073. setValue(&I, N);
  6074. HasTailCall = true;
  6075. return;
  6076. }
  6077. case Intrinsic::wasm_landingpad_index:
  6078. // Information this intrinsic contained has been transferred to
  6079. // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
  6080. // delete it now.
  6081. return;
  6082. case Intrinsic::aarch64_settag:
  6083. case Intrinsic::aarch64_settag_zero: {
  6084. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6085. bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
  6086. SDValue Val = TSI.EmitTargetCodeForSetTag(
  6087. DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
  6088. getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
  6089. ZeroMemory);
  6090. DAG.setRoot(Val);
  6091. setValue(&I, Val);
  6092. return;
  6093. }
  6094. case Intrinsic::ptrmask: {
  6095. SDValue Ptr = getValue(I.getOperand(0));
  6096. SDValue Const = getValue(I.getOperand(1));
  6097. EVT DestVT =
  6098. EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
  6099. setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
  6100. DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
  6101. return;
  6102. }
  6103. }
  6104. }
  6105. void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
  6106. const ConstrainedFPIntrinsic &FPI) {
  6107. SDLoc sdl = getCurSDLoc();
  6108. unsigned Opcode;
  6109. switch (FPI.getIntrinsicID()) {
  6110. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  6111. case Intrinsic::experimental_constrained_fadd:
  6112. Opcode = ISD::STRICT_FADD;
  6113. break;
  6114. case Intrinsic::experimental_constrained_fsub:
  6115. Opcode = ISD::STRICT_FSUB;
  6116. break;
  6117. case Intrinsic::experimental_constrained_fmul:
  6118. Opcode = ISD::STRICT_FMUL;
  6119. break;
  6120. case Intrinsic::experimental_constrained_fdiv:
  6121. Opcode = ISD::STRICT_FDIV;
  6122. break;
  6123. case Intrinsic::experimental_constrained_frem:
  6124. Opcode = ISD::STRICT_FREM;
  6125. break;
  6126. case Intrinsic::experimental_constrained_fma:
  6127. Opcode = ISD::STRICT_FMA;
  6128. break;
  6129. case Intrinsic::experimental_constrained_fptosi:
  6130. Opcode = ISD::STRICT_FP_TO_SINT;
  6131. break;
  6132. case Intrinsic::experimental_constrained_fptoui:
  6133. Opcode = ISD::STRICT_FP_TO_UINT;
  6134. break;
  6135. case Intrinsic::experimental_constrained_fptrunc:
  6136. Opcode = ISD::STRICT_FP_ROUND;
  6137. break;
  6138. case Intrinsic::experimental_constrained_fpext:
  6139. Opcode = ISD::STRICT_FP_EXTEND;
  6140. break;
  6141. case Intrinsic::experimental_constrained_sqrt:
  6142. Opcode = ISD::STRICT_FSQRT;
  6143. break;
  6144. case Intrinsic::experimental_constrained_pow:
  6145. Opcode = ISD::STRICT_FPOW;
  6146. break;
  6147. case Intrinsic::experimental_constrained_powi:
  6148. Opcode = ISD::STRICT_FPOWI;
  6149. break;
  6150. case Intrinsic::experimental_constrained_sin:
  6151. Opcode = ISD::STRICT_FSIN;
  6152. break;
  6153. case Intrinsic::experimental_constrained_cos:
  6154. Opcode = ISD::STRICT_FCOS;
  6155. break;
  6156. case Intrinsic::experimental_constrained_exp:
  6157. Opcode = ISD::STRICT_FEXP;
  6158. break;
  6159. case Intrinsic::experimental_constrained_exp2:
  6160. Opcode = ISD::STRICT_FEXP2;
  6161. break;
  6162. case Intrinsic::experimental_constrained_log:
  6163. Opcode = ISD::STRICT_FLOG;
  6164. break;
  6165. case Intrinsic::experimental_constrained_log10:
  6166. Opcode = ISD::STRICT_FLOG10;
  6167. break;
  6168. case Intrinsic::experimental_constrained_log2:
  6169. Opcode = ISD::STRICT_FLOG2;
  6170. break;
  6171. case Intrinsic::experimental_constrained_rint:
  6172. Opcode = ISD::STRICT_FRINT;
  6173. break;
  6174. case Intrinsic::experimental_constrained_nearbyint:
  6175. Opcode = ISD::STRICT_FNEARBYINT;
  6176. break;
  6177. case Intrinsic::experimental_constrained_maxnum:
  6178. Opcode = ISD::STRICT_FMAXNUM;
  6179. break;
  6180. case Intrinsic::experimental_constrained_minnum:
  6181. Opcode = ISD::STRICT_FMINNUM;
  6182. break;
  6183. case Intrinsic::experimental_constrained_ceil:
  6184. Opcode = ISD::STRICT_FCEIL;
  6185. break;
  6186. case Intrinsic::experimental_constrained_floor:
  6187. Opcode = ISD::STRICT_FFLOOR;
  6188. break;
  6189. case Intrinsic::experimental_constrained_round:
  6190. Opcode = ISD::STRICT_FROUND;
  6191. break;
  6192. case Intrinsic::experimental_constrained_trunc:
  6193. Opcode = ISD::STRICT_FTRUNC;
  6194. break;
  6195. }
  6196. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6197. SDValue Chain = getRoot();
  6198. SmallVector<EVT, 4> ValueVTs;
  6199. ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
  6200. ValueVTs.push_back(MVT::Other); // Out chain
  6201. SDVTList VTs = DAG.getVTList(ValueVTs);
  6202. SDValue Result;
  6203. if (Opcode == ISD::STRICT_FP_ROUND)
  6204. Result = DAG.getNode(Opcode, sdl, VTs,
  6205. { Chain, getValue(FPI.getArgOperand(0)),
  6206. DAG.getTargetConstant(0, sdl,
  6207. TLI.getPointerTy(DAG.getDataLayout())) });
  6208. else if (FPI.isUnaryOp())
  6209. Result = DAG.getNode(Opcode, sdl, VTs,
  6210. { Chain, getValue(FPI.getArgOperand(0)) });
  6211. else if (FPI.isTernaryOp())
  6212. Result = DAG.getNode(Opcode, sdl, VTs,
  6213. { Chain, getValue(FPI.getArgOperand(0)),
  6214. getValue(FPI.getArgOperand(1)),
  6215. getValue(FPI.getArgOperand(2)) });
  6216. else
  6217. Result = DAG.getNode(Opcode, sdl, VTs,
  6218. { Chain, getValue(FPI.getArgOperand(0)),
  6219. getValue(FPI.getArgOperand(1)) });
  6220. if (FPI.getExceptionBehavior() !=
  6221. ConstrainedFPIntrinsic::ExceptionBehavior::ebIgnore) {
  6222. SDNodeFlags Flags;
  6223. Flags.setFPExcept(true);
  6224. Result->setFlags(Flags);
  6225. }
  6226. assert(Result.getNode()->getNumValues() == 2);
  6227. SDValue OutChain = Result.getValue(1);
  6228. DAG.setRoot(OutChain);
  6229. SDValue FPResult = Result.getValue(0);
  6230. setValue(&FPI, FPResult);
  6231. }
  6232. std::pair<SDValue, SDValue>
  6233. SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
  6234. const BasicBlock *EHPadBB) {
  6235. MachineFunction &MF = DAG.getMachineFunction();
  6236. MachineModuleInfo &MMI = MF.getMMI();
  6237. MCSymbol *BeginLabel = nullptr;
  6238. if (EHPadBB) {
  6239. // Insert a label before the invoke call to mark the try range. This can be
  6240. // used to detect deletion of the invoke via the MachineModuleInfo.
  6241. BeginLabel = MMI.getContext().createTempSymbol();
  6242. // For SjLj, keep track of which landing pads go with which invokes
  6243. // so as to maintain the ordering of pads in the LSDA.
  6244. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  6245. if (CallSiteIndex) {
  6246. MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  6247. LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
  6248. // Now that the call site is handled, stop tracking it.
  6249. MMI.setCurrentCallSite(0);
  6250. }
  6251. // Both PendingLoads and PendingExports must be flushed here;
  6252. // this call might not return.
  6253. (void)getRoot();
  6254. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
  6255. CLI.setChain(getRoot());
  6256. }
  6257. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6258. std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
  6259. assert((CLI.IsTailCall || Result.second.getNode()) &&
  6260. "Non-null chain expected with non-tail call!");
  6261. assert((Result.second.getNode() || !Result.first.getNode()) &&
  6262. "Null value expected with tail call!");
  6263. if (!Result.second.getNode()) {
  6264. // As a special case, a null chain means that a tail call has been emitted
  6265. // and the DAG root is already updated.
  6266. HasTailCall = true;
  6267. // Since there's no actual continuation from this block, nothing can be
  6268. // relying on us setting vregs for them.
  6269. PendingExports.clear();
  6270. } else {
  6271. DAG.setRoot(Result.second);
  6272. }
  6273. if (EHPadBB) {
  6274. // Insert a label at the end of the invoke call to mark the try range. This
  6275. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  6276. MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
  6277. DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
  6278. // Inform MachineModuleInfo of range.
  6279. auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
  6280. // There is a platform (e.g. wasm) that uses funclet style IR but does not
  6281. // actually use outlined funclets and their LSDA info style.
  6282. if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
  6283. assert(CLI.CS);
  6284. WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
  6285. EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
  6286. BeginLabel, EndLabel);
  6287. } else if (!isScopedEHPersonality(Pers)) {
  6288. MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
  6289. }
  6290. }
  6291. return Result;
  6292. }
  6293. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  6294. bool isTailCall,
  6295. const BasicBlock *EHPadBB) {
  6296. auto &DL = DAG.getDataLayout();
  6297. FunctionType *FTy = CS.getFunctionType();
  6298. Type *RetTy = CS.getType();
  6299. TargetLowering::ArgListTy Args;
  6300. Args.reserve(CS.arg_size());
  6301. const Value *SwiftErrorVal = nullptr;
  6302. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6303. // We can't tail call inside a function with a swifterror argument. Lowering
  6304. // does not support this yet. It would have to move into the swifterror
  6305. // register before the call.
  6306. auto *Caller = CS.getInstruction()->getParent()->getParent();
  6307. if (TLI.supportSwiftError() &&
  6308. Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  6309. isTailCall = false;
  6310. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  6311. i != e; ++i) {
  6312. TargetLowering::ArgListEntry Entry;
  6313. const Value *V = *i;
  6314. // Skip empty types
  6315. if (V->getType()->isEmptyTy())
  6316. continue;
  6317. SDValue ArgNode = getValue(V);
  6318. Entry.Node = ArgNode; Entry.Ty = V->getType();
  6319. Entry.setAttributes(&CS, i - CS.arg_begin());
  6320. // Use swifterror virtual register as input to the call.
  6321. if (Entry.IsSwiftError && TLI.supportSwiftError()) {
  6322. SwiftErrorVal = V;
  6323. // We find the virtual register for the actual swifterror argument.
  6324. // Instead of using the Value, we use the virtual register instead.
  6325. Entry.Node = DAG.getRegister(
  6326. SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
  6327. EVT(TLI.getPointerTy(DL)));
  6328. }
  6329. Args.push_back(Entry);
  6330. // If we have an explicit sret argument that is an Instruction, (i.e., it
  6331. // might point to function-local memory), we can't meaningfully tail-call.
  6332. if (Entry.IsSRet && isa<Instruction>(V))
  6333. isTailCall = false;
  6334. }
  6335. // Check if target-independent constraints permit a tail call here.
  6336. // Target-dependent constraints are checked within TLI->LowerCallTo.
  6337. if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
  6338. isTailCall = false;
  6339. // Disable tail calls if there is an swifterror argument. Targets have not
  6340. // been updated to support tail calls.
  6341. if (TLI.supportSwiftError() && SwiftErrorVal)
  6342. isTailCall = false;
  6343. TargetLowering::CallLoweringInfo CLI(DAG);
  6344. CLI.setDebugLoc(getCurSDLoc())
  6345. .setChain(getRoot())
  6346. .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
  6347. .setTailCall(isTailCall)
  6348. .setConvergent(CS.isConvergent());
  6349. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  6350. if (Result.first.getNode()) {
  6351. const Instruction *Inst = CS.getInstruction();
  6352. Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
  6353. setValue(Inst, Result.first);
  6354. }
  6355. // The last element of CLI.InVals has the SDValue for swifterror return.
  6356. // Here we copy it to a virtual register and update SwiftErrorMap for
  6357. // book-keeping.
  6358. if (SwiftErrorVal && TLI.supportSwiftError()) {
  6359. // Get the last element of InVals.
  6360. SDValue Src = CLI.InVals.back();
  6361. Register VReg = SwiftError.getOrCreateVRegDefAt(
  6362. CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
  6363. SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
  6364. DAG.setRoot(CopyNode);
  6365. }
  6366. }
  6367. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  6368. SelectionDAGBuilder &Builder) {
  6369. // Check to see if this load can be trivially constant folded, e.g. if the
  6370. // input is from a string literal.
  6371. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  6372. // Cast pointer to the type we really want to load.
  6373. Type *LoadTy =
  6374. Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
  6375. if (LoadVT.isVector())
  6376. LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
  6377. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  6378. PointerType::getUnqual(LoadTy));
  6379. if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
  6380. const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
  6381. return Builder.getValue(LoadCst);
  6382. }
  6383. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  6384. // still constant memory, the input chain can be the entry node.
  6385. SDValue Root;
  6386. bool ConstantMemory = false;
  6387. // Do not serialize (non-volatile) loads of constant memory with anything.
  6388. if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
  6389. Root = Builder.DAG.getEntryNode();
  6390. ConstantMemory = true;
  6391. } else {
  6392. // Do not serialize non-volatile loads against each other.
  6393. Root = Builder.DAG.getRoot();
  6394. }
  6395. SDValue Ptr = Builder.getValue(PtrVal);
  6396. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
  6397. Ptr, MachinePointerInfo(PtrVal),
  6398. /* Alignment = */ 1);
  6399. if (!ConstantMemory)
  6400. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  6401. return LoadVal;
  6402. }
  6403. /// Record the value for an instruction that produces an integer result,
  6404. /// converting the type where necessary.
  6405. void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
  6406. SDValue Value,
  6407. bool IsSigned) {
  6408. EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6409. I.getType(), true);
  6410. if (IsSigned)
  6411. Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
  6412. else
  6413. Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
  6414. setValue(&I, Value);
  6415. }
  6416. /// See if we can lower a memcmp call into an optimized form. If so, return
  6417. /// true and lower it. Otherwise return false, and it will be lowered like a
  6418. /// normal call.
  6419. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6420. /// correct prototype.
  6421. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  6422. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  6423. const Value *Size = I.getArgOperand(2);
  6424. const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
  6425. if (CSize && CSize->getZExtValue() == 0) {
  6426. EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
  6427. I.getType(), true);
  6428. setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
  6429. return true;
  6430. }
  6431. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6432. std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
  6433. DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
  6434. getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
  6435. if (Res.first.getNode()) {
  6436. processIntegerCallValue(I, Res.first, true);
  6437. PendingLoads.push_back(Res.second);
  6438. return true;
  6439. }
  6440. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  6441. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  6442. if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
  6443. return false;
  6444. // If the target has a fast compare for the given size, it will return a
  6445. // preferred load type for that size. Require that the load VT is legal and
  6446. // that the target supports unaligned loads of that type. Otherwise, return
  6447. // INVALID.
  6448. auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
  6449. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6450. MVT LVT = TLI.hasFastEqualityCompare(NumBits);
  6451. if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
  6452. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  6453. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  6454. // TODO: Check alignment of src and dest ptrs.
  6455. unsigned DstAS = LHS->getType()->getPointerAddressSpace();
  6456. unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
  6457. if (!TLI.isTypeLegal(LVT) ||
  6458. !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
  6459. !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
  6460. LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
  6461. }
  6462. return LVT;
  6463. };
  6464. // This turns into unaligned loads. We only do this if the target natively
  6465. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  6466. // we'll only produce a small number of byte loads.
  6467. MVT LoadVT;
  6468. unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
  6469. switch (NumBitsToCompare) {
  6470. default:
  6471. return false;
  6472. case 16:
  6473. LoadVT = MVT::i16;
  6474. break;
  6475. case 32:
  6476. LoadVT = MVT::i32;
  6477. break;
  6478. case 64:
  6479. case 128:
  6480. case 256:
  6481. LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
  6482. break;
  6483. }
  6484. if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
  6485. return false;
  6486. SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
  6487. SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
  6488. // Bitcast to a wide integer type if the loads are vectors.
  6489. if (LoadVT.isVector()) {
  6490. EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
  6491. LoadL = DAG.getBitcast(CmpVT, LoadL);
  6492. LoadR = DAG.getBitcast(CmpVT, LoadR);
  6493. }
  6494. SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
  6495. processIntegerCallValue(I, Cmp, false);
  6496. return true;
  6497. }
  6498. /// See if we can lower a memchr call into an optimized form. If so, return
  6499. /// true and lower it. Otherwise return false, and it will be lowered like a
  6500. /// normal call.
  6501. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6502. /// correct prototype.
  6503. bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
  6504. const Value *Src = I.getArgOperand(0);
  6505. const Value *Char = I.getArgOperand(1);
  6506. const Value *Length = I.getArgOperand(2);
  6507. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6508. std::pair<SDValue, SDValue> Res =
  6509. TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
  6510. getValue(Src), getValue(Char), getValue(Length),
  6511. MachinePointerInfo(Src));
  6512. if (Res.first.getNode()) {
  6513. setValue(&I, Res.first);
  6514. PendingLoads.push_back(Res.second);
  6515. return true;
  6516. }
  6517. return false;
  6518. }
  6519. /// See if we can lower a mempcpy call into an optimized form. If so, return
  6520. /// true and lower it. Otherwise return false, and it will be lowered like a
  6521. /// normal call.
  6522. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6523. /// correct prototype.
  6524. bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
  6525. SDValue Dst = getValue(I.getArgOperand(0));
  6526. SDValue Src = getValue(I.getArgOperand(1));
  6527. SDValue Size = getValue(I.getArgOperand(2));
  6528. unsigned DstAlign = DAG.InferPtrAlignment(Dst);
  6529. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  6530. unsigned Align = std::min(DstAlign, SrcAlign);
  6531. if (Align == 0) // Alignment of one or both could not be inferred.
  6532. Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
  6533. bool isVol = false;
  6534. SDLoc sdl = getCurSDLoc();
  6535. // In the mempcpy context we need to pass in a false value for isTailCall
  6536. // because the return pointer needs to be adjusted by the size of
  6537. // the copied memory.
  6538. SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
  6539. false, /*isTailCall=*/false,
  6540. MachinePointerInfo(I.getArgOperand(0)),
  6541. MachinePointerInfo(I.getArgOperand(1)));
  6542. assert(MC.getNode() != nullptr &&
  6543. "** memcpy should not be lowered as TailCall in mempcpy context **");
  6544. DAG.setRoot(MC);
  6545. // Check if Size needs to be truncated or extended.
  6546. Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
  6547. // Adjust return pointer to point just past the last dst byte.
  6548. SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
  6549. Dst, Size);
  6550. setValue(&I, DstPlusSize);
  6551. return true;
  6552. }
  6553. /// See if we can lower a strcpy call into an optimized form. If so, return
  6554. /// true and lower it, otherwise return false and it will be lowered like a
  6555. /// normal call.
  6556. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6557. /// correct prototype.
  6558. bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
  6559. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6560. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6561. std::pair<SDValue, SDValue> Res =
  6562. TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
  6563. getValue(Arg0), getValue(Arg1),
  6564. MachinePointerInfo(Arg0),
  6565. MachinePointerInfo(Arg1), isStpcpy);
  6566. if (Res.first.getNode()) {
  6567. setValue(&I, Res.first);
  6568. DAG.setRoot(Res.second);
  6569. return true;
  6570. }
  6571. return false;
  6572. }
  6573. /// See if we can lower a strcmp call into an optimized form. If so, return
  6574. /// true and lower it, otherwise return false and it will be lowered like a
  6575. /// normal call.
  6576. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6577. /// correct prototype.
  6578. bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
  6579. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6580. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6581. std::pair<SDValue, SDValue> Res =
  6582. TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
  6583. getValue(Arg0), getValue(Arg1),
  6584. MachinePointerInfo(Arg0),
  6585. MachinePointerInfo(Arg1));
  6586. if (Res.first.getNode()) {
  6587. processIntegerCallValue(I, Res.first, true);
  6588. PendingLoads.push_back(Res.second);
  6589. return true;
  6590. }
  6591. return false;
  6592. }
  6593. /// See if we can lower a strlen call into an optimized form. If so, return
  6594. /// true and lower it, otherwise return false and it will be lowered like a
  6595. /// normal call.
  6596. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6597. /// correct prototype.
  6598. bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
  6599. const Value *Arg0 = I.getArgOperand(0);
  6600. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6601. std::pair<SDValue, SDValue> Res =
  6602. TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6603. getValue(Arg0), MachinePointerInfo(Arg0));
  6604. if (Res.first.getNode()) {
  6605. processIntegerCallValue(I, Res.first, false);
  6606. PendingLoads.push_back(Res.second);
  6607. return true;
  6608. }
  6609. return false;
  6610. }
  6611. /// See if we can lower a strnlen call into an optimized form. If so, return
  6612. /// true and lower it, otherwise return false and it will be lowered like a
  6613. /// normal call.
  6614. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6615. /// correct prototype.
  6616. bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
  6617. const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
  6618. const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
  6619. std::pair<SDValue, SDValue> Res =
  6620. TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
  6621. getValue(Arg0), getValue(Arg1),
  6622. MachinePointerInfo(Arg0));
  6623. if (Res.first.getNode()) {
  6624. processIntegerCallValue(I, Res.first, false);
  6625. PendingLoads.push_back(Res.second);
  6626. return true;
  6627. }
  6628. return false;
  6629. }
  6630. /// See if we can lower a unary floating-point operation into an SDNode with
  6631. /// the specified Opcode. If so, return true and lower it, otherwise return
  6632. /// false and it will be lowered like a normal call.
  6633. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6634. /// correct prototype.
  6635. bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
  6636. unsigned Opcode) {
  6637. // We already checked this call's prototype; verify it doesn't modify errno.
  6638. if (!I.onlyReadsMemory())
  6639. return false;
  6640. SDValue Tmp = getValue(I.getArgOperand(0));
  6641. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
  6642. return true;
  6643. }
  6644. /// See if we can lower a binary floating-point operation into an SDNode with
  6645. /// the specified Opcode. If so, return true and lower it. Otherwise return
  6646. /// false, and it will be lowered like a normal call.
  6647. /// The caller already checked that \p I calls the appropriate LibFunc with a
  6648. /// correct prototype.
  6649. bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
  6650. unsigned Opcode) {
  6651. // We already checked this call's prototype; verify it doesn't modify errno.
  6652. if (!I.onlyReadsMemory())
  6653. return false;
  6654. SDValue Tmp0 = getValue(I.getArgOperand(0));
  6655. SDValue Tmp1 = getValue(I.getArgOperand(1));
  6656. EVT VT = Tmp0.getValueType();
  6657. setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
  6658. return true;
  6659. }
  6660. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  6661. // Handle inline assembly differently.
  6662. if (isa<InlineAsm>(I.getCalledValue())) {
  6663. visitInlineAsm(&I);
  6664. return;
  6665. }
  6666. if (Function *F = I.getCalledFunction()) {
  6667. if (F->isDeclaration()) {
  6668. // Is this an LLVM intrinsic or a target-specific intrinsic?
  6669. unsigned IID = F->getIntrinsicID();
  6670. if (!IID)
  6671. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
  6672. IID = II->getIntrinsicID(F);
  6673. if (IID) {
  6674. visitIntrinsicCall(I, IID);
  6675. return;
  6676. }
  6677. }
  6678. // Check for well-known libc/libm calls. If the function is internal, it
  6679. // can't be a library call. Don't do the check if marked as nobuiltin for
  6680. // some reason or the call site requires strict floating point semantics.
  6681. LibFunc Func;
  6682. if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
  6683. F->hasName() && LibInfo->getLibFunc(*F, Func) &&
  6684. LibInfo->hasOptimizedCodeGen(Func)) {
  6685. switch (Func) {
  6686. default: break;
  6687. case LibFunc_copysign:
  6688. case LibFunc_copysignf:
  6689. case LibFunc_copysignl:
  6690. // We already checked this call's prototype; verify it doesn't modify
  6691. // errno.
  6692. if (I.onlyReadsMemory()) {
  6693. SDValue LHS = getValue(I.getArgOperand(0));
  6694. SDValue RHS = getValue(I.getArgOperand(1));
  6695. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
  6696. LHS.getValueType(), LHS, RHS));
  6697. return;
  6698. }
  6699. break;
  6700. case LibFunc_fabs:
  6701. case LibFunc_fabsf:
  6702. case LibFunc_fabsl:
  6703. if (visitUnaryFloatCall(I, ISD::FABS))
  6704. return;
  6705. break;
  6706. case LibFunc_fmin:
  6707. case LibFunc_fminf:
  6708. case LibFunc_fminl:
  6709. if (visitBinaryFloatCall(I, ISD::FMINNUM))
  6710. return;
  6711. break;
  6712. case LibFunc_fmax:
  6713. case LibFunc_fmaxf:
  6714. case LibFunc_fmaxl:
  6715. if (visitBinaryFloatCall(I, ISD::FMAXNUM))
  6716. return;
  6717. break;
  6718. case LibFunc_sin:
  6719. case LibFunc_sinf:
  6720. case LibFunc_sinl:
  6721. if (visitUnaryFloatCall(I, ISD::FSIN))
  6722. return;
  6723. break;
  6724. case LibFunc_cos:
  6725. case LibFunc_cosf:
  6726. case LibFunc_cosl:
  6727. if (visitUnaryFloatCall(I, ISD::FCOS))
  6728. return;
  6729. break;
  6730. case LibFunc_sqrt:
  6731. case LibFunc_sqrtf:
  6732. case LibFunc_sqrtl:
  6733. case LibFunc_sqrt_finite:
  6734. case LibFunc_sqrtf_finite:
  6735. case LibFunc_sqrtl_finite:
  6736. if (visitUnaryFloatCall(I, ISD::FSQRT))
  6737. return;
  6738. break;
  6739. case LibFunc_floor:
  6740. case LibFunc_floorf:
  6741. case LibFunc_floorl:
  6742. if (visitUnaryFloatCall(I, ISD::FFLOOR))
  6743. return;
  6744. break;
  6745. case LibFunc_nearbyint:
  6746. case LibFunc_nearbyintf:
  6747. case LibFunc_nearbyintl:
  6748. if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
  6749. return;
  6750. break;
  6751. case LibFunc_ceil:
  6752. case LibFunc_ceilf:
  6753. case LibFunc_ceill:
  6754. if (visitUnaryFloatCall(I, ISD::FCEIL))
  6755. return;
  6756. break;
  6757. case LibFunc_rint:
  6758. case LibFunc_rintf:
  6759. case LibFunc_rintl:
  6760. if (visitUnaryFloatCall(I, ISD::FRINT))
  6761. return;
  6762. break;
  6763. case LibFunc_round:
  6764. case LibFunc_roundf:
  6765. case LibFunc_roundl:
  6766. if (visitUnaryFloatCall(I, ISD::FROUND))
  6767. return;
  6768. break;
  6769. case LibFunc_trunc:
  6770. case LibFunc_truncf:
  6771. case LibFunc_truncl:
  6772. if (visitUnaryFloatCall(I, ISD::FTRUNC))
  6773. return;
  6774. break;
  6775. case LibFunc_log2:
  6776. case LibFunc_log2f:
  6777. case LibFunc_log2l:
  6778. if (visitUnaryFloatCall(I, ISD::FLOG2))
  6779. return;
  6780. break;
  6781. case LibFunc_exp2:
  6782. case LibFunc_exp2f:
  6783. case LibFunc_exp2l:
  6784. if (visitUnaryFloatCall(I, ISD::FEXP2))
  6785. return;
  6786. break;
  6787. case LibFunc_memcmp:
  6788. if (visitMemCmpCall(I))
  6789. return;
  6790. break;
  6791. case LibFunc_mempcpy:
  6792. if (visitMemPCpyCall(I))
  6793. return;
  6794. break;
  6795. case LibFunc_memchr:
  6796. if (visitMemChrCall(I))
  6797. return;
  6798. break;
  6799. case LibFunc_strcpy:
  6800. if (visitStrCpyCall(I, false))
  6801. return;
  6802. break;
  6803. case LibFunc_stpcpy:
  6804. if (visitStrCpyCall(I, true))
  6805. return;
  6806. break;
  6807. case LibFunc_strcmp:
  6808. if (visitStrCmpCall(I))
  6809. return;
  6810. break;
  6811. case LibFunc_strlen:
  6812. if (visitStrLenCall(I))
  6813. return;
  6814. break;
  6815. case LibFunc_strnlen:
  6816. if (visitStrNLenCall(I))
  6817. return;
  6818. break;
  6819. }
  6820. }
  6821. }
  6822. // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
  6823. // have to do anything here to lower funclet bundles.
  6824. assert(!I.hasOperandBundlesOtherThan(
  6825. {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
  6826. "Cannot lower calls with arbitrary operand bundles!");
  6827. SDValue Callee = getValue(I.getCalledValue());
  6828. if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
  6829. LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
  6830. else
  6831. // Check if we can potentially perform a tail call. More detailed checking
  6832. // is be done within LowerCallTo, after more information about the call is
  6833. // known.
  6834. LowerCallTo(&I, Callee, I.isTailCall());
  6835. }
  6836. namespace {
  6837. /// AsmOperandInfo - This contains information for each constraint that we are
  6838. /// lowering.
  6839. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  6840. public:
  6841. /// CallOperand - If this is the result output operand or a clobber
  6842. /// this is null, otherwise it is the incoming operand to the CallInst.
  6843. /// This gets modified as the asm is processed.
  6844. SDValue CallOperand;
  6845. /// AssignedRegs - If this is a register or register class operand, this
  6846. /// contains the set of register corresponding to the operand.
  6847. RegsForValue AssignedRegs;
  6848. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  6849. : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
  6850. }
  6851. /// Whether or not this operand accesses memory
  6852. bool hasMemory(const TargetLowering &TLI) const {
  6853. // Indirect operand accesses access memory.
  6854. if (isIndirect)
  6855. return true;
  6856. for (const auto &Code : Codes)
  6857. if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
  6858. return true;
  6859. return false;
  6860. }
  6861. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  6862. /// corresponds to. If there is no Value* for this operand, it returns
  6863. /// MVT::Other.
  6864. EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
  6865. const DataLayout &DL) const {
  6866. if (!CallOperandVal) return MVT::Other;
  6867. if (isa<BasicBlock>(CallOperandVal))
  6868. return TLI.getPointerTy(DL);
  6869. llvm::Type *OpTy = CallOperandVal->getType();
  6870. // FIXME: code duplicated from TargetLowering::ParseConstraints().
  6871. // If this is an indirect operand, the operand is a pointer to the
  6872. // accessed type.
  6873. if (isIndirect) {
  6874. PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  6875. if (!PtrTy)
  6876. report_fatal_error("Indirect operand for inline asm not a pointer!");
  6877. OpTy = PtrTy->getElementType();
  6878. }
  6879. // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
  6880. if (StructType *STy = dyn_cast<StructType>(OpTy))
  6881. if (STy->getNumElements() == 1)
  6882. OpTy = STy->getElementType(0);
  6883. // If OpTy is not a single value, it may be a struct/union that we
  6884. // can tile with integers.
  6885. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  6886. unsigned BitSize = DL.getTypeSizeInBits(OpTy);
  6887. switch (BitSize) {
  6888. default: break;
  6889. case 1:
  6890. case 8:
  6891. case 16:
  6892. case 32:
  6893. case 64:
  6894. case 128:
  6895. OpTy = IntegerType::get(Context, BitSize);
  6896. break;
  6897. }
  6898. }
  6899. return TLI.getValueType(DL, OpTy, true);
  6900. }
  6901. };
  6902. using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
  6903. } // end anonymous namespace
  6904. /// Make sure that the output operand \p OpInfo and its corresponding input
  6905. /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
  6906. /// out).
  6907. static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
  6908. SDISelAsmOperandInfo &MatchingOpInfo,
  6909. SelectionDAG &DAG) {
  6910. if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
  6911. return;
  6912. const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
  6913. const auto &TLI = DAG.getTargetLoweringInfo();
  6914. std::pair<unsigned, const TargetRegisterClass *> MatchRC =
  6915. TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
  6916. OpInfo.ConstraintVT);
  6917. std::pair<unsigned, const TargetRegisterClass *> InputRC =
  6918. TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
  6919. MatchingOpInfo.ConstraintVT);
  6920. if ((OpInfo.ConstraintVT.isInteger() !=
  6921. MatchingOpInfo.ConstraintVT.isInteger()) ||
  6922. (MatchRC.second != InputRC.second)) {
  6923. // FIXME: error out in a more elegant fashion
  6924. report_fatal_error("Unsupported asm: input constraint"
  6925. " with a matching output constraint of"
  6926. " incompatible type!");
  6927. }
  6928. MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
  6929. }
  6930. /// Get a direct memory input to behave well as an indirect operand.
  6931. /// This may introduce stores, hence the need for a \p Chain.
  6932. /// \return The (possibly updated) chain.
  6933. static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
  6934. SDISelAsmOperandInfo &OpInfo,
  6935. SelectionDAG &DAG) {
  6936. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6937. // If we don't have an indirect input, put it in the constpool if we can,
  6938. // otherwise spill it to a stack slot.
  6939. // TODO: This isn't quite right. We need to handle these according to
  6940. // the addressing mode that the constraint wants. Also, this may take
  6941. // an additional register for the computation and we don't want that
  6942. // either.
  6943. // If the operand is a float, integer, or vector constant, spill to a
  6944. // constant pool entry to get its address.
  6945. const Value *OpVal = OpInfo.CallOperandVal;
  6946. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  6947. isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
  6948. OpInfo.CallOperand = DAG.getConstantPool(
  6949. cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
  6950. return Chain;
  6951. }
  6952. // Otherwise, create a stack slot and emit a store to it before the asm.
  6953. Type *Ty = OpVal->getType();
  6954. auto &DL = DAG.getDataLayout();
  6955. uint64_t TySize = DL.getTypeAllocSize(Ty);
  6956. unsigned Align = DL.getPrefTypeAlignment(Ty);
  6957. MachineFunction &MF = DAG.getMachineFunction();
  6958. int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  6959. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
  6960. Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
  6961. MachinePointerInfo::getFixedStack(MF, SSFI),
  6962. TLI.getMemValueType(DL, Ty));
  6963. OpInfo.CallOperand = StackSlot;
  6964. return Chain;
  6965. }
  6966. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  6967. /// specified operand. We prefer to assign virtual registers, to allow the
  6968. /// register allocator to handle the assignment process. However, if the asm
  6969. /// uses features that we can't model on machineinstrs, we have SDISel do the
  6970. /// allocation. This produces generally horrible, but correct, code.
  6971. ///
  6972. /// OpInfo describes the operand
  6973. /// RefOpInfo describes the matching operand if any, the operand otherwise
  6974. static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
  6975. SDISelAsmOperandInfo &OpInfo,
  6976. SDISelAsmOperandInfo &RefOpInfo) {
  6977. LLVMContext &Context = *DAG.getContext();
  6978. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  6979. MachineFunction &MF = DAG.getMachineFunction();
  6980. SmallVector<unsigned, 4> Regs;
  6981. const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
  6982. // No work to do for memory operations.
  6983. if (OpInfo.ConstraintType == TargetLowering::C_Memory)
  6984. return;
  6985. // If this is a constraint for a single physreg, or a constraint for a
  6986. // register class, find it.
  6987. unsigned AssignedReg;
  6988. const TargetRegisterClass *RC;
  6989. std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
  6990. &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
  6991. // RC is unset only on failure. Return immediately.
  6992. if (!RC)
  6993. return;
  6994. // Get the actual register value type. This is important, because the user
  6995. // may have asked for (e.g.) the AX register in i32 type. We need to
  6996. // remember that AX is actually i16 to get the right extension.
  6997. const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
  6998. if (OpInfo.ConstraintVT != MVT::Other) {
  6999. // If this is an FP operand in an integer register (or visa versa), or more
  7000. // generally if the operand value disagrees with the register class we plan
  7001. // to stick it in, fix the operand type.
  7002. //
  7003. // If this is an input value, the bitcast to the new type is done now.
  7004. // Bitcast for output value is done at the end of visitInlineAsm().
  7005. if ((OpInfo.Type == InlineAsm::isOutput ||
  7006. OpInfo.Type == InlineAsm::isInput) &&
  7007. !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
  7008. // Try to convert to the first EVT that the reg class contains. If the
  7009. // types are identical size, use a bitcast to convert (e.g. two differing
  7010. // vector types). Note: output bitcast is done at the end of
  7011. // visitInlineAsm().
  7012. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  7013. // Exclude indirect inputs while they are unsupported because the code
  7014. // to perform the load is missing and thus OpInfo.CallOperand still
  7015. // refers to the input address rather than the pointed-to value.
  7016. if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
  7017. OpInfo.CallOperand =
  7018. DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
  7019. OpInfo.ConstraintVT = RegVT;
  7020. // If the operand is an FP value and we want it in integer registers,
  7021. // use the corresponding integer type. This turns an f64 value into
  7022. // i64, which can be passed with two i32 values on a 32-bit machine.
  7023. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  7024. MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
  7025. if (OpInfo.Type == InlineAsm::isInput)
  7026. OpInfo.CallOperand =
  7027. DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
  7028. OpInfo.ConstraintVT = VT;
  7029. }
  7030. }
  7031. }
  7032. // No need to allocate a matching input constraint since the constraint it's
  7033. // matching to has already been allocated.
  7034. if (OpInfo.isMatchingInputConstraint())
  7035. return;
  7036. EVT ValueVT = OpInfo.ConstraintVT;
  7037. if (OpInfo.ConstraintVT == MVT::Other)
  7038. ValueVT = RegVT;
  7039. // Initialize NumRegs.
  7040. unsigned NumRegs = 1;
  7041. if (OpInfo.ConstraintVT != MVT::Other)
  7042. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  7043. // If this is a constraint for a specific physical register, like {r17},
  7044. // assign it now.
  7045. // If this associated to a specific register, initialize iterator to correct
  7046. // place. If virtual, make sure we have enough registers
  7047. // Initialize iterator if necessary
  7048. TargetRegisterClass::iterator I = RC->begin();
  7049. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  7050. // Do not check for single registers.
  7051. if (AssignedReg) {
  7052. for (; *I != AssignedReg; ++I)
  7053. assert(I != RC->end() && "AssignedReg should be member of RC");
  7054. }
  7055. for (; NumRegs; --NumRegs, ++I) {
  7056. assert(I != RC->end() && "Ran out of registers to allocate!");
  7057. Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
  7058. Regs.push_back(R);
  7059. }
  7060. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  7061. }
  7062. static unsigned
  7063. findMatchingInlineAsmOperand(unsigned OperandNo,
  7064. const std::vector<SDValue> &AsmNodeOperands) {
  7065. // Scan until we find the definition we already emitted of this operand.
  7066. unsigned CurOp = InlineAsm::Op_FirstOperand;
  7067. for (; OperandNo; --OperandNo) {
  7068. // Advance to the next operand.
  7069. unsigned OpFlag =
  7070. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7071. assert((InlineAsm::isRegDefKind(OpFlag) ||
  7072. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  7073. InlineAsm::isMemKind(OpFlag)) &&
  7074. "Skipped past definitions?");
  7075. CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
  7076. }
  7077. return CurOp;
  7078. }
  7079. namespace {
  7080. class ExtraFlags {
  7081. unsigned Flags = 0;
  7082. public:
  7083. explicit ExtraFlags(ImmutableCallSite CS) {
  7084. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7085. if (IA->hasSideEffects())
  7086. Flags |= InlineAsm::Extra_HasSideEffects;
  7087. if (IA->isAlignStack())
  7088. Flags |= InlineAsm::Extra_IsAlignStack;
  7089. if (CS.isConvergent())
  7090. Flags |= InlineAsm::Extra_IsConvergent;
  7091. Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
  7092. }
  7093. void update(const TargetLowering::AsmOperandInfo &OpInfo) {
  7094. // Ideally, we would only check against memory constraints. However, the
  7095. // meaning of an Other constraint can be target-specific and we can't easily
  7096. // reason about it. Therefore, be conservative and set MayLoad/MayStore
  7097. // for Other constraints as well.
  7098. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7099. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7100. if (OpInfo.Type == InlineAsm::isInput)
  7101. Flags |= InlineAsm::Extra_MayLoad;
  7102. else if (OpInfo.Type == InlineAsm::isOutput)
  7103. Flags |= InlineAsm::Extra_MayStore;
  7104. else if (OpInfo.Type == InlineAsm::isClobber)
  7105. Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
  7106. }
  7107. }
  7108. unsigned get() const { return Flags; }
  7109. };
  7110. } // end anonymous namespace
  7111. /// visitInlineAsm - Handle a call to an InlineAsm object.
  7112. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  7113. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  7114. /// ConstraintOperands - Information about all of the constraints.
  7115. SDISelAsmOperandInfoVector ConstraintOperands;
  7116. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7117. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
  7118. DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
  7119. // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
  7120. // AsmDialect, MayLoad, MayStore).
  7121. bool HasSideEffect = IA->hasSideEffects();
  7122. ExtraFlags ExtraInfo(CS);
  7123. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  7124. unsigned ResNo = 0; // ResNo - The result number of the next output.
  7125. for (auto &T : TargetConstraints) {
  7126. ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
  7127. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  7128. // Compute the value type for each operand.
  7129. if (OpInfo.Type == InlineAsm::isInput ||
  7130. (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
  7131. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  7132. // Process the call argument. BasicBlocks are labels, currently appearing
  7133. // only in asm's.
  7134. const Instruction *I = CS.getInstruction();
  7135. if (isa<CallBrInst>(I) &&
  7136. (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
  7137. cast<CallBrInst>(I)->getNumIndirectDests())) {
  7138. const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
  7139. EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
  7140. OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
  7141. } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  7142. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  7143. } else {
  7144. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  7145. }
  7146. OpInfo.ConstraintVT =
  7147. OpInfo
  7148. .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
  7149. .getSimpleVT();
  7150. } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
  7151. // The return value of the call is this value. As such, there is no
  7152. // corresponding argument.
  7153. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7154. if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
  7155. OpInfo.ConstraintVT = TLI.getSimpleValueType(
  7156. DAG.getDataLayout(), STy->getElementType(ResNo));
  7157. } else {
  7158. assert(ResNo == 0 && "Asm only has one result!");
  7159. OpInfo.ConstraintVT =
  7160. TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
  7161. }
  7162. ++ResNo;
  7163. } else {
  7164. OpInfo.ConstraintVT = MVT::Other;
  7165. }
  7166. if (!HasSideEffect)
  7167. HasSideEffect = OpInfo.hasMemory(TLI);
  7168. // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
  7169. // FIXME: Could we compute this on OpInfo rather than T?
  7170. // Compute the constraint code and ConstraintType to use.
  7171. TLI.ComputeConstraintToUse(T, SDValue());
  7172. if (T.ConstraintType == TargetLowering::C_Immediate &&
  7173. OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
  7174. // We've delayed emitting a diagnostic like the "n" constraint because
  7175. // inlining could cause an integer showing up.
  7176. return emitInlineAsmError(
  7177. CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
  7178. "integer constant expression");
  7179. ExtraInfo.update(T);
  7180. }
  7181. // We won't need to flush pending loads if this asm doesn't touch
  7182. // memory and is nonvolatile.
  7183. SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
  7184. bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
  7185. if (IsCallBr) {
  7186. // If this is a callbr we need to flush pending exports since inlineasm_br
  7187. // is a terminator. We need to do this before nodes are glued to
  7188. // the inlineasm_br node.
  7189. Chain = getControlRoot();
  7190. }
  7191. // Second pass over the constraints: compute which constraint option to use.
  7192. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7193. // If this is an output operand with a matching input operand, look up the
  7194. // matching input. If their types mismatch, e.g. one is an integer, the
  7195. // other is floating point, or their sizes are different, flag it as an
  7196. // error.
  7197. if (OpInfo.hasMatchingInput()) {
  7198. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  7199. patchMatchingInput(OpInfo, Input, DAG);
  7200. }
  7201. // Compute the constraint code and ConstraintType to use.
  7202. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  7203. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7204. OpInfo.Type == InlineAsm::isClobber)
  7205. continue;
  7206. // If this is a memory input, and if the operand is not indirect, do what we
  7207. // need to provide an address for the memory input.
  7208. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  7209. !OpInfo.isIndirect) {
  7210. assert((OpInfo.isMultipleAlternative ||
  7211. (OpInfo.Type == InlineAsm::isInput)) &&
  7212. "Can only indirectify direct input operands!");
  7213. // Memory operands really want the address of the value.
  7214. Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
  7215. // There is no longer a Value* corresponding to this operand.
  7216. OpInfo.CallOperandVal = nullptr;
  7217. // It is now an indirect operand.
  7218. OpInfo.isIndirect = true;
  7219. }
  7220. }
  7221. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  7222. std::vector<SDValue> AsmNodeOperands;
  7223. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  7224. AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
  7225. IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
  7226. // If we have a !srcloc metadata node associated with it, we want to attach
  7227. // this to the ultimately generated inline asm machineinstr. To do this, we
  7228. // pass in the third operand as this (potentially null) inline asm MDNode.
  7229. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  7230. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  7231. // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
  7232. // bits as operand 3.
  7233. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7234. ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7235. // Third pass: Loop over operands to prepare DAG-level operands.. As part of
  7236. // this, assign virtual and physical registers for inputs and otput.
  7237. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7238. // Assign Registers.
  7239. SDISelAsmOperandInfo &RefOpInfo =
  7240. OpInfo.isMatchingInputConstraint()
  7241. ? ConstraintOperands[OpInfo.getMatchedOperand()]
  7242. : OpInfo;
  7243. GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
  7244. switch (OpInfo.Type) {
  7245. case InlineAsm::isOutput:
  7246. if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
  7247. ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7248. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7249. OpInfo.isIndirect)) {
  7250. unsigned ConstraintID =
  7251. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7252. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7253. "Failed to convert memory constraint code to constraint id.");
  7254. // Add information to the INLINEASM node to know about this output.
  7255. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7256. OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
  7257. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
  7258. MVT::i32));
  7259. AsmNodeOperands.push_back(OpInfo.CallOperand);
  7260. break;
  7261. } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7262. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7263. !OpInfo.isIndirect) ||
  7264. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7265. OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
  7266. // Otherwise, this outputs to a register (directly for C_Register /
  7267. // C_RegisterClass, and a target-defined fashion for
  7268. // C_Immediate/C_Other). Find a register that we can use.
  7269. if (OpInfo.AssignedRegs.Regs.empty()) {
  7270. emitInlineAsmError(
  7271. CS, "couldn't allocate output register for constraint '" +
  7272. Twine(OpInfo.ConstraintCode) + "'");
  7273. return;
  7274. }
  7275. // Add information to the INLINEASM node to know that this register is
  7276. // set.
  7277. OpInfo.AssignedRegs.AddInlineAsmOperands(
  7278. OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
  7279. : InlineAsm::Kind_RegDef,
  7280. false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
  7281. }
  7282. break;
  7283. case InlineAsm::isInput: {
  7284. SDValue InOperandVal = OpInfo.CallOperand;
  7285. if (OpInfo.isMatchingInputConstraint()) {
  7286. // If this is required to match an output register we have already set,
  7287. // just use its register.
  7288. auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
  7289. AsmNodeOperands);
  7290. unsigned OpFlag =
  7291. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  7292. if (InlineAsm::isRegDefKind(OpFlag) ||
  7293. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  7294. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  7295. if (OpInfo.isIndirect) {
  7296. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  7297. emitInlineAsmError(CS, "inline asm not supported yet:"
  7298. " don't know how to handle tied "
  7299. "indirect register inputs");
  7300. return;
  7301. }
  7302. MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
  7303. SmallVector<unsigned, 4> Regs;
  7304. if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
  7305. unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
  7306. MachineRegisterInfo &RegInfo =
  7307. DAG.getMachineFunction().getRegInfo();
  7308. for (unsigned i = 0; i != NumRegs; ++i)
  7309. Regs.push_back(RegInfo.createVirtualRegister(RC));
  7310. } else {
  7311. emitInlineAsmError(CS, "inline asm error: This value type register "
  7312. "class is not natively supported!");
  7313. return;
  7314. }
  7315. RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
  7316. SDLoc dl = getCurSDLoc();
  7317. // Use the produced MatchedRegs object to
  7318. MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
  7319. CS.getInstruction());
  7320. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  7321. true, OpInfo.getMatchedOperand(), dl,
  7322. DAG, AsmNodeOperands);
  7323. break;
  7324. }
  7325. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  7326. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  7327. "Unexpected number of operands");
  7328. // Add information to the INLINEASM node to know about this input.
  7329. // See InlineAsm.h isUseOperandTiedToDef.
  7330. OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
  7331. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  7332. OpInfo.getMatchedOperand());
  7333. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7334. OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7335. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  7336. break;
  7337. }
  7338. // Treat indirect 'X' constraint as memory.
  7339. if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7340. OpInfo.ConstraintType == TargetLowering::C_Other) &&
  7341. OpInfo.isIndirect)
  7342. OpInfo.ConstraintType = TargetLowering::C_Memory;
  7343. if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
  7344. OpInfo.ConstraintType == TargetLowering::C_Other) {
  7345. std::vector<SDValue> Ops;
  7346. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
  7347. Ops, DAG);
  7348. if (Ops.empty()) {
  7349. if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
  7350. if (isa<ConstantSDNode>(InOperandVal)) {
  7351. emitInlineAsmError(CS, "value out of range for constraint '" +
  7352. Twine(OpInfo.ConstraintCode) + "'");
  7353. return;
  7354. }
  7355. emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
  7356. Twine(OpInfo.ConstraintCode) + "'");
  7357. return;
  7358. }
  7359. // Add information to the INLINEASM node to know about this input.
  7360. unsigned ResOpType =
  7361. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  7362. AsmNodeOperands.push_back(DAG.getTargetConstant(
  7363. ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
  7364. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  7365. break;
  7366. }
  7367. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  7368. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  7369. assert(InOperandVal.getValueType() ==
  7370. TLI.getPointerTy(DAG.getDataLayout()) &&
  7371. "Memory operands expect pointer values");
  7372. unsigned ConstraintID =
  7373. TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
  7374. assert(ConstraintID != InlineAsm::Constraint_Unknown &&
  7375. "Failed to convert memory constraint code to constraint id.");
  7376. // Add information to the INLINEASM node to know about this input.
  7377. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  7378. ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
  7379. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  7380. getCurSDLoc(),
  7381. MVT::i32));
  7382. AsmNodeOperands.push_back(InOperandVal);
  7383. break;
  7384. }
  7385. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  7386. OpInfo.ConstraintType == TargetLowering::C_Register ||
  7387. OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
  7388. "Unknown constraint type!");
  7389. // TODO: Support this.
  7390. if (OpInfo.isIndirect) {
  7391. emitInlineAsmError(
  7392. CS, "Don't know how to handle indirect register inputs yet "
  7393. "for constraint '" +
  7394. Twine(OpInfo.ConstraintCode) + "'");
  7395. return;
  7396. }
  7397. // Copy the input into the appropriate registers.
  7398. if (OpInfo.AssignedRegs.Regs.empty()) {
  7399. emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
  7400. Twine(OpInfo.ConstraintCode) + "'");
  7401. return;
  7402. }
  7403. SDLoc dl = getCurSDLoc();
  7404. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
  7405. Chain, &Flag, CS.getInstruction());
  7406. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  7407. dl, DAG, AsmNodeOperands);
  7408. break;
  7409. }
  7410. case InlineAsm::isClobber:
  7411. // Add the clobbered value to the operand list, so that the register
  7412. // allocator is aware that the physreg got clobbered.
  7413. if (!OpInfo.AssignedRegs.Regs.empty())
  7414. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
  7415. false, 0, getCurSDLoc(), DAG,
  7416. AsmNodeOperands);
  7417. break;
  7418. }
  7419. }
  7420. // Finish up input operands. Set the input chain and add the flag last.
  7421. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  7422. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  7423. unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
  7424. Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
  7425. DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
  7426. Flag = Chain.getValue(1);
  7427. // Do additional work to generate outputs.
  7428. SmallVector<EVT, 1> ResultVTs;
  7429. SmallVector<SDValue, 1> ResultValues;
  7430. SmallVector<SDValue, 8> OutChains;
  7431. llvm::Type *CSResultType = CS.getType();
  7432. ArrayRef<Type *> ResultTypes;
  7433. if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
  7434. ResultTypes = StructResult->elements();
  7435. else if (!CSResultType->isVoidTy())
  7436. ResultTypes = makeArrayRef(CSResultType);
  7437. auto CurResultType = ResultTypes.begin();
  7438. auto handleRegAssign = [&](SDValue V) {
  7439. assert(CurResultType != ResultTypes.end() && "Unexpected value");
  7440. assert((*CurResultType)->isSized() && "Unexpected unsized type");
  7441. EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
  7442. ++CurResultType;
  7443. // If the type of the inline asm call site return value is different but has
  7444. // same size as the type of the asm output bitcast it. One example of this
  7445. // is for vectors with different width / number of elements. This can
  7446. // happen for register classes that can contain multiple different value
  7447. // types. The preg or vreg allocated may not have the same VT as was
  7448. // expected.
  7449. //
  7450. // This can also happen for a return value that disagrees with the register
  7451. // class it is put in, eg. a double in a general-purpose register on a
  7452. // 32-bit machine.
  7453. if (ResultVT != V.getValueType() &&
  7454. ResultVT.getSizeInBits() == V.getValueSizeInBits())
  7455. V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
  7456. else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
  7457. V.getValueType().isInteger()) {
  7458. // If a result value was tied to an input value, the computed result
  7459. // may have a wider width than the expected result. Extract the
  7460. // relevant portion.
  7461. V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
  7462. }
  7463. assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
  7464. ResultVTs.push_back(ResultVT);
  7465. ResultValues.push_back(V);
  7466. };
  7467. // Deal with output operands.
  7468. for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
  7469. if (OpInfo.Type == InlineAsm::isOutput) {
  7470. SDValue Val;
  7471. // Skip trivial output operands.
  7472. if (OpInfo.AssignedRegs.Regs.empty())
  7473. continue;
  7474. switch (OpInfo.ConstraintType) {
  7475. case TargetLowering::C_Register:
  7476. case TargetLowering::C_RegisterClass:
  7477. Val = OpInfo.AssignedRegs.getCopyFromRegs(
  7478. DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
  7479. break;
  7480. case TargetLowering::C_Immediate:
  7481. case TargetLowering::C_Other:
  7482. Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
  7483. OpInfo, DAG);
  7484. break;
  7485. case TargetLowering::C_Memory:
  7486. break; // Already handled.
  7487. case TargetLowering::C_Unknown:
  7488. assert(false && "Unexpected unknown constraint");
  7489. }
  7490. // Indirect output manifest as stores. Record output chains.
  7491. if (OpInfo.isIndirect) {
  7492. const Value *Ptr = OpInfo.CallOperandVal;
  7493. assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
  7494. SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
  7495. MachinePointerInfo(Ptr));
  7496. OutChains.push_back(Store);
  7497. } else {
  7498. // generate CopyFromRegs to associated registers.
  7499. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  7500. if (Val.getOpcode() == ISD::MERGE_VALUES) {
  7501. for (const SDValue &V : Val->op_values())
  7502. handleRegAssign(V);
  7503. } else
  7504. handleRegAssign(Val);
  7505. }
  7506. }
  7507. }
  7508. // Set results.
  7509. if (!ResultValues.empty()) {
  7510. assert(CurResultType == ResultTypes.end() &&
  7511. "Mismatch in number of ResultTypes");
  7512. assert(ResultValues.size() == ResultTypes.size() &&
  7513. "Mismatch in number of output operands in asm result");
  7514. SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
  7515. DAG.getVTList(ResultVTs), ResultValues);
  7516. setValue(CS.getInstruction(), V);
  7517. }
  7518. // Collect store chains.
  7519. if (!OutChains.empty())
  7520. Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
  7521. // Only Update Root if inline assembly has a memory effect.
  7522. if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
  7523. DAG.setRoot(Chain);
  7524. }
  7525. void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
  7526. const Twine &Message) {
  7527. LLVMContext &Ctx = *DAG.getContext();
  7528. Ctx.emitError(CS.getInstruction(), Message);
  7529. // Make sure we leave the DAG in a valid state
  7530. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7531. SmallVector<EVT, 1> ValueVTs;
  7532. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7533. if (ValueVTs.empty())
  7534. return;
  7535. SmallVector<SDValue, 1> Ops;
  7536. for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
  7537. Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
  7538. setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
  7539. }
  7540. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  7541. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
  7542. MVT::Other, getRoot(),
  7543. getValue(I.getArgOperand(0)),
  7544. DAG.getSrcValue(I.getArgOperand(0))));
  7545. }
  7546. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  7547. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7548. const DataLayout &DL = DAG.getDataLayout();
  7549. SDValue V = DAG.getVAArg(
  7550. TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
  7551. getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
  7552. DL.getABITypeAlignment(I.getType()));
  7553. DAG.setRoot(V.getValue(1));
  7554. if (I.getType()->isPointerTy())
  7555. V = DAG.getPtrExtOrTrunc(
  7556. V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
  7557. setValue(&I, V);
  7558. }
  7559. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  7560. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
  7561. MVT::Other, getRoot(),
  7562. getValue(I.getArgOperand(0)),
  7563. DAG.getSrcValue(I.getArgOperand(0))));
  7564. }
  7565. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  7566. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
  7567. MVT::Other, getRoot(),
  7568. getValue(I.getArgOperand(0)),
  7569. getValue(I.getArgOperand(1)),
  7570. DAG.getSrcValue(I.getArgOperand(0)),
  7571. DAG.getSrcValue(I.getArgOperand(1))));
  7572. }
  7573. SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
  7574. const Instruction &I,
  7575. SDValue Op) {
  7576. const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
  7577. if (!Range)
  7578. return Op;
  7579. ConstantRange CR = getConstantRangeFromMetadata(*Range);
  7580. if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
  7581. return Op;
  7582. APInt Lo = CR.getUnsignedMin();
  7583. if (!Lo.isMinValue())
  7584. return Op;
  7585. APInt Hi = CR.getUnsignedMax();
  7586. unsigned Bits = std::max(Hi.getActiveBits(),
  7587. static_cast<unsigned>(IntegerType::MIN_INT_BITS));
  7588. EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
  7589. SDLoc SL = getCurSDLoc();
  7590. SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
  7591. DAG.getValueType(SmallVT));
  7592. unsigned NumVals = Op.getNode()->getNumValues();
  7593. if (NumVals == 1)
  7594. return ZExt;
  7595. SmallVector<SDValue, 4> Ops;
  7596. Ops.push_back(ZExt);
  7597. for (unsigned I = 1; I != NumVals; ++I)
  7598. Ops.push_back(Op.getValue(I));
  7599. return DAG.getMergeValues(Ops, SL);
  7600. }
  7601. /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
  7602. /// the call being lowered.
  7603. ///
  7604. /// This is a helper for lowering intrinsics that follow a target calling
  7605. /// convention or require stack pointer adjustment. Only a subset of the
  7606. /// intrinsic's operands need to participate in the calling convention.
  7607. void SelectionDAGBuilder::populateCallLoweringInfo(
  7608. TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
  7609. unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
  7610. bool IsPatchPoint) {
  7611. TargetLowering::ArgListTy Args;
  7612. Args.reserve(NumArgs);
  7613. // Populate the argument list.
  7614. // Attributes for args start at offset 1, after the return attribute.
  7615. for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
  7616. ArgI != ArgE; ++ArgI) {
  7617. const Value *V = Call->getOperand(ArgI);
  7618. assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
  7619. TargetLowering::ArgListEntry Entry;
  7620. Entry.Node = getValue(V);
  7621. Entry.Ty = V->getType();
  7622. Entry.setAttributes(Call, ArgI);
  7623. Args.push_back(Entry);
  7624. }
  7625. CLI.setDebugLoc(getCurSDLoc())
  7626. .setChain(getRoot())
  7627. .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
  7628. .setDiscardResult(Call->use_empty())
  7629. .setIsPatchPoint(IsPatchPoint);
  7630. }
  7631. /// Add a stack map intrinsic call's live variable operands to a stackmap
  7632. /// or patchpoint target node's operand list.
  7633. ///
  7634. /// Constants are converted to TargetConstants purely as an optimization to
  7635. /// avoid constant materialization and register allocation.
  7636. ///
  7637. /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
  7638. /// generate addess computation nodes, and so FinalizeISel can convert the
  7639. /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
  7640. /// address materialization and register allocation, but may also be required
  7641. /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
  7642. /// alloca in the entry block, then the runtime may assume that the alloca's
  7643. /// StackMap location can be read immediately after compilation and that the
  7644. /// location is valid at any point during execution (this is similar to the
  7645. /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
  7646. /// only available in a register, then the runtime would need to trap when
  7647. /// execution reaches the StackMap in order to read the alloca's location.
  7648. static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
  7649. const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
  7650. SelectionDAGBuilder &Builder) {
  7651. for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
  7652. SDValue OpVal = Builder.getValue(CS.getArgument(i));
  7653. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
  7654. Ops.push_back(
  7655. Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
  7656. Ops.push_back(
  7657. Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
  7658. } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
  7659. const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
  7660. Ops.push_back(Builder.DAG.getTargetFrameIndex(
  7661. FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
  7662. } else
  7663. Ops.push_back(OpVal);
  7664. }
  7665. }
  7666. /// Lower llvm.experimental.stackmap directly to its target opcode.
  7667. void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
  7668. // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
  7669. // [live variables...])
  7670. assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
  7671. SDValue Chain, InFlag, Callee, NullPtr;
  7672. SmallVector<SDValue, 32> Ops;
  7673. SDLoc DL = getCurSDLoc();
  7674. Callee = getValue(CI.getCalledValue());
  7675. NullPtr = DAG.getIntPtrConstant(0, DL, true);
  7676. // The stackmap intrinsic only records the live variables (the arguemnts
  7677. // passed to it) and emits NOPS (if requested). Unlike the patchpoint
  7678. // intrinsic, this won't be lowered to a function call. This means we don't
  7679. // have to worry about calling conventions and target specific lowering code.
  7680. // Instead we perform the call lowering right here.
  7681. //
  7682. // chain, flag = CALLSEQ_START(chain, 0, 0)
  7683. // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
  7684. // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
  7685. //
  7686. Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
  7687. InFlag = Chain.getValue(1);
  7688. // Add the <id> and <numBytes> constants.
  7689. SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
  7690. Ops.push_back(DAG.getTargetConstant(
  7691. cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
  7692. SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
  7693. Ops.push_back(DAG.getTargetConstant(
  7694. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
  7695. MVT::i32));
  7696. // Push live variables for the stack map.
  7697. addStackMapLiveVars(&CI, 2, DL, Ops, *this);
  7698. // We are not pushing any register mask info here on the operands list,
  7699. // because the stackmap doesn't clobber anything.
  7700. // Push the chain and the glue flag.
  7701. Ops.push_back(Chain);
  7702. Ops.push_back(InFlag);
  7703. // Create the STACKMAP node.
  7704. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7705. SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
  7706. Chain = SDValue(SM, 0);
  7707. InFlag = Chain.getValue(1);
  7708. Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
  7709. // Stackmaps don't generate values, so nothing goes into the NodeMap.
  7710. // Set the root to the target-lowered call chain.
  7711. DAG.setRoot(Chain);
  7712. // Inform the Frame Information that we have a stackmap in this function.
  7713. FuncInfo.MF->getFrameInfo().setHasStackMap();
  7714. }
  7715. /// Lower llvm.experimental.patchpoint directly to its target opcode.
  7716. void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
  7717. const BasicBlock *EHPadBB) {
  7718. // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
  7719. // i32 <numBytes>,
  7720. // i8* <target>,
  7721. // i32 <numArgs>,
  7722. // [Args...],
  7723. // [live variables...])
  7724. CallingConv::ID CC = CS.getCallingConv();
  7725. bool IsAnyRegCC = CC == CallingConv::AnyReg;
  7726. bool HasDef = !CS->getType()->isVoidTy();
  7727. SDLoc dl = getCurSDLoc();
  7728. SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
  7729. // Handle immediate and symbolic callees.
  7730. if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
  7731. Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
  7732. /*isTarget=*/true);
  7733. else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
  7734. Callee = DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
  7735. SDLoc(SymbolicCallee),
  7736. SymbolicCallee->getValueType(0));
  7737. // Get the real number of arguments participating in the call <numArgs>
  7738. SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
  7739. unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
  7740. // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
  7741. // Intrinsics include all meta-operands up to but not including CC.
  7742. unsigned NumMetaOpers = PatchPointOpers::CCPos;
  7743. assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
  7744. "Not enough arguments provided to the patchpoint intrinsic");
  7745. // For AnyRegCC the arguments are lowered later on manually.
  7746. unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
  7747. Type *ReturnTy =
  7748. IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
  7749. TargetLowering::CallLoweringInfo CLI(DAG);
  7750. populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
  7751. NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
  7752. std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
  7753. SDNode *CallEnd = Result.second.getNode();
  7754. if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
  7755. CallEnd = CallEnd->getOperand(0).getNode();
  7756. /// Get a call instruction from the call sequence chain.
  7757. /// Tail calls are not allowed.
  7758. assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
  7759. "Expected a callseq node.");
  7760. SDNode *Call = CallEnd->getOperand(0).getNode();
  7761. bool HasGlue = Call->getGluedNode();
  7762. // Replace the target specific call node with the patchable intrinsic.
  7763. SmallVector<SDValue, 8> Ops;
  7764. // Add the <id> and <numBytes> constants.
  7765. SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
  7766. Ops.push_back(DAG.getTargetConstant(
  7767. cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
  7768. SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
  7769. Ops.push_back(DAG.getTargetConstant(
  7770. cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
  7771. MVT::i32));
  7772. // Add the callee.
  7773. Ops.push_back(Callee);
  7774. // Adjust <numArgs> to account for any arguments that have been passed on the
  7775. // stack instead.
  7776. // Call Node: Chain, Target, {Args}, RegMask, [Glue]
  7777. unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
  7778. NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
  7779. Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
  7780. // Add the calling convention
  7781. Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
  7782. // Add the arguments we omitted previously. The register allocator should
  7783. // place these in any free register.
  7784. if (IsAnyRegCC)
  7785. for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
  7786. Ops.push_back(getValue(CS.getArgument(i)));
  7787. // Push the arguments from the call instruction up to the register mask.
  7788. SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
  7789. Ops.append(Call->op_begin() + 2, e);
  7790. // Push live variables for the stack map.
  7791. addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
  7792. // Push the register mask info.
  7793. if (HasGlue)
  7794. Ops.push_back(*(Call->op_end()-2));
  7795. else
  7796. Ops.push_back(*(Call->op_end()-1));
  7797. // Push the chain (this is originally the first operand of the call, but
  7798. // becomes now the last or second to last operand).
  7799. Ops.push_back(*(Call->op_begin()));
  7800. // Push the glue flag (last operand).
  7801. if (HasGlue)
  7802. Ops.push_back(*(Call->op_end()-1));
  7803. SDVTList NodeTys;
  7804. if (IsAnyRegCC && HasDef) {
  7805. // Create the return types based on the intrinsic definition
  7806. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7807. SmallVector<EVT, 3> ValueVTs;
  7808. ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
  7809. assert(ValueVTs.size() == 1 && "Expected only one return value type.");
  7810. // There is always a chain and a glue type at the end
  7811. ValueVTs.push_back(MVT::Other);
  7812. ValueVTs.push_back(MVT::Glue);
  7813. NodeTys = DAG.getVTList(ValueVTs);
  7814. } else
  7815. NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  7816. // Replace the target specific call node with a PATCHPOINT node.
  7817. MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
  7818. dl, NodeTys, Ops);
  7819. // Update the NodeMap.
  7820. if (HasDef) {
  7821. if (IsAnyRegCC)
  7822. setValue(CS.getInstruction(), SDValue(MN, 0));
  7823. else
  7824. setValue(CS.getInstruction(), Result.first);
  7825. }
  7826. // Fixup the consumers of the intrinsic. The chain and glue may be used in the
  7827. // call sequence. Furthermore the location of the chain and glue can change
  7828. // when the AnyReg calling convention is used and the intrinsic returns a
  7829. // value.
  7830. if (IsAnyRegCC && HasDef) {
  7831. SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
  7832. SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
  7833. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7834. } else
  7835. DAG.ReplaceAllUsesWith(Call, MN);
  7836. DAG.DeleteNode(Call);
  7837. // Inform the Frame Information that we have a patchpoint in this function.
  7838. FuncInfo.MF->getFrameInfo().setHasPatchPoint();
  7839. }
  7840. void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
  7841. unsigned Intrinsic) {
  7842. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7843. SDValue Op1 = getValue(I.getArgOperand(0));
  7844. SDValue Op2;
  7845. if (I.getNumArgOperands() > 1)
  7846. Op2 = getValue(I.getArgOperand(1));
  7847. SDLoc dl = getCurSDLoc();
  7848. EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
  7849. SDValue Res;
  7850. FastMathFlags FMF;
  7851. if (isa<FPMathOperator>(I))
  7852. FMF = I.getFastMathFlags();
  7853. switch (Intrinsic) {
  7854. case Intrinsic::experimental_vector_reduce_v2_fadd:
  7855. if (FMF.allowReassoc())
  7856. Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
  7857. DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
  7858. else
  7859. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
  7860. break;
  7861. case Intrinsic::experimental_vector_reduce_v2_fmul:
  7862. if (FMF.allowReassoc())
  7863. Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
  7864. DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
  7865. else
  7866. Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
  7867. break;
  7868. case Intrinsic::experimental_vector_reduce_add:
  7869. Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
  7870. break;
  7871. case Intrinsic::experimental_vector_reduce_mul:
  7872. Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
  7873. break;
  7874. case Intrinsic::experimental_vector_reduce_and:
  7875. Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
  7876. break;
  7877. case Intrinsic::experimental_vector_reduce_or:
  7878. Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
  7879. break;
  7880. case Intrinsic::experimental_vector_reduce_xor:
  7881. Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
  7882. break;
  7883. case Intrinsic::experimental_vector_reduce_smax:
  7884. Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
  7885. break;
  7886. case Intrinsic::experimental_vector_reduce_smin:
  7887. Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
  7888. break;
  7889. case Intrinsic::experimental_vector_reduce_umax:
  7890. Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
  7891. break;
  7892. case Intrinsic::experimental_vector_reduce_umin:
  7893. Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
  7894. break;
  7895. case Intrinsic::experimental_vector_reduce_fmax:
  7896. Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
  7897. break;
  7898. case Intrinsic::experimental_vector_reduce_fmin:
  7899. Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
  7900. break;
  7901. default:
  7902. llvm_unreachable("Unhandled vector reduce intrinsic");
  7903. }
  7904. setValue(&I, Res);
  7905. }
  7906. /// Returns an AttributeList representing the attributes applied to the return
  7907. /// value of the given call.
  7908. static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
  7909. SmallVector<Attribute::AttrKind, 2> Attrs;
  7910. if (CLI.RetSExt)
  7911. Attrs.push_back(Attribute::SExt);
  7912. if (CLI.RetZExt)
  7913. Attrs.push_back(Attribute::ZExt);
  7914. if (CLI.IsInReg)
  7915. Attrs.push_back(Attribute::InReg);
  7916. return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
  7917. Attrs);
  7918. }
  7919. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  7920. /// implementation, which just calls LowerCall.
  7921. /// FIXME: When all targets are
  7922. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  7923. std::pair<SDValue, SDValue>
  7924. TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
  7925. // Handle the incoming return values from the call.
  7926. CLI.Ins.clear();
  7927. Type *OrigRetTy = CLI.RetTy;
  7928. SmallVector<EVT, 4> RetTys;
  7929. SmallVector<uint64_t, 4> Offsets;
  7930. auto &DL = CLI.DAG.getDataLayout();
  7931. ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
  7932. if (CLI.IsPostTypeLegalization) {
  7933. // If we are lowering a libcall after legalization, split the return type.
  7934. SmallVector<EVT, 4> OldRetTys;
  7935. SmallVector<uint64_t, 4> OldOffsets;
  7936. RetTys.swap(OldRetTys);
  7937. Offsets.swap(OldOffsets);
  7938. for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
  7939. EVT RetVT = OldRetTys[i];
  7940. uint64_t Offset = OldOffsets[i];
  7941. MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
  7942. unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
  7943. unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
  7944. RetTys.append(NumRegs, RegisterVT);
  7945. for (unsigned j = 0; j != NumRegs; ++j)
  7946. Offsets.push_back(Offset + j * RegisterVTByteSZ);
  7947. }
  7948. }
  7949. SmallVector<ISD::OutputArg, 4> Outs;
  7950. GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
  7951. bool CanLowerReturn =
  7952. this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
  7953. CLI.IsVarArg, Outs, CLI.RetTy->getContext());
  7954. SDValue DemoteStackSlot;
  7955. int DemoteStackIdx = -100;
  7956. if (!CanLowerReturn) {
  7957. // FIXME: equivalent assert?
  7958. // assert(!CS.hasInAllocaArgument() &&
  7959. // "sret demotion is incompatible with inalloca");
  7960. uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
  7961. unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
  7962. MachineFunction &MF = CLI.DAG.getMachineFunction();
  7963. DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
  7964. Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
  7965. DL.getAllocaAddrSpace());
  7966. DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
  7967. ArgListEntry Entry;
  7968. Entry.Node = DemoteStackSlot;
  7969. Entry.Ty = StackSlotPtrType;
  7970. Entry.IsSExt = false;
  7971. Entry.IsZExt = false;
  7972. Entry.IsInReg = false;
  7973. Entry.IsSRet = true;
  7974. Entry.IsNest = false;
  7975. Entry.IsByVal = false;
  7976. Entry.IsReturned = false;
  7977. Entry.IsSwiftSelf = false;
  7978. Entry.IsSwiftError = false;
  7979. Entry.Alignment = Align;
  7980. CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
  7981. CLI.NumFixedArgs += 1;
  7982. CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
  7983. // sret demotion isn't compatible with tail-calls, since the sret argument
  7984. // points into the callers stack frame.
  7985. CLI.IsTailCall = false;
  7986. } else {
  7987. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  7988. CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
  7989. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  7990. ISD::ArgFlagsTy Flags;
  7991. if (NeedsRegBlock) {
  7992. Flags.setInConsecutiveRegs();
  7993. if (I == RetTys.size() - 1)
  7994. Flags.setInConsecutiveRegsLast();
  7995. }
  7996. EVT VT = RetTys[I];
  7997. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  7998. CLI.CallConv, VT);
  7999. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8000. CLI.CallConv, VT);
  8001. for (unsigned i = 0; i != NumRegs; ++i) {
  8002. ISD::InputArg MyFlags;
  8003. MyFlags.Flags = Flags;
  8004. MyFlags.VT = RegisterVT;
  8005. MyFlags.ArgVT = VT;
  8006. MyFlags.Used = CLI.IsReturnValueUsed;
  8007. if (CLI.RetTy->isPointerTy()) {
  8008. MyFlags.Flags.setPointer();
  8009. MyFlags.Flags.setPointerAddrSpace(
  8010. cast<PointerType>(CLI.RetTy)->getAddressSpace());
  8011. }
  8012. if (CLI.RetSExt)
  8013. MyFlags.Flags.setSExt();
  8014. if (CLI.RetZExt)
  8015. MyFlags.Flags.setZExt();
  8016. if (CLI.IsInReg)
  8017. MyFlags.Flags.setInReg();
  8018. CLI.Ins.push_back(MyFlags);
  8019. }
  8020. }
  8021. }
  8022. // We push in swifterror return as the last element of CLI.Ins.
  8023. ArgListTy &Args = CLI.getArgs();
  8024. if (supportSwiftError()) {
  8025. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8026. if (Args[i].IsSwiftError) {
  8027. ISD::InputArg MyFlags;
  8028. MyFlags.VT = getPointerTy(DL);
  8029. MyFlags.ArgVT = EVT(getPointerTy(DL));
  8030. MyFlags.Flags.setSwiftError();
  8031. CLI.Ins.push_back(MyFlags);
  8032. }
  8033. }
  8034. }
  8035. // Handle all of the outgoing arguments.
  8036. CLI.Outs.clear();
  8037. CLI.OutVals.clear();
  8038. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  8039. SmallVector<EVT, 4> ValueVTs;
  8040. ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
  8041. // FIXME: Split arguments if CLI.IsPostTypeLegalization
  8042. Type *FinalType = Args[i].Ty;
  8043. if (Args[i].IsByVal)
  8044. FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
  8045. bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
  8046. FinalType, CLI.CallConv, CLI.IsVarArg);
  8047. for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
  8048. ++Value) {
  8049. EVT VT = ValueVTs[Value];
  8050. Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
  8051. SDValue Op = SDValue(Args[i].Node.getNode(),
  8052. Args[i].Node.getResNo() + Value);
  8053. ISD::ArgFlagsTy Flags;
  8054. // Certain targets (such as MIPS), may have a different ABI alignment
  8055. // for a type depending on the context. Give the target a chance to
  8056. // specify the alignment it wants.
  8057. unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
  8058. if (Args[i].Ty->isPointerTy()) {
  8059. Flags.setPointer();
  8060. Flags.setPointerAddrSpace(
  8061. cast<PointerType>(Args[i].Ty)->getAddressSpace());
  8062. }
  8063. if (Args[i].IsZExt)
  8064. Flags.setZExt();
  8065. if (Args[i].IsSExt)
  8066. Flags.setSExt();
  8067. if (Args[i].IsInReg) {
  8068. // If we are using vectorcall calling convention, a structure that is
  8069. // passed InReg - is surely an HVA
  8070. if (CLI.CallConv == CallingConv::X86_VectorCall &&
  8071. isa<StructType>(FinalType)) {
  8072. // The first value of a structure is marked
  8073. if (0 == Value)
  8074. Flags.setHvaStart();
  8075. Flags.setHva();
  8076. }
  8077. // Set InReg Flag
  8078. Flags.setInReg();
  8079. }
  8080. if (Args[i].IsSRet)
  8081. Flags.setSRet();
  8082. if (Args[i].IsSwiftSelf)
  8083. Flags.setSwiftSelf();
  8084. if (Args[i].IsSwiftError)
  8085. Flags.setSwiftError();
  8086. if (Args[i].IsByVal)
  8087. Flags.setByVal();
  8088. if (Args[i].IsInAlloca) {
  8089. Flags.setInAlloca();
  8090. // Set the byval flag for CCAssignFn callbacks that don't know about
  8091. // inalloca. This way we can know how many bytes we should've allocated
  8092. // and how many bytes a callee cleanup function will pop. If we port
  8093. // inalloca to more targets, we'll have to add custom inalloca handling
  8094. // in the various CC lowering callbacks.
  8095. Flags.setByVal();
  8096. }
  8097. if (Args[i].IsByVal || Args[i].IsInAlloca) {
  8098. PointerType *Ty = cast<PointerType>(Args[i].Ty);
  8099. Type *ElementTy = Ty->getElementType();
  8100. unsigned FrameSize = DL.getTypeAllocSize(
  8101. Args[i].ByValType ? Args[i].ByValType : ElementTy);
  8102. Flags.setByValSize(FrameSize);
  8103. // info is not there but there are cases it cannot get right.
  8104. unsigned FrameAlign;
  8105. if (Args[i].Alignment)
  8106. FrameAlign = Args[i].Alignment;
  8107. else
  8108. FrameAlign = getByValTypeAlignment(ElementTy, DL);
  8109. Flags.setByValAlign(FrameAlign);
  8110. }
  8111. if (Args[i].IsNest)
  8112. Flags.setNest();
  8113. if (NeedsRegBlock)
  8114. Flags.setInConsecutiveRegs();
  8115. Flags.setOrigAlign(OriginalAlignment);
  8116. MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8117. CLI.CallConv, VT);
  8118. unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8119. CLI.CallConv, VT);
  8120. SmallVector<SDValue, 4> Parts(NumParts);
  8121. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  8122. if (Args[i].IsSExt)
  8123. ExtendKind = ISD::SIGN_EXTEND;
  8124. else if (Args[i].IsZExt)
  8125. ExtendKind = ISD::ZERO_EXTEND;
  8126. // Conservatively only handle 'returned' on non-vectors that can be lowered,
  8127. // for now.
  8128. if (Args[i].IsReturned && !Op.getValueType().isVector() &&
  8129. CanLowerReturn) {
  8130. assert((CLI.RetTy == Args[i].Ty ||
  8131. (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
  8132. CLI.RetTy->getPointerAddressSpace() ==
  8133. Args[i].Ty->getPointerAddressSpace())) &&
  8134. RetTys.size() == NumValues && "unexpected use of 'returned'");
  8135. // Before passing 'returned' to the target lowering code, ensure that
  8136. // either the register MVT and the actual EVT are the same size or that
  8137. // the return value and argument are extended in the same way; in these
  8138. // cases it's safe to pass the argument register value unchanged as the
  8139. // return register value (although it's at the target's option whether
  8140. // to do so)
  8141. // TODO: allow code generation to take advantage of partially preserved
  8142. // registers rather than clobbering the entire register when the
  8143. // parameter extension method is not compatible with the return
  8144. // extension method
  8145. if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
  8146. (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
  8147. CLI.RetZExt == Args[i].IsZExt))
  8148. Flags.setReturned();
  8149. }
  8150. getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
  8151. CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
  8152. for (unsigned j = 0; j != NumParts; ++j) {
  8153. // if it isn't first piece, alignment must be 1
  8154. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
  8155. i < CLI.NumFixedArgs,
  8156. i, j*Parts[j].getValueType().getStoreSize());
  8157. if (NumParts > 1 && j == 0)
  8158. MyFlags.Flags.setSplit();
  8159. else if (j != 0) {
  8160. MyFlags.Flags.setOrigAlign(1);
  8161. if (j == NumParts - 1)
  8162. MyFlags.Flags.setSplitEnd();
  8163. }
  8164. CLI.Outs.push_back(MyFlags);
  8165. CLI.OutVals.push_back(Parts[j]);
  8166. }
  8167. if (NeedsRegBlock && Value == NumValues - 1)
  8168. CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
  8169. }
  8170. }
  8171. SmallVector<SDValue, 4> InVals;
  8172. CLI.Chain = LowerCall(CLI, InVals);
  8173. // Update CLI.InVals to use outside of this function.
  8174. CLI.InVals = InVals;
  8175. // Verify that the target's LowerCall behaved as expected.
  8176. assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
  8177. "LowerCall didn't return a valid chain!");
  8178. assert((!CLI.IsTailCall || InVals.empty()) &&
  8179. "LowerCall emitted a return value for a tail call!");
  8180. assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
  8181. "LowerCall didn't emit the correct number of values!");
  8182. // For a tail call, the return value is merely live-out and there aren't
  8183. // any nodes in the DAG representing it. Return a special value to
  8184. // indicate that a tail call has been emitted and no more Instructions
  8185. // should be processed in the current block.
  8186. if (CLI.IsTailCall) {
  8187. CLI.DAG.setRoot(CLI.Chain);
  8188. return std::make_pair(SDValue(), SDValue());
  8189. }
  8190. #ifndef NDEBUG
  8191. for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
  8192. assert(InVals[i].getNode() && "LowerCall emitted a null value!");
  8193. assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
  8194. "LowerCall emitted a value with the wrong type!");
  8195. }
  8196. #endif
  8197. SmallVector<SDValue, 4> ReturnValues;
  8198. if (!CanLowerReturn) {
  8199. // The instruction result is the result of loading from the
  8200. // hidden sret parameter.
  8201. SmallVector<EVT, 1> PVTs;
  8202. Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
  8203. ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
  8204. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  8205. EVT PtrVT = PVTs[0];
  8206. unsigned NumValues = RetTys.size();
  8207. ReturnValues.resize(NumValues);
  8208. SmallVector<SDValue, 4> Chains(NumValues);
  8209. // An aggregate return value cannot wrap around the address space, so
  8210. // offsets to its parts don't wrap either.
  8211. SDNodeFlags Flags;
  8212. Flags.setNoUnsignedWrap(true);
  8213. for (unsigned i = 0; i < NumValues; ++i) {
  8214. SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
  8215. CLI.DAG.getConstant(Offsets[i], CLI.DL,
  8216. PtrVT), Flags);
  8217. SDValue L = CLI.DAG.getLoad(
  8218. RetTys[i], CLI.DL, CLI.Chain, Add,
  8219. MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
  8220. DemoteStackIdx, Offsets[i]),
  8221. /* Alignment = */ 1);
  8222. ReturnValues[i] = L;
  8223. Chains[i] = L.getValue(1);
  8224. }
  8225. CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
  8226. } else {
  8227. // Collect the legal value parts into potentially illegal values
  8228. // that correspond to the original function's return values.
  8229. Optional<ISD::NodeType> AssertOp;
  8230. if (CLI.RetSExt)
  8231. AssertOp = ISD::AssertSext;
  8232. else if (CLI.RetZExt)
  8233. AssertOp = ISD::AssertZext;
  8234. unsigned CurReg = 0;
  8235. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  8236. EVT VT = RetTys[I];
  8237. MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
  8238. CLI.CallConv, VT);
  8239. unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
  8240. CLI.CallConv, VT);
  8241. ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
  8242. NumRegs, RegisterVT, VT, nullptr,
  8243. CLI.CallConv, AssertOp));
  8244. CurReg += NumRegs;
  8245. }
  8246. // For a function returning void, there is no return value. We can't create
  8247. // such a node, so we just return a null return value in that case. In
  8248. // that case, nothing will actually look at the value.
  8249. if (ReturnValues.empty())
  8250. return std::make_pair(SDValue(), CLI.Chain);
  8251. }
  8252. SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
  8253. CLI.DAG.getVTList(RetTys), ReturnValues);
  8254. return std::make_pair(Res, CLI.Chain);
  8255. }
  8256. void TargetLowering::LowerOperationWrapper(SDNode *N,
  8257. SmallVectorImpl<SDValue> &Results,
  8258. SelectionDAG &DAG) const {
  8259. if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
  8260. Results.push_back(Res);
  8261. }
  8262. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  8263. llvm_unreachable("LowerOperation not implemented for this target!");
  8264. }
  8265. void
  8266. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  8267. SDValue Op = getNonRegisterValue(V);
  8268. assert((Op.getOpcode() != ISD::CopyFromReg ||
  8269. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  8270. "Copy from a reg to the same reg!");
  8271. assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
  8272. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8273. // If this is an InlineAsm we have to match the registers required, not the
  8274. // notional registers required by the type.
  8275. RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
  8276. None); // This is not an ABI copy.
  8277. SDValue Chain = DAG.getEntryNode();
  8278. ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
  8279. FuncInfo.PreferredExtendType.end())
  8280. ? ISD::ANY_EXTEND
  8281. : FuncInfo.PreferredExtendType[V];
  8282. RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
  8283. PendingExports.push_back(Chain);
  8284. }
  8285. #include "llvm/CodeGen/SelectionDAGISel.h"
  8286. /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
  8287. /// entry block, return true. This includes arguments used by switches, since
  8288. /// the switch may expand into multiple basic blocks.
  8289. static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
  8290. // With FastISel active, we may be splitting blocks, so force creation
  8291. // of virtual registers for all non-dead arguments.
  8292. if (FastISel)
  8293. return A->use_empty();
  8294. const BasicBlock &Entry = A->getParent()->front();
  8295. for (const User *U : A->users())
  8296. if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
  8297. return false; // Use not in entry block.
  8298. return true;
  8299. }
  8300. using ArgCopyElisionMapTy =
  8301. DenseMap<const Argument *,
  8302. std::pair<const AllocaInst *, const StoreInst *>>;
  8303. /// Scan the entry block of the function in FuncInfo for arguments that look
  8304. /// like copies into a local alloca. Record any copied arguments in
  8305. /// ArgCopyElisionCandidates.
  8306. static void
  8307. findArgumentCopyElisionCandidates(const DataLayout &DL,
  8308. FunctionLoweringInfo *FuncInfo,
  8309. ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
  8310. // Record the state of every static alloca used in the entry block. Argument
  8311. // allocas are all used in the entry block, so we need approximately as many
  8312. // entries as we have arguments.
  8313. enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
  8314. SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
  8315. unsigned NumArgs = FuncInfo->Fn->arg_size();
  8316. StaticAllocas.reserve(NumArgs * 2);
  8317. auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
  8318. if (!V)
  8319. return nullptr;
  8320. V = V->stripPointerCasts();
  8321. const auto *AI = dyn_cast<AllocaInst>(V);
  8322. if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
  8323. return nullptr;
  8324. auto Iter = StaticAllocas.insert({AI, Unknown});
  8325. return &Iter.first->second;
  8326. };
  8327. // Look for stores of arguments to static allocas. Look through bitcasts and
  8328. // GEPs to handle type coercions, as long as the alloca is fully initialized
  8329. // by the store. Any non-store use of an alloca escapes it and any subsequent
  8330. // unanalyzed store might write it.
  8331. // FIXME: Handle structs initialized with multiple stores.
  8332. for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
  8333. // Look for stores, and handle non-store uses conservatively.
  8334. const auto *SI = dyn_cast<StoreInst>(&I);
  8335. if (!SI) {
  8336. // We will look through cast uses, so ignore them completely.
  8337. if (I.isCast())
  8338. continue;
  8339. // Ignore debug info intrinsics, they don't escape or store to allocas.
  8340. if (isa<DbgInfoIntrinsic>(I))
  8341. continue;
  8342. // This is an unknown instruction. Assume it escapes or writes to all
  8343. // static alloca operands.
  8344. for (const Use &U : I.operands()) {
  8345. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
  8346. *Info = StaticAllocaInfo::Clobbered;
  8347. }
  8348. continue;
  8349. }
  8350. // If the stored value is a static alloca, mark it as escaped.
  8351. if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
  8352. *Info = StaticAllocaInfo::Clobbered;
  8353. // Check if the destination is a static alloca.
  8354. const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
  8355. StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
  8356. if (!Info)
  8357. continue;
  8358. const AllocaInst *AI = cast<AllocaInst>(Dst);
  8359. // Skip allocas that have been initialized or clobbered.
  8360. if (*Info != StaticAllocaInfo::Unknown)
  8361. continue;
  8362. // Check if the stored value is an argument, and that this store fully
  8363. // initializes the alloca. Don't elide copies from the same argument twice.
  8364. const Value *Val = SI->getValueOperand()->stripPointerCasts();
  8365. const auto *Arg = dyn_cast<Argument>(Val);
  8366. if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
  8367. Arg->getType()->isEmptyTy() ||
  8368. DL.getTypeStoreSize(Arg->getType()) !=
  8369. DL.getTypeAllocSize(AI->getAllocatedType()) ||
  8370. ArgCopyElisionCandidates.count(Arg)) {
  8371. *Info = StaticAllocaInfo::Clobbered;
  8372. continue;
  8373. }
  8374. LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
  8375. << '\n');
  8376. // Mark this alloca and store for argument copy elision.
  8377. *Info = StaticAllocaInfo::Elidable;
  8378. ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
  8379. // Stop scanning if we've seen all arguments. This will happen early in -O0
  8380. // builds, which is useful, because -O0 builds have large entry blocks and
  8381. // many allocas.
  8382. if (ArgCopyElisionCandidates.size() == NumArgs)
  8383. break;
  8384. }
  8385. }
  8386. /// Try to elide argument copies from memory into a local alloca. Succeeds if
  8387. /// ArgVal is a load from a suitable fixed stack object.
  8388. static void tryToElideArgumentCopy(
  8389. FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
  8390. DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
  8391. SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
  8392. ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
  8393. SDValue ArgVal, bool &ArgHasUses) {
  8394. // Check if this is a load from a fixed stack object.
  8395. auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
  8396. if (!LNode)
  8397. return;
  8398. auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
  8399. if (!FINode)
  8400. return;
  8401. // Check that the fixed stack object is the right size and alignment.
  8402. // Look at the alignment that the user wrote on the alloca instead of looking
  8403. // at the stack object.
  8404. auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
  8405. assert(ArgCopyIter != ArgCopyElisionCandidates.end());
  8406. const AllocaInst *AI = ArgCopyIter->second.first;
  8407. int FixedIndex = FINode->getIndex();
  8408. int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
  8409. int OldIndex = AllocaIndex;
  8410. MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
  8411. if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
  8412. LLVM_DEBUG(
  8413. dbgs() << " argument copy elision failed due to bad fixed stack "
  8414. "object size\n");
  8415. return;
  8416. }
  8417. unsigned RequiredAlignment = AI->getAlignment();
  8418. if (!RequiredAlignment) {
  8419. RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
  8420. AI->getAllocatedType());
  8421. }
  8422. if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
  8423. LLVM_DEBUG(dbgs() << " argument copy elision failed: alignment of alloca "
  8424. "greater than stack argument alignment ("
  8425. << RequiredAlignment << " vs "
  8426. << MFI.getObjectAlignment(FixedIndex) << ")\n");
  8427. return;
  8428. }
  8429. // Perform the elision. Delete the old stack object and replace its only use
  8430. // in the variable info map. Mark the stack object as mutable.
  8431. LLVM_DEBUG({
  8432. dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
  8433. << " Replacing frame index " << OldIndex << " with " << FixedIndex
  8434. << '\n';
  8435. });
  8436. MFI.RemoveStackObject(OldIndex);
  8437. MFI.setIsImmutableObjectIndex(FixedIndex, false);
  8438. AllocaIndex = FixedIndex;
  8439. ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
  8440. Chains.push_back(ArgVal.getValue(1));
  8441. // Avoid emitting code for the store implementing the copy.
  8442. const StoreInst *SI = ArgCopyIter->second.second;
  8443. ElidedArgCopyInstrs.insert(SI);
  8444. // Check for uses of the argument again so that we can avoid exporting ArgVal
  8445. // if it is't used by anything other than the store.
  8446. for (const Value *U : Arg.users()) {
  8447. if (U != SI) {
  8448. ArgHasUses = true;
  8449. break;
  8450. }
  8451. }
  8452. }
  8453. void SelectionDAGISel::LowerArguments(const Function &F) {
  8454. SelectionDAG &DAG = SDB->DAG;
  8455. SDLoc dl = SDB->getCurSDLoc();
  8456. const DataLayout &DL = DAG.getDataLayout();
  8457. SmallVector<ISD::InputArg, 16> Ins;
  8458. if (!FuncInfo->CanLowerReturn) {
  8459. // Put in an sret pointer parameter before all the other parameters.
  8460. SmallVector<EVT, 1> ValueVTs;
  8461. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8462. F.getReturnType()->getPointerTo(
  8463. DAG.getDataLayout().getAllocaAddrSpace()),
  8464. ValueVTs);
  8465. // NOTE: Assuming that a pointer will never break down to more than one VT
  8466. // or one register.
  8467. ISD::ArgFlagsTy Flags;
  8468. Flags.setSRet();
  8469. MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
  8470. ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
  8471. ISD::InputArg::NoArgIndex, 0);
  8472. Ins.push_back(RetArg);
  8473. }
  8474. // Look for stores of arguments to static allocas. Mark such arguments with a
  8475. // flag to ask the target to give us the memory location of that argument if
  8476. // available.
  8477. ArgCopyElisionMapTy ArgCopyElisionCandidates;
  8478. findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
  8479. // Set up the incoming argument description vector.
  8480. for (const Argument &Arg : F.args()) {
  8481. unsigned ArgNo = Arg.getArgNo();
  8482. SmallVector<EVT, 4> ValueVTs;
  8483. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8484. bool isArgValueUsed = !Arg.use_empty();
  8485. unsigned PartBase = 0;
  8486. Type *FinalType = Arg.getType();
  8487. if (Arg.hasAttribute(Attribute::ByVal))
  8488. FinalType = Arg.getParamByValType();
  8489. bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
  8490. FinalType, F.getCallingConv(), F.isVarArg());
  8491. for (unsigned Value = 0, NumValues = ValueVTs.size();
  8492. Value != NumValues; ++Value) {
  8493. EVT VT = ValueVTs[Value];
  8494. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  8495. ISD::ArgFlagsTy Flags;
  8496. // Certain targets (such as MIPS), may have a different ABI alignment
  8497. // for a type depending on the context. Give the target a chance to
  8498. // specify the alignment it wants.
  8499. unsigned OriginalAlignment =
  8500. TLI->getABIAlignmentForCallingConv(ArgTy, DL);
  8501. if (Arg.getType()->isPointerTy()) {
  8502. Flags.setPointer();
  8503. Flags.setPointerAddrSpace(
  8504. cast<PointerType>(Arg.getType())->getAddressSpace());
  8505. }
  8506. if (Arg.hasAttribute(Attribute::ZExt))
  8507. Flags.setZExt();
  8508. if (Arg.hasAttribute(Attribute::SExt))
  8509. Flags.setSExt();
  8510. if (Arg.hasAttribute(Attribute::InReg)) {
  8511. // If we are using vectorcall calling convention, a structure that is
  8512. // passed InReg - is surely an HVA
  8513. if (F.getCallingConv() == CallingConv::X86_VectorCall &&
  8514. isa<StructType>(Arg.getType())) {
  8515. // The first value of a structure is marked
  8516. if (0 == Value)
  8517. Flags.setHvaStart();
  8518. Flags.setHva();
  8519. }
  8520. // Set InReg Flag
  8521. Flags.setInReg();
  8522. }
  8523. if (Arg.hasAttribute(Attribute::StructRet))
  8524. Flags.setSRet();
  8525. if (Arg.hasAttribute(Attribute::SwiftSelf))
  8526. Flags.setSwiftSelf();
  8527. if (Arg.hasAttribute(Attribute::SwiftError))
  8528. Flags.setSwiftError();
  8529. if (Arg.hasAttribute(Attribute::ByVal))
  8530. Flags.setByVal();
  8531. if (Arg.hasAttribute(Attribute::InAlloca)) {
  8532. Flags.setInAlloca();
  8533. // Set the byval flag for CCAssignFn callbacks that don't know about
  8534. // inalloca. This way we can know how many bytes we should've allocated
  8535. // and how many bytes a callee cleanup function will pop. If we port
  8536. // inalloca to more targets, we'll have to add custom inalloca handling
  8537. // in the various CC lowering callbacks.
  8538. Flags.setByVal();
  8539. }
  8540. if (F.getCallingConv() == CallingConv::X86_INTR) {
  8541. // IA Interrupt passes frame (1st parameter) by value in the stack.
  8542. if (ArgNo == 0)
  8543. Flags.setByVal();
  8544. }
  8545. if (Flags.isByVal() || Flags.isInAlloca()) {
  8546. Type *ElementTy = Arg.getParamByValType();
  8547. // For ByVal, size and alignment should be passed from FE. BE will
  8548. // guess if this info is not there but there are cases it cannot get
  8549. // right.
  8550. unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
  8551. Flags.setByValSize(FrameSize);
  8552. unsigned FrameAlign;
  8553. if (Arg.getParamAlignment())
  8554. FrameAlign = Arg.getParamAlignment();
  8555. else
  8556. FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
  8557. Flags.setByValAlign(FrameAlign);
  8558. }
  8559. if (Arg.hasAttribute(Attribute::Nest))
  8560. Flags.setNest();
  8561. if (NeedsRegBlock)
  8562. Flags.setInConsecutiveRegs();
  8563. Flags.setOrigAlign(OriginalAlignment);
  8564. if (ArgCopyElisionCandidates.count(&Arg))
  8565. Flags.setCopyElisionCandidate();
  8566. if (Arg.hasAttribute(Attribute::Returned))
  8567. Flags.setReturned();
  8568. MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
  8569. *CurDAG->getContext(), F.getCallingConv(), VT);
  8570. unsigned NumRegs = TLI->getNumRegistersForCallingConv(
  8571. *CurDAG->getContext(), F.getCallingConv(), VT);
  8572. for (unsigned i = 0; i != NumRegs; ++i) {
  8573. ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
  8574. ArgNo, PartBase+i*RegisterVT.getStoreSize());
  8575. if (NumRegs > 1 && i == 0)
  8576. MyFlags.Flags.setSplit();
  8577. // if it isn't first piece, alignment must be 1
  8578. else if (i > 0) {
  8579. MyFlags.Flags.setOrigAlign(1);
  8580. if (i == NumRegs - 1)
  8581. MyFlags.Flags.setSplitEnd();
  8582. }
  8583. Ins.push_back(MyFlags);
  8584. }
  8585. if (NeedsRegBlock && Value == NumValues - 1)
  8586. Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
  8587. PartBase += VT.getStoreSize();
  8588. }
  8589. }
  8590. // Call the target to set up the argument values.
  8591. SmallVector<SDValue, 8> InVals;
  8592. SDValue NewRoot = TLI->LowerFormalArguments(
  8593. DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
  8594. // Verify that the target's LowerFormalArguments behaved as expected.
  8595. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  8596. "LowerFormalArguments didn't return a valid chain!");
  8597. assert(InVals.size() == Ins.size() &&
  8598. "LowerFormalArguments didn't emit the correct number of values!");
  8599. LLVM_DEBUG({
  8600. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  8601. assert(InVals[i].getNode() &&
  8602. "LowerFormalArguments emitted a null value!");
  8603. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  8604. "LowerFormalArguments emitted a value with the wrong type!");
  8605. }
  8606. });
  8607. // Update the DAG with the new chain value resulting from argument lowering.
  8608. DAG.setRoot(NewRoot);
  8609. // Set up the argument values.
  8610. unsigned i = 0;
  8611. if (!FuncInfo->CanLowerReturn) {
  8612. // Create a virtual register for the sret pointer, and put in a copy
  8613. // from the sret argument into it.
  8614. SmallVector<EVT, 1> ValueVTs;
  8615. ComputeValueVTs(*TLI, DAG.getDataLayout(),
  8616. F.getReturnType()->getPointerTo(
  8617. DAG.getDataLayout().getAllocaAddrSpace()),
  8618. ValueVTs);
  8619. MVT VT = ValueVTs[0].getSimpleVT();
  8620. MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
  8621. Optional<ISD::NodeType> AssertOp = None;
  8622. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
  8623. nullptr, F.getCallingConv(), AssertOp);
  8624. MachineFunction& MF = SDB->DAG.getMachineFunction();
  8625. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  8626. Register SRetReg =
  8627. RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
  8628. FuncInfo->DemoteRegister = SRetReg;
  8629. NewRoot =
  8630. SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
  8631. DAG.setRoot(NewRoot);
  8632. // i indexes lowered arguments. Bump it past the hidden sret argument.
  8633. ++i;
  8634. }
  8635. SmallVector<SDValue, 4> Chains;
  8636. DenseMap<int, int> ArgCopyElisionFrameIndexMap;
  8637. for (const Argument &Arg : F.args()) {
  8638. SmallVector<SDValue, 4> ArgValues;
  8639. SmallVector<EVT, 4> ValueVTs;
  8640. ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
  8641. unsigned NumValues = ValueVTs.size();
  8642. if (NumValues == 0)
  8643. continue;
  8644. bool ArgHasUses = !Arg.use_empty();
  8645. // Elide the copying store if the target loaded this argument from a
  8646. // suitable fixed stack object.
  8647. if (Ins[i].Flags.isCopyElisionCandidate()) {
  8648. tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
  8649. ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
  8650. InVals[i], ArgHasUses);
  8651. }
  8652. // If this argument is unused then remember its value. It is used to generate
  8653. // debugging information.
  8654. bool isSwiftErrorArg =
  8655. TLI->supportSwiftError() &&
  8656. Arg.hasAttribute(Attribute::SwiftError);
  8657. if (!ArgHasUses && !isSwiftErrorArg) {
  8658. SDB->setUnusedArgValue(&Arg, InVals[i]);
  8659. // Also remember any frame index for use in FastISel.
  8660. if (FrameIndexSDNode *FI =
  8661. dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
  8662. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8663. }
  8664. for (unsigned Val = 0; Val != NumValues; ++Val) {
  8665. EVT VT = ValueVTs[Val];
  8666. MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
  8667. F.getCallingConv(), VT);
  8668. unsigned NumParts = TLI->getNumRegistersForCallingConv(
  8669. *CurDAG->getContext(), F.getCallingConv(), VT);
  8670. // Even an apparant 'unused' swifterror argument needs to be returned. So
  8671. // we do generate a copy for it that can be used on return from the
  8672. // function.
  8673. if (ArgHasUses || isSwiftErrorArg) {
  8674. Optional<ISD::NodeType> AssertOp;
  8675. if (Arg.hasAttribute(Attribute::SExt))
  8676. AssertOp = ISD::AssertSext;
  8677. else if (Arg.hasAttribute(Attribute::ZExt))
  8678. AssertOp = ISD::AssertZext;
  8679. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
  8680. PartVT, VT, nullptr,
  8681. F.getCallingConv(), AssertOp));
  8682. }
  8683. i += NumParts;
  8684. }
  8685. // We don't need to do anything else for unused arguments.
  8686. if (ArgValues.empty())
  8687. continue;
  8688. // Note down frame index.
  8689. if (FrameIndexSDNode *FI =
  8690. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  8691. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8692. SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
  8693. SDB->getCurSDLoc());
  8694. SDB->setValue(&Arg, Res);
  8695. if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
  8696. // We want to associate the argument with the frame index, among
  8697. // involved operands, that correspond to the lowest address. The
  8698. // getCopyFromParts function, called earlier, is swapping the order of
  8699. // the operands to BUILD_PAIR depending on endianness. The result of
  8700. // that swapping is that the least significant bits of the argument will
  8701. // be in the first operand of the BUILD_PAIR node, and the most
  8702. // significant bits will be in the second operand.
  8703. unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
  8704. if (LoadSDNode *LNode =
  8705. dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
  8706. if (FrameIndexSDNode *FI =
  8707. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
  8708. FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
  8709. }
  8710. // Update the SwiftErrorVRegDefMap.
  8711. if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
  8712. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8713. if (Register::isVirtualRegister(Reg))
  8714. SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
  8715. Reg);
  8716. }
  8717. // If this argument is live outside of the entry block, insert a copy from
  8718. // wherever we got it to the vreg that other BB's will reference it as.
  8719. if (Res.getOpcode() == ISD::CopyFromReg) {
  8720. // If we can, though, try to skip creating an unnecessary vreg.
  8721. // FIXME: This isn't very clean... it would be nice to make this more
  8722. // general.
  8723. unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
  8724. if (Register::isVirtualRegister(Reg)) {
  8725. FuncInfo->ValueMap[&Arg] = Reg;
  8726. continue;
  8727. }
  8728. }
  8729. if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
  8730. FuncInfo->InitializeRegForValue(&Arg);
  8731. SDB->CopyToExportRegsIfNeeded(&Arg);
  8732. }
  8733. }
  8734. if (!Chains.empty()) {
  8735. Chains.push_back(NewRoot);
  8736. NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
  8737. }
  8738. DAG.setRoot(NewRoot);
  8739. assert(i == InVals.size() && "Argument register count mismatch!");
  8740. // If any argument copy elisions occurred and we have debug info, update the
  8741. // stale frame indices used in the dbg.declare variable info table.
  8742. MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
  8743. if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
  8744. for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
  8745. auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
  8746. if (I != ArgCopyElisionFrameIndexMap.end())
  8747. VI.Slot = I->second;
  8748. }
  8749. }
  8750. // Finally, if the target has anything special to do, allow it to do so.
  8751. EmitFunctionEntryCode();
  8752. }
  8753. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  8754. /// ensure constants are generated when needed. Remember the virtual registers
  8755. /// that need to be added to the Machine PHI nodes as input. We cannot just
  8756. /// directly add them, because expansion might result in multiple MBB's for one
  8757. /// BB. As such, the start of the BB might correspond to a different MBB than
  8758. /// the end.
  8759. void
  8760. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  8761. const Instruction *TI = LLVMBB->getTerminator();
  8762. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  8763. // Check PHI nodes in successors that expect a value to be available from this
  8764. // block.
  8765. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  8766. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  8767. if (!isa<PHINode>(SuccBB->begin())) continue;
  8768. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  8769. // If this terminator has multiple identical successors (common for
  8770. // switches), only handle each succ once.
  8771. if (!SuccsHandled.insert(SuccMBB).second)
  8772. continue;
  8773. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  8774. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  8775. // nodes and Machine PHI nodes, but the incoming operands have not been
  8776. // emitted yet.
  8777. for (const PHINode &PN : SuccBB->phis()) {
  8778. // Ignore dead phi's.
  8779. if (PN.use_empty())
  8780. continue;
  8781. // Skip empty types
  8782. if (PN.getType()->isEmptyTy())
  8783. continue;
  8784. unsigned Reg;
  8785. const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
  8786. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  8787. unsigned &RegOut = ConstantsOut[C];
  8788. if (RegOut == 0) {
  8789. RegOut = FuncInfo.CreateRegs(C);
  8790. CopyValueToVirtualRegister(C, RegOut);
  8791. }
  8792. Reg = RegOut;
  8793. } else {
  8794. DenseMap<const Value *, unsigned>::iterator I =
  8795. FuncInfo.ValueMap.find(PHIOp);
  8796. if (I != FuncInfo.ValueMap.end())
  8797. Reg = I->second;
  8798. else {
  8799. assert(isa<AllocaInst>(PHIOp) &&
  8800. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  8801. "Didn't codegen value into a register!??");
  8802. Reg = FuncInfo.CreateRegs(PHIOp);
  8803. CopyValueToVirtualRegister(PHIOp, Reg);
  8804. }
  8805. }
  8806. // Remember that this register needs to added to the machine PHI node as
  8807. // the input for this MBB.
  8808. SmallVector<EVT, 4> ValueVTs;
  8809. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8810. ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
  8811. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  8812. EVT VT = ValueVTs[vti];
  8813. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  8814. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  8815. FuncInfo.PHINodesToUpdate.push_back(
  8816. std::make_pair(&*MBBI++, Reg + i));
  8817. Reg += NumRegisters;
  8818. }
  8819. }
  8820. }
  8821. ConstantsOut.clear();
  8822. }
  8823. /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
  8824. /// is 0.
  8825. MachineBasicBlock *
  8826. SelectionDAGBuilder::StackProtectorDescriptor::
  8827. AddSuccessorMBB(const BasicBlock *BB,
  8828. MachineBasicBlock *ParentMBB,
  8829. bool IsLikely,
  8830. MachineBasicBlock *SuccMBB) {
  8831. // If SuccBB has not been created yet, create it.
  8832. if (!SuccMBB) {
  8833. MachineFunction *MF = ParentMBB->getParent();
  8834. MachineFunction::iterator BBI(ParentMBB);
  8835. SuccMBB = MF->CreateMachineBasicBlock(BB);
  8836. MF->insert(++BBI, SuccMBB);
  8837. }
  8838. // Add it as a successor of ParentMBB.
  8839. ParentMBB->addSuccessor(
  8840. SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
  8841. return SuccMBB;
  8842. }
  8843. MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
  8844. MachineFunction::iterator I(MBB);
  8845. if (++I == FuncInfo.MF->end())
  8846. return nullptr;
  8847. return &*I;
  8848. }
  8849. /// During lowering new call nodes can be created (such as memset, etc.).
  8850. /// Those will become new roots of the current DAG, but complications arise
  8851. /// when they are tail calls. In such cases, the call lowering will update
  8852. /// the root, but the builder still needs to know that a tail call has been
  8853. /// lowered in order to avoid generating an additional return.
  8854. void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
  8855. // If the node is null, we do have a tail call.
  8856. if (MaybeTC.getNode() != nullptr)
  8857. DAG.setRoot(MaybeTC);
  8858. else
  8859. HasTailCall = true;
  8860. }
  8861. void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
  8862. MachineBasicBlock *SwitchMBB,
  8863. MachineBasicBlock *DefaultMBB) {
  8864. MachineFunction *CurMF = FuncInfo.MF;
  8865. MachineBasicBlock *NextMBB = nullptr;
  8866. MachineFunction::iterator BBI(W.MBB);
  8867. if (++BBI != FuncInfo.MF->end())
  8868. NextMBB = &*BBI;
  8869. unsigned Size = W.LastCluster - W.FirstCluster + 1;
  8870. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  8871. if (Size == 2 && W.MBB == SwitchMBB) {
  8872. // If any two of the cases has the same destination, and if one value
  8873. // is the same as the other, but has one bit unset that the other has set,
  8874. // use bit manipulation to do two compares at once. For example:
  8875. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  8876. // TODO: This could be extended to merge any 2 cases in switches with 3
  8877. // cases.
  8878. // TODO: Handle cases where W.CaseBB != SwitchBB.
  8879. CaseCluster &Small = *W.FirstCluster;
  8880. CaseCluster &Big = *W.LastCluster;
  8881. if (Small.Low == Small.High && Big.Low == Big.High &&
  8882. Small.MBB == Big.MBB) {
  8883. const APInt &SmallValue = Small.Low->getValue();
  8884. const APInt &BigValue = Big.Low->getValue();
  8885. // Check that there is only one bit different.
  8886. APInt CommonBit = BigValue ^ SmallValue;
  8887. if (CommonBit.isPowerOf2()) {
  8888. SDValue CondLHS = getValue(Cond);
  8889. EVT VT = CondLHS.getValueType();
  8890. SDLoc DL = getCurSDLoc();
  8891. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  8892. DAG.getConstant(CommonBit, DL, VT));
  8893. SDValue Cond = DAG.getSetCC(
  8894. DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
  8895. ISD::SETEQ);
  8896. // Update successor info.
  8897. // Both Small and Big will jump to Small.BB, so we sum up the
  8898. // probabilities.
  8899. addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
  8900. if (BPI)
  8901. addSuccessorWithProb(
  8902. SwitchMBB, DefaultMBB,
  8903. // The default destination is the first successor in IR.
  8904. BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
  8905. else
  8906. addSuccessorWithProb(SwitchMBB, DefaultMBB);
  8907. // Insert the true branch.
  8908. SDValue BrCond =
  8909. DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
  8910. DAG.getBasicBlock(Small.MBB));
  8911. // Insert the false branch.
  8912. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  8913. DAG.getBasicBlock(DefaultMBB));
  8914. DAG.setRoot(BrCond);
  8915. return;
  8916. }
  8917. }
  8918. }
  8919. if (TM.getOptLevel() != CodeGenOpt::None) {
  8920. // Here, we order cases by probability so the most likely case will be
  8921. // checked first. However, two clusters can have the same probability in
  8922. // which case their relative ordering is non-deterministic. So we use Low
  8923. // as a tie-breaker as clusters are guaranteed to never overlap.
  8924. llvm::sort(W.FirstCluster, W.LastCluster + 1,
  8925. [](const CaseCluster &a, const CaseCluster &b) {
  8926. return a.Prob != b.Prob ?
  8927. a.Prob > b.Prob :
  8928. a.Low->getValue().slt(b.Low->getValue());
  8929. });
  8930. // Rearrange the case blocks so that the last one falls through if possible
  8931. // without changing the order of probabilities.
  8932. for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
  8933. --I;
  8934. if (I->Prob > W.LastCluster->Prob)
  8935. break;
  8936. if (I->Kind == CC_Range && I->MBB == NextMBB) {
  8937. std::swap(*I, *W.LastCluster);
  8938. break;
  8939. }
  8940. }
  8941. }
  8942. // Compute total probability.
  8943. BranchProbability DefaultProb = W.DefaultProb;
  8944. BranchProbability UnhandledProbs = DefaultProb;
  8945. for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
  8946. UnhandledProbs += I->Prob;
  8947. MachineBasicBlock *CurMBB = W.MBB;
  8948. for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
  8949. bool FallthroughUnreachable = false;
  8950. MachineBasicBlock *Fallthrough;
  8951. if (I == W.LastCluster) {
  8952. // For the last cluster, fall through to the default destination.
  8953. Fallthrough = DefaultMBB;
  8954. FallthroughUnreachable = isa<UnreachableInst>(
  8955. DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
  8956. } else {
  8957. Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
  8958. CurMF->insert(BBI, Fallthrough);
  8959. // Put Cond in a virtual register to make it available from the new blocks.
  8960. ExportFromCurrentBlock(Cond);
  8961. }
  8962. UnhandledProbs -= I->Prob;
  8963. switch (I->Kind) {
  8964. case CC_JumpTable: {
  8965. // FIXME: Optimize away range check based on pivot comparisons.
  8966. JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
  8967. SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
  8968. // The jump block hasn't been inserted yet; insert it here.
  8969. MachineBasicBlock *JumpMBB = JT->MBB;
  8970. CurMF->insert(BBI, JumpMBB);
  8971. auto JumpProb = I->Prob;
  8972. auto FallthroughProb = UnhandledProbs;
  8973. // If the default statement is a target of the jump table, we evenly
  8974. // distribute the default probability to successors of CurMBB. Also
  8975. // update the probability on the edge from JumpMBB to Fallthrough.
  8976. for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
  8977. SE = JumpMBB->succ_end();
  8978. SI != SE; ++SI) {
  8979. if (*SI == DefaultMBB) {
  8980. JumpProb += DefaultProb / 2;
  8981. FallthroughProb -= DefaultProb / 2;
  8982. JumpMBB->setSuccProbability(SI, DefaultProb / 2);
  8983. JumpMBB->normalizeSuccProbs();
  8984. break;
  8985. }
  8986. }
  8987. if (FallthroughUnreachable) {
  8988. // Skip the range check if the fallthrough block is unreachable.
  8989. JTH->OmitRangeCheck = true;
  8990. }
  8991. if (!JTH->OmitRangeCheck)
  8992. addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
  8993. addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
  8994. CurMBB->normalizeSuccProbs();
  8995. // The jump table header will be inserted in our current block, do the
  8996. // range check, and fall through to our fallthrough block.
  8997. JTH->HeaderBB = CurMBB;
  8998. JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
  8999. // If we're in the right place, emit the jump table header right now.
  9000. if (CurMBB == SwitchMBB) {
  9001. visitJumpTableHeader(*JT, *JTH, SwitchMBB);
  9002. JTH->Emitted = true;
  9003. }
  9004. break;
  9005. }
  9006. case CC_BitTests: {
  9007. // FIXME: If Fallthrough is unreachable, skip the range check.
  9008. // FIXME: Optimize away range check based on pivot comparisons.
  9009. BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
  9010. // The bit test blocks haven't been inserted yet; insert them here.
  9011. for (BitTestCase &BTC : BTB->Cases)
  9012. CurMF->insert(BBI, BTC.ThisBB);
  9013. // Fill in fields of the BitTestBlock.
  9014. BTB->Parent = CurMBB;
  9015. BTB->Default = Fallthrough;
  9016. BTB->DefaultProb = UnhandledProbs;
  9017. // If the cases in bit test don't form a contiguous range, we evenly
  9018. // distribute the probability on the edge to Fallthrough to two
  9019. // successors of CurMBB.
  9020. if (!BTB->ContiguousRange) {
  9021. BTB->Prob += DefaultProb / 2;
  9022. BTB->DefaultProb -= DefaultProb / 2;
  9023. }
  9024. // If we're in the right place, emit the bit test header right now.
  9025. if (CurMBB == SwitchMBB) {
  9026. visitBitTestHeader(*BTB, SwitchMBB);
  9027. BTB->Emitted = true;
  9028. }
  9029. break;
  9030. }
  9031. case CC_Range: {
  9032. const Value *RHS, *LHS, *MHS;
  9033. ISD::CondCode CC;
  9034. if (I->Low == I->High) {
  9035. // Check Cond == I->Low.
  9036. CC = ISD::SETEQ;
  9037. LHS = Cond;
  9038. RHS=I->Low;
  9039. MHS = nullptr;
  9040. } else {
  9041. // Check I->Low <= Cond <= I->High.
  9042. CC = ISD::SETLE;
  9043. LHS = I->Low;
  9044. MHS = Cond;
  9045. RHS = I->High;
  9046. }
  9047. // If Fallthrough is unreachable, fold away the comparison.
  9048. if (FallthroughUnreachable)
  9049. CC = ISD::SETTRUE;
  9050. // The false probability is the sum of all unhandled cases.
  9051. CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
  9052. getCurSDLoc(), I->Prob, UnhandledProbs);
  9053. if (CurMBB == SwitchMBB)
  9054. visitSwitchCase(CB, SwitchMBB);
  9055. else
  9056. SL->SwitchCases.push_back(CB);
  9057. break;
  9058. }
  9059. }
  9060. CurMBB = Fallthrough;
  9061. }
  9062. }
  9063. unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
  9064. CaseClusterIt First,
  9065. CaseClusterIt Last) {
  9066. return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
  9067. if (X.Prob != CC.Prob)
  9068. return X.Prob > CC.Prob;
  9069. // Ties are broken by comparing the case value.
  9070. return X.Low->getValue().slt(CC.Low->getValue());
  9071. });
  9072. }
  9073. void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
  9074. const SwitchWorkListItem &W,
  9075. Value *Cond,
  9076. MachineBasicBlock *SwitchMBB) {
  9077. assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
  9078. "Clusters not sorted?");
  9079. assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
  9080. // Balance the tree based on branch probabilities to create a near-optimal (in
  9081. // terms of search time given key frequency) binary search tree. See e.g. Kurt
  9082. // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
  9083. CaseClusterIt LastLeft = W.FirstCluster;
  9084. CaseClusterIt FirstRight = W.LastCluster;
  9085. auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
  9086. auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
  9087. // Move LastLeft and FirstRight towards each other from opposite directions to
  9088. // find a partitioning of the clusters which balances the probability on both
  9089. // sides. If LeftProb and RightProb are equal, alternate which side is
  9090. // taken to ensure 0-probability nodes are distributed evenly.
  9091. unsigned I = 0;
  9092. while (LastLeft + 1 < FirstRight) {
  9093. if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
  9094. LeftProb += (++LastLeft)->Prob;
  9095. else
  9096. RightProb += (--FirstRight)->Prob;
  9097. I++;
  9098. }
  9099. while (true) {
  9100. // Our binary search tree differs from a typical BST in that ours can have up
  9101. // to three values in each leaf. The pivot selection above doesn't take that
  9102. // into account, which means the tree might require more nodes and be less
  9103. // efficient. We compensate for this here.
  9104. unsigned NumLeft = LastLeft - W.FirstCluster + 1;
  9105. unsigned NumRight = W.LastCluster - FirstRight + 1;
  9106. if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
  9107. // If one side has less than 3 clusters, and the other has more than 3,
  9108. // consider taking a cluster from the other side.
  9109. if (NumLeft < NumRight) {
  9110. // Consider moving the first cluster on the right to the left side.
  9111. CaseCluster &CC = *FirstRight;
  9112. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9113. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9114. if (LeftSideRank <= RightSideRank) {
  9115. // Moving the cluster to the left does not demote it.
  9116. ++LastLeft;
  9117. ++FirstRight;
  9118. continue;
  9119. }
  9120. } else {
  9121. assert(NumRight < NumLeft);
  9122. // Consider moving the last element on the left to the right side.
  9123. CaseCluster &CC = *LastLeft;
  9124. unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
  9125. unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
  9126. if (RightSideRank <= LeftSideRank) {
  9127. // Moving the cluster to the right does not demot it.
  9128. --LastLeft;
  9129. --FirstRight;
  9130. continue;
  9131. }
  9132. }
  9133. }
  9134. break;
  9135. }
  9136. assert(LastLeft + 1 == FirstRight);
  9137. assert(LastLeft >= W.FirstCluster);
  9138. assert(FirstRight <= W.LastCluster);
  9139. // Use the first element on the right as pivot since we will make less-than
  9140. // comparisons against it.
  9141. CaseClusterIt PivotCluster = FirstRight;
  9142. assert(PivotCluster > W.FirstCluster);
  9143. assert(PivotCluster <= W.LastCluster);
  9144. CaseClusterIt FirstLeft = W.FirstCluster;
  9145. CaseClusterIt LastRight = W.LastCluster;
  9146. const ConstantInt *Pivot = PivotCluster->Low;
  9147. // New blocks will be inserted immediately after the current one.
  9148. MachineFunction::iterator BBI(W.MBB);
  9149. ++BBI;
  9150. // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
  9151. // we can branch to its destination directly if it's squeezed exactly in
  9152. // between the known lower bound and Pivot - 1.
  9153. MachineBasicBlock *LeftMBB;
  9154. if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
  9155. FirstLeft->Low == W.GE &&
  9156. (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
  9157. LeftMBB = FirstLeft->MBB;
  9158. } else {
  9159. LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9160. FuncInfo.MF->insert(BBI, LeftMBB);
  9161. WorkList.push_back(
  9162. {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
  9163. // Put Cond in a virtual register to make it available from the new blocks.
  9164. ExportFromCurrentBlock(Cond);
  9165. }
  9166. // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
  9167. // single cluster, RHS.Low == Pivot, and we can branch to its destination
  9168. // directly if RHS.High equals the current upper bound.
  9169. MachineBasicBlock *RightMBB;
  9170. if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
  9171. W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
  9172. RightMBB = FirstRight->MBB;
  9173. } else {
  9174. RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
  9175. FuncInfo.MF->insert(BBI, RightMBB);
  9176. WorkList.push_back(
  9177. {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
  9178. // Put Cond in a virtual register to make it available from the new blocks.
  9179. ExportFromCurrentBlock(Cond);
  9180. }
  9181. // Create the CaseBlock record that will be used to lower the branch.
  9182. CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
  9183. getCurSDLoc(), LeftProb, RightProb);
  9184. if (W.MBB == SwitchMBB)
  9185. visitSwitchCase(CB, SwitchMBB);
  9186. else
  9187. SL->SwitchCases.push_back(CB);
  9188. }
  9189. // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
  9190. // from the swith statement.
  9191. static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
  9192. BranchProbability PeeledCaseProb) {
  9193. if (PeeledCaseProb == BranchProbability::getOne())
  9194. return BranchProbability::getZero();
  9195. BranchProbability SwitchProb = PeeledCaseProb.getCompl();
  9196. uint32_t Numerator = CaseProb.getNumerator();
  9197. uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
  9198. return BranchProbability(Numerator, std::max(Numerator, Denominator));
  9199. }
  9200. // Try to peel the top probability case if it exceeds the threshold.
  9201. // Return current MachineBasicBlock for the switch statement if the peeling
  9202. // does not occur.
  9203. // If the peeling is performed, return the newly created MachineBasicBlock
  9204. // for the peeled switch statement. Also update Clusters to remove the peeled
  9205. // case. PeeledCaseProb is the BranchProbability for the peeled case.
  9206. MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
  9207. const SwitchInst &SI, CaseClusterVector &Clusters,
  9208. BranchProbability &PeeledCaseProb) {
  9209. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9210. // Don't perform if there is only one cluster or optimizing for size.
  9211. if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
  9212. TM.getOptLevel() == CodeGenOpt::None ||
  9213. SwitchMBB->getParent()->getFunction().hasMinSize())
  9214. return SwitchMBB;
  9215. BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
  9216. unsigned PeeledCaseIndex = 0;
  9217. bool SwitchPeeled = false;
  9218. for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
  9219. CaseCluster &CC = Clusters[Index];
  9220. if (CC.Prob < TopCaseProb)
  9221. continue;
  9222. TopCaseProb = CC.Prob;
  9223. PeeledCaseIndex = Index;
  9224. SwitchPeeled = true;
  9225. }
  9226. if (!SwitchPeeled)
  9227. return SwitchMBB;
  9228. LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
  9229. << TopCaseProb << "\n");
  9230. // Record the MBB for the peeled switch statement.
  9231. MachineFunction::iterator BBI(SwitchMBB);
  9232. ++BBI;
  9233. MachineBasicBlock *PeeledSwitchMBB =
  9234. FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
  9235. FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
  9236. ExportFromCurrentBlock(SI.getCondition());
  9237. auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
  9238. SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
  9239. nullptr, nullptr, TopCaseProb.getCompl()};
  9240. lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
  9241. Clusters.erase(PeeledCaseIt);
  9242. for (CaseCluster &CC : Clusters) {
  9243. LLVM_DEBUG(
  9244. dbgs() << "Scale the probablity for one cluster, before scaling: "
  9245. << CC.Prob << "\n");
  9246. CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
  9247. LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
  9248. }
  9249. PeeledCaseProb = TopCaseProb;
  9250. return PeeledSwitchMBB;
  9251. }
  9252. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  9253. // Extract cases from the switch.
  9254. BranchProbabilityInfo *BPI = FuncInfo.BPI;
  9255. CaseClusterVector Clusters;
  9256. Clusters.reserve(SI.getNumCases());
  9257. for (auto I : SI.cases()) {
  9258. MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
  9259. const ConstantInt *CaseVal = I.getCaseValue();
  9260. BranchProbability Prob =
  9261. BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
  9262. : BranchProbability(1, SI.getNumCases() + 1);
  9263. Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
  9264. }
  9265. MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
  9266. // Cluster adjacent cases with the same destination. We do this at all
  9267. // optimization levels because it's cheap to do and will make codegen faster
  9268. // if there are many clusters.
  9269. sortAndRangeify(Clusters);
  9270. // The branch probablity of the peeled case.
  9271. BranchProbability PeeledCaseProb = BranchProbability::getZero();
  9272. MachineBasicBlock *PeeledSwitchMBB =
  9273. peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
  9274. // If there is only the default destination, jump there directly.
  9275. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  9276. if (Clusters.empty()) {
  9277. assert(PeeledSwitchMBB == SwitchMBB);
  9278. SwitchMBB->addSuccessor(DefaultMBB);
  9279. if (DefaultMBB != NextBlock(SwitchMBB)) {
  9280. DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
  9281. getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
  9282. }
  9283. return;
  9284. }
  9285. SL->findJumpTables(Clusters, &SI, DefaultMBB);
  9286. SL->findBitTestClusters(Clusters, &SI);
  9287. LLVM_DEBUG({
  9288. dbgs() << "Case clusters: ";
  9289. for (const CaseCluster &C : Clusters) {
  9290. if (C.Kind == CC_JumpTable)
  9291. dbgs() << "JT:";
  9292. if (C.Kind == CC_BitTests)
  9293. dbgs() << "BT:";
  9294. C.Low->getValue().print(dbgs(), true);
  9295. if (C.Low != C.High) {
  9296. dbgs() << '-';
  9297. C.High->getValue().print(dbgs(), true);
  9298. }
  9299. dbgs() << ' ';
  9300. }
  9301. dbgs() << '\n';
  9302. });
  9303. assert(!Clusters.empty());
  9304. SwitchWorkList WorkList;
  9305. CaseClusterIt First = Clusters.begin();
  9306. CaseClusterIt Last = Clusters.end() - 1;
  9307. auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
  9308. // Scale the branchprobability for DefaultMBB if the peel occurs and
  9309. // DefaultMBB is not replaced.
  9310. if (PeeledCaseProb != BranchProbability::getZero() &&
  9311. DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
  9312. DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
  9313. WorkList.push_back(
  9314. {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
  9315. while (!WorkList.empty()) {
  9316. SwitchWorkListItem W = WorkList.back();
  9317. WorkList.pop_back();
  9318. unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
  9319. if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
  9320. !DefaultMBB->getParent()->getFunction().hasMinSize()) {
  9321. // For optimized builds, lower large range as a balanced binary tree.
  9322. splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
  9323. continue;
  9324. }
  9325. lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
  9326. }
  9327. }