SelectionDAGBuilder.cpp 254 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500
  1. //===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This implements routines for translating from LLVM IR into SelectionDAG IR.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #define DEBUG_TYPE "isel"
  14. #include "SDNodeDbgValue.h"
  15. #include "SelectionDAGBuilder.h"
  16. #include "llvm/ADT/BitVector.h"
  17. #include "llvm/ADT/PostOrderIterator.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/ConstantFolding.h"
  21. #include "llvm/Constants.h"
  22. #include "llvm/CallingConv.h"
  23. #include "llvm/DerivedTypes.h"
  24. #include "llvm/Function.h"
  25. #include "llvm/GlobalVariable.h"
  26. #include "llvm/InlineAsm.h"
  27. #include "llvm/Instructions.h"
  28. #include "llvm/Intrinsics.h"
  29. #include "llvm/IntrinsicInst.h"
  30. #include "llvm/LLVMContext.h"
  31. #include "llvm/Module.h"
  32. #include "llvm/CodeGen/Analysis.h"
  33. #include "llvm/CodeGen/FastISel.h"
  34. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  35. #include "llvm/CodeGen/GCStrategy.h"
  36. #include "llvm/CodeGen/GCMetadata.h"
  37. #include "llvm/CodeGen/MachineFunction.h"
  38. #include "llvm/CodeGen/MachineFrameInfo.h"
  39. #include "llvm/CodeGen/MachineInstrBuilder.h"
  40. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  41. #include "llvm/CodeGen/MachineModuleInfo.h"
  42. #include "llvm/CodeGen/MachineRegisterInfo.h"
  43. #include "llvm/CodeGen/PseudoSourceValue.h"
  44. #include "llvm/CodeGen/SelectionDAG.h"
  45. #include "llvm/Analysis/DebugInfo.h"
  46. #include "llvm/Target/TargetData.h"
  47. #include "llvm/Target/TargetFrameLowering.h"
  48. #include "llvm/Target/TargetInstrInfo.h"
  49. #include "llvm/Target/TargetIntrinsicInfo.h"
  50. #include "llvm/Target/TargetLowering.h"
  51. #include "llvm/Target/TargetOptions.h"
  52. #include "llvm/Support/CommandLine.h"
  53. #include "llvm/Support/Debug.h"
  54. #include "llvm/Support/ErrorHandling.h"
  55. #include "llvm/Support/MathExtras.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include <algorithm>
  58. using namespace llvm;
  59. /// LimitFloatPrecision - Generate low-precision inline sequences for
  60. /// some float libcalls (6, 8 or 12 bits).
  61. static unsigned LimitFloatPrecision;
  62. static cl::opt<unsigned, true>
  63. LimitFPPrecision("limit-float-precision",
  64. cl::desc("Generate low-precision inline sequences "
  65. "for some float libcalls"),
  66. cl::location(LimitFloatPrecision),
  67. cl::init(0));
  68. // Limit the width of DAG chains. This is important in general to prevent
  69. // prevent DAG-based analysis from blowing up. For example, alias analysis and
  70. // load clustering may not complete in reasonable time. It is difficult to
  71. // recognize and avoid this situation within each individual analysis, and
  72. // future analyses are likely to have the same behavior. Limiting DAG width is
  73. // the safe approach, and will be especially important with global DAGs.
  74. //
  75. // MaxParallelChains default is arbitrarily high to avoid affecting
  76. // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
  77. // sequence over this should have been converted to llvm.memcpy by the
  78. // frontend. It easy to induce this behavior with .ll code such as:
  79. // %buffer = alloca [4096 x i8]
  80. // %data = load [4096 x i8]* %argPtr
  81. // store [4096 x i8] %data, [4096 x i8]* %buffer
  82. static const unsigned MaxParallelChains = 64;
  83. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
  84. const SDValue *Parts, unsigned NumParts,
  85. EVT PartVT, EVT ValueVT);
  86. /// getCopyFromParts - Create a value that contains the specified legal parts
  87. /// combined into the value they represent. If the parts combine to a type
  88. /// larger then ValueVT then AssertOp can be used to specify whether the extra
  89. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  90. /// (ISD::AssertSext).
  91. static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL,
  92. const SDValue *Parts,
  93. unsigned NumParts, EVT PartVT, EVT ValueVT,
  94. ISD::NodeType AssertOp = ISD::DELETED_NODE) {
  95. if (ValueVT.isVector())
  96. return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT);
  97. assert(NumParts > 0 && "No parts to assemble!");
  98. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  99. SDValue Val = Parts[0];
  100. if (NumParts > 1) {
  101. // Assemble the value from multiple parts.
  102. if (ValueVT.isInteger()) {
  103. unsigned PartBits = PartVT.getSizeInBits();
  104. unsigned ValueBits = ValueVT.getSizeInBits();
  105. // Assemble the power of 2 part.
  106. unsigned RoundParts = NumParts & (NumParts - 1) ?
  107. 1 << Log2_32(NumParts) : NumParts;
  108. unsigned RoundBits = PartBits * RoundParts;
  109. EVT RoundVT = RoundBits == ValueBits ?
  110. ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
  111. SDValue Lo, Hi;
  112. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
  113. if (RoundParts > 2) {
  114. Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
  115. PartVT, HalfVT);
  116. Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
  117. RoundParts / 2, PartVT, HalfVT);
  118. } else {
  119. Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
  120. Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
  121. }
  122. if (TLI.isBigEndian())
  123. std::swap(Lo, Hi);
  124. Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
  125. if (RoundParts < NumParts) {
  126. // Assemble the trailing non-power-of-2 part.
  127. unsigned OddParts = NumParts - RoundParts;
  128. EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
  129. Hi = getCopyFromParts(DAG, DL,
  130. Parts + RoundParts, OddParts, PartVT, OddVT);
  131. // Combine the round and odd parts.
  132. Lo = Val;
  133. if (TLI.isBigEndian())
  134. std::swap(Lo, Hi);
  135. EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  136. Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
  137. Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
  138. DAG.getConstant(Lo.getValueType().getSizeInBits(),
  139. TLI.getPointerTy()));
  140. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
  141. Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
  142. }
  143. } else if (PartVT.isFloatingPoint()) {
  144. // FP split into multiple FP parts (for ppcf128)
  145. assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
  146. "Unexpected split");
  147. SDValue Lo, Hi;
  148. Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
  149. Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
  150. if (TLI.isBigEndian())
  151. std::swap(Lo, Hi);
  152. Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
  153. } else {
  154. // FP split into integer parts (soft fp)
  155. assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
  156. !PartVT.isVector() && "Unexpected split");
  157. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
  158. Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT);
  159. }
  160. }
  161. // There is now one part, held in Val. Correct it to match ValueVT.
  162. PartVT = Val.getValueType();
  163. if (PartVT == ValueVT)
  164. return Val;
  165. if (PartVT.isInteger() && ValueVT.isInteger()) {
  166. if (ValueVT.bitsLT(PartVT)) {
  167. // For a truncate, see if we have any information to
  168. // indicate whether the truncated bits will always be
  169. // zero or sign-extension.
  170. if (AssertOp != ISD::DELETED_NODE)
  171. Val = DAG.getNode(AssertOp, DL, PartVT, Val,
  172. DAG.getValueType(ValueVT));
  173. return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  174. }
  175. return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
  176. }
  177. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  178. // FP_ROUND's are always exact here.
  179. if (ValueVT.bitsLT(Val.getValueType()))
  180. return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
  181. DAG.getIntPtrConstant(1));
  182. return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
  183. }
  184. if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
  185. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  186. llvm_unreachable("Unknown mismatch!");
  187. return SDValue();
  188. }
  189. /// getCopyFromParts - Create a value that contains the specified legal parts
  190. /// combined into the value they represent. If the parts combine to a type
  191. /// larger then ValueVT then AssertOp can be used to specify whether the extra
  192. /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
  193. /// (ISD::AssertSext).
  194. static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
  195. const SDValue *Parts, unsigned NumParts,
  196. EVT PartVT, EVT ValueVT) {
  197. assert(ValueVT.isVector() && "Not a vector value");
  198. assert(NumParts > 0 && "No parts to assemble!");
  199. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  200. SDValue Val = Parts[0];
  201. // Handle a multi-element vector.
  202. if (NumParts > 1) {
  203. EVT IntermediateVT, RegisterVT;
  204. unsigned NumIntermediates;
  205. unsigned NumRegs =
  206. TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
  207. NumIntermediates, RegisterVT);
  208. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  209. NumParts = NumRegs; // Silence a compiler warning.
  210. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  211. assert(RegisterVT == Parts[0].getValueType() &&
  212. "Part type doesn't match part!");
  213. // Assemble the parts into intermediate operands.
  214. SmallVector<SDValue, 8> Ops(NumIntermediates);
  215. if (NumIntermediates == NumParts) {
  216. // If the register was not expanded, truncate or copy the value,
  217. // as appropriate.
  218. for (unsigned i = 0; i != NumParts; ++i)
  219. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
  220. PartVT, IntermediateVT);
  221. } else if (NumParts > 0) {
  222. // If the intermediate type was expanded, build the intermediate
  223. // operands from the parts.
  224. assert(NumParts % NumIntermediates == 0 &&
  225. "Must expand into a divisible number of parts!");
  226. unsigned Factor = NumParts / NumIntermediates;
  227. for (unsigned i = 0; i != NumIntermediates; ++i)
  228. Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
  229. PartVT, IntermediateVT);
  230. }
  231. // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
  232. // intermediate operands.
  233. Val = DAG.getNode(IntermediateVT.isVector() ?
  234. ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
  235. ValueVT, &Ops[0], NumIntermediates);
  236. }
  237. // There is now one part, held in Val. Correct it to match ValueVT.
  238. PartVT = Val.getValueType();
  239. if (PartVT == ValueVT)
  240. return Val;
  241. if (PartVT.isVector()) {
  242. // If the element type of the source/dest vectors are the same, but the
  243. // parts vector has more elements than the value vector, then we have a
  244. // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
  245. // elements we want.
  246. if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
  247. assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
  248. "Cannot narrow, it would be a lossy transformation");
  249. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  250. DAG.getIntPtrConstant(0));
  251. }
  252. // Vector/Vector bitcast.
  253. return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
  254. }
  255. assert(ValueVT.getVectorElementType() == PartVT &&
  256. ValueVT.getVectorNumElements() == 1 &&
  257. "Only trivial scalar-to-vector conversions should get here!");
  258. return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
  259. }
  260. static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl,
  261. SDValue Val, SDValue *Parts, unsigned NumParts,
  262. EVT PartVT);
  263. /// getCopyToParts - Create a series of nodes that contain the specified value
  264. /// split into legal parts. If the parts contain more bits than Val, then, for
  265. /// integers, ExtendKind can be used to specify how to generate the extra bits.
  266. static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL,
  267. SDValue Val, SDValue *Parts, unsigned NumParts,
  268. EVT PartVT,
  269. ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
  270. EVT ValueVT = Val.getValueType();
  271. // Handle the vector case separately.
  272. if (ValueVT.isVector())
  273. return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT);
  274. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  275. unsigned PartBits = PartVT.getSizeInBits();
  276. unsigned OrigNumParts = NumParts;
  277. assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
  278. if (NumParts == 0)
  279. return;
  280. assert(!ValueVT.isVector() && "Vector case handled elsewhere");
  281. if (PartVT == ValueVT) {
  282. assert(NumParts == 1 && "No-op copy with multiple parts!");
  283. Parts[0] = Val;
  284. return;
  285. }
  286. if (NumParts * PartBits > ValueVT.getSizeInBits()) {
  287. // If the parts cover more bits than the value has, promote the value.
  288. if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
  289. assert(NumParts == 1 && "Do not know what to promote to!");
  290. Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
  291. } else {
  292. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  293. "Unknown mismatch!");
  294. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  295. Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
  296. }
  297. } else if (PartBits == ValueVT.getSizeInBits()) {
  298. // Different types of the same size.
  299. assert(NumParts == 1 && PartVT != ValueVT);
  300. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  301. } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
  302. // If the parts cover less bits than value has, truncate the value.
  303. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  304. "Unknown mismatch!");
  305. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  306. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  307. }
  308. // The value may have changed - recompute ValueVT.
  309. ValueVT = Val.getValueType();
  310. assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
  311. "Failed to tile the value with PartVT!");
  312. if (NumParts == 1) {
  313. assert(PartVT == ValueVT && "Type conversion failed!");
  314. Parts[0] = Val;
  315. return;
  316. }
  317. // Expand the value into multiple parts.
  318. if (NumParts & (NumParts - 1)) {
  319. // The number of parts is not a power of 2. Split off and copy the tail.
  320. assert(PartVT.isInteger() && ValueVT.isInteger() &&
  321. "Do not know what to expand to!");
  322. unsigned RoundParts = 1 << Log2_32(NumParts);
  323. unsigned RoundBits = RoundParts * PartBits;
  324. unsigned OddParts = NumParts - RoundParts;
  325. SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
  326. DAG.getIntPtrConstant(RoundBits));
  327. getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT);
  328. if (TLI.isBigEndian())
  329. // The odd parts were reversed by getCopyToParts - unreverse them.
  330. std::reverse(Parts + RoundParts, Parts + NumParts);
  331. NumParts = RoundParts;
  332. ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
  333. Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
  334. }
  335. // The number of parts is a power of 2. Repeatedly bisect the value using
  336. // EXTRACT_ELEMENT.
  337. Parts[0] = DAG.getNode(ISD::BITCAST, DL,
  338. EVT::getIntegerVT(*DAG.getContext(),
  339. ValueVT.getSizeInBits()),
  340. Val);
  341. for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
  342. for (unsigned i = 0; i < NumParts; i += StepSize) {
  343. unsigned ThisBits = StepSize * PartBits / 2;
  344. EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
  345. SDValue &Part0 = Parts[i];
  346. SDValue &Part1 = Parts[i+StepSize/2];
  347. Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  348. ThisVT, Part0, DAG.getIntPtrConstant(1));
  349. Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
  350. ThisVT, Part0, DAG.getIntPtrConstant(0));
  351. if (ThisBits == PartBits && ThisVT != PartVT) {
  352. Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
  353. Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
  354. }
  355. }
  356. }
  357. if (TLI.isBigEndian())
  358. std::reverse(Parts, Parts + OrigNumParts);
  359. }
  360. /// getCopyToPartsVector - Create a series of nodes that contain the specified
  361. /// value split into legal parts.
  362. static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL,
  363. SDValue Val, SDValue *Parts, unsigned NumParts,
  364. EVT PartVT) {
  365. EVT ValueVT = Val.getValueType();
  366. assert(ValueVT.isVector() && "Not a vector");
  367. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  368. if (NumParts == 1) {
  369. if (PartVT == ValueVT) {
  370. // Nothing to do.
  371. } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
  372. // Bitconvert vector->vector case.
  373. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  374. } else if (PartVT.isVector() &&
  375. PartVT.getVectorElementType() == ValueVT.getVectorElementType()&&
  376. PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
  377. EVT ElementVT = PartVT.getVectorElementType();
  378. // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
  379. // undef elements.
  380. SmallVector<SDValue, 16> Ops;
  381. for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
  382. Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  383. ElementVT, Val, DAG.getIntPtrConstant(i)));
  384. for (unsigned i = ValueVT.getVectorNumElements(),
  385. e = PartVT.getVectorNumElements(); i != e; ++i)
  386. Ops.push_back(DAG.getUNDEF(ElementVT));
  387. Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
  388. // FIXME: Use CONCAT for 2x -> 4x.
  389. //SDValue UndefElts = DAG.getUNDEF(VectorTy);
  390. //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
  391. } else {
  392. // Vector -> scalar conversion.
  393. assert(ValueVT.getVectorElementType() == PartVT &&
  394. ValueVT.getVectorNumElements() == 1 &&
  395. "Only trivial vector-to-scalar conversions should get here!");
  396. Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  397. PartVT, Val, DAG.getIntPtrConstant(0));
  398. }
  399. Parts[0] = Val;
  400. return;
  401. }
  402. // Handle a multi-element vector.
  403. EVT IntermediateVT, RegisterVT;
  404. unsigned NumIntermediates;
  405. unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
  406. IntermediateVT,
  407. NumIntermediates, RegisterVT);
  408. unsigned NumElements = ValueVT.getVectorNumElements();
  409. assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
  410. NumParts = NumRegs; // Silence a compiler warning.
  411. assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
  412. // Split the vector into intermediate operands.
  413. SmallVector<SDValue, 8> Ops(NumIntermediates);
  414. for (unsigned i = 0; i != NumIntermediates; ++i) {
  415. if (IntermediateVT.isVector())
  416. Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
  417. IntermediateVT, Val,
  418. DAG.getIntPtrConstant(i * (NumElements / NumIntermediates)));
  419. else
  420. Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
  421. IntermediateVT, Val, DAG.getIntPtrConstant(i));
  422. }
  423. // Split the intermediate operands into legal parts.
  424. if (NumParts == NumIntermediates) {
  425. // If the register was not expanded, promote or copy the value,
  426. // as appropriate.
  427. for (unsigned i = 0; i != NumParts; ++i)
  428. getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT);
  429. } else if (NumParts > 0) {
  430. // If the intermediate type was expanded, split each the value into
  431. // legal parts.
  432. assert(NumParts % NumIntermediates == 0 &&
  433. "Must expand into a divisible number of parts!");
  434. unsigned Factor = NumParts / NumIntermediates;
  435. for (unsigned i = 0; i != NumIntermediates; ++i)
  436. getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT);
  437. }
  438. }
  439. namespace {
  440. /// RegsForValue - This struct represents the registers (physical or virtual)
  441. /// that a particular set of values is assigned, and the type information
  442. /// about the value. The most common situation is to represent one value at a
  443. /// time, but struct or array values are handled element-wise as multiple
  444. /// values. The splitting of aggregates is performed recursively, so that we
  445. /// never have aggregate-typed registers. The values at this point do not
  446. /// necessarily have legal types, so each value may require one or more
  447. /// registers of some legal type.
  448. ///
  449. struct RegsForValue {
  450. /// ValueVTs - The value types of the values, which may not be legal, and
  451. /// may need be promoted or synthesized from one or more registers.
  452. ///
  453. SmallVector<EVT, 4> ValueVTs;
  454. /// RegVTs - The value types of the registers. This is the same size as
  455. /// ValueVTs and it records, for each value, what the type of the assigned
  456. /// register or registers are. (Individual values are never synthesized
  457. /// from more than one type of register.)
  458. ///
  459. /// With virtual registers, the contents of RegVTs is redundant with TLI's
  460. /// getRegisterType member function, however when with physical registers
  461. /// it is necessary to have a separate record of the types.
  462. ///
  463. SmallVector<EVT, 4> RegVTs;
  464. /// Regs - This list holds the registers assigned to the values.
  465. /// Each legal or promoted value requires one register, and each
  466. /// expanded value requires multiple registers.
  467. ///
  468. SmallVector<unsigned, 4> Regs;
  469. RegsForValue() {}
  470. RegsForValue(const SmallVector<unsigned, 4> &regs,
  471. EVT regvt, EVT valuevt)
  472. : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
  473. RegsForValue(LLVMContext &Context, const TargetLowering &tli,
  474. unsigned Reg, const Type *Ty) {
  475. ComputeValueVTs(tli, Ty, ValueVTs);
  476. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  477. EVT ValueVT = ValueVTs[Value];
  478. unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
  479. EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
  480. for (unsigned i = 0; i != NumRegs; ++i)
  481. Regs.push_back(Reg + i);
  482. RegVTs.push_back(RegisterVT);
  483. Reg += NumRegs;
  484. }
  485. }
  486. /// areValueTypesLegal - Return true if types of all the values are legal.
  487. bool areValueTypesLegal(const TargetLowering &TLI) {
  488. for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
  489. EVT RegisterVT = RegVTs[Value];
  490. if (!TLI.isTypeLegal(RegisterVT))
  491. return false;
  492. }
  493. return true;
  494. }
  495. /// append - Add the specified values to this one.
  496. void append(const RegsForValue &RHS) {
  497. ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
  498. RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
  499. Regs.append(RHS.Regs.begin(), RHS.Regs.end());
  500. }
  501. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  502. /// this value and returns the result as a ValueVTs value. This uses
  503. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  504. /// If the Flag pointer is NULL, no flag is used.
  505. SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
  506. DebugLoc dl,
  507. SDValue &Chain, SDValue *Flag) const;
  508. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  509. /// specified value into the registers specified by this object. This uses
  510. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  511. /// If the Flag pointer is NULL, no flag is used.
  512. void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
  513. SDValue &Chain, SDValue *Flag) const;
  514. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  515. /// operand list. This adds the code marker, matching input operand index
  516. /// (if applicable), and includes the number of values added into it.
  517. void AddInlineAsmOperands(unsigned Kind,
  518. bool HasMatching, unsigned MatchingIdx,
  519. SelectionDAG &DAG,
  520. std::vector<SDValue> &Ops) const;
  521. };
  522. }
  523. /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
  524. /// this value and returns the result as a ValueVT value. This uses
  525. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  526. /// If the Flag pointer is NULL, no flag is used.
  527. SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
  528. FunctionLoweringInfo &FuncInfo,
  529. DebugLoc dl,
  530. SDValue &Chain, SDValue *Flag) const {
  531. // A Value with type {} or [0 x %t] needs no registers.
  532. if (ValueVTs.empty())
  533. return SDValue();
  534. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  535. // Assemble the legal parts into the final values.
  536. SmallVector<SDValue, 4> Values(ValueVTs.size());
  537. SmallVector<SDValue, 8> Parts;
  538. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  539. // Copy the legal parts from the registers.
  540. EVT ValueVT = ValueVTs[Value];
  541. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  542. EVT RegisterVT = RegVTs[Value];
  543. Parts.resize(NumRegs);
  544. for (unsigned i = 0; i != NumRegs; ++i) {
  545. SDValue P;
  546. if (Flag == 0) {
  547. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
  548. } else {
  549. P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
  550. *Flag = P.getValue(2);
  551. }
  552. Chain = P.getValue(1);
  553. Parts[i] = P;
  554. // If the source register was virtual and if we know something about it,
  555. // add an assert node.
  556. if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
  557. !RegisterVT.isInteger() || RegisterVT.isVector())
  558. continue;
  559. const FunctionLoweringInfo::LiveOutInfo *LOI =
  560. FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
  561. if (!LOI)
  562. continue;
  563. unsigned RegSize = RegisterVT.getSizeInBits();
  564. unsigned NumSignBits = LOI->NumSignBits;
  565. unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
  566. // FIXME: We capture more information than the dag can represent. For
  567. // now, just use the tightest assertzext/assertsext possible.
  568. bool isSExt = true;
  569. EVT FromVT(MVT::Other);
  570. if (NumSignBits == RegSize)
  571. isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
  572. else if (NumZeroBits >= RegSize-1)
  573. isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
  574. else if (NumSignBits > RegSize-8)
  575. isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
  576. else if (NumZeroBits >= RegSize-8)
  577. isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
  578. else if (NumSignBits > RegSize-16)
  579. isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
  580. else if (NumZeroBits >= RegSize-16)
  581. isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
  582. else if (NumSignBits > RegSize-32)
  583. isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
  584. else if (NumZeroBits >= RegSize-32)
  585. isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
  586. else
  587. continue;
  588. // Add an assertion node.
  589. assert(FromVT != MVT::Other);
  590. Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
  591. RegisterVT, P, DAG.getValueType(FromVT));
  592. }
  593. Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
  594. NumRegs, RegisterVT, ValueVT);
  595. Part += NumRegs;
  596. Parts.clear();
  597. }
  598. return DAG.getNode(ISD::MERGE_VALUES, dl,
  599. DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
  600. &Values[0], ValueVTs.size());
  601. }
  602. /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
  603. /// specified value into the registers specified by this object. This uses
  604. /// Chain/Flag as the input and updates them for the output Chain/Flag.
  605. /// If the Flag pointer is NULL, no flag is used.
  606. void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
  607. SDValue &Chain, SDValue *Flag) const {
  608. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  609. // Get the list of the values's legal parts.
  610. unsigned NumRegs = Regs.size();
  611. SmallVector<SDValue, 8> Parts(NumRegs);
  612. for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
  613. EVT ValueVT = ValueVTs[Value];
  614. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
  615. EVT RegisterVT = RegVTs[Value];
  616. getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
  617. &Parts[Part], NumParts, RegisterVT);
  618. Part += NumParts;
  619. }
  620. // Copy the parts into the registers.
  621. SmallVector<SDValue, 8> Chains(NumRegs);
  622. for (unsigned i = 0; i != NumRegs; ++i) {
  623. SDValue Part;
  624. if (Flag == 0) {
  625. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
  626. } else {
  627. Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
  628. *Flag = Part.getValue(1);
  629. }
  630. Chains[i] = Part.getValue(0);
  631. }
  632. if (NumRegs == 1 || Flag)
  633. // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
  634. // flagged to it. That is the CopyToReg nodes and the user are considered
  635. // a single scheduling unit. If we create a TokenFactor and return it as
  636. // chain, then the TokenFactor is both a predecessor (operand) of the
  637. // user as well as a successor (the TF operands are flagged to the user).
  638. // c1, f1 = CopyToReg
  639. // c2, f2 = CopyToReg
  640. // c3 = TokenFactor c1, c2
  641. // ...
  642. // = op c3, ..., f2
  643. Chain = Chains[NumRegs-1];
  644. else
  645. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
  646. }
  647. /// AddInlineAsmOperands - Add this value to the specified inlineasm node
  648. /// operand list. This adds the code marker and includes the number of
  649. /// values added into it.
  650. void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
  651. unsigned MatchingIdx,
  652. SelectionDAG &DAG,
  653. std::vector<SDValue> &Ops) const {
  654. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  655. unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
  656. if (HasMatching)
  657. Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
  658. SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
  659. Ops.push_back(Res);
  660. for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
  661. unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
  662. EVT RegisterVT = RegVTs[Value];
  663. for (unsigned i = 0; i != NumRegs; ++i) {
  664. assert(Reg < Regs.size() && "Mismatch in # registers expected");
  665. Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
  666. }
  667. }
  668. }
  669. void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
  670. AA = &aa;
  671. GFI = gfi;
  672. TD = DAG.getTarget().getTargetData();
  673. }
  674. /// clear - Clear out the current SelectionDAG and the associated
  675. /// state and prepare this SelectionDAGBuilder object to be used
  676. /// for a new block. This doesn't clear out information about
  677. /// additional blocks that are needed to complete switch lowering
  678. /// or PHI node updating; that information is cleared out as it is
  679. /// consumed.
  680. void SelectionDAGBuilder::clear() {
  681. NodeMap.clear();
  682. UnusedArgNodeMap.clear();
  683. PendingLoads.clear();
  684. PendingExports.clear();
  685. DanglingDebugInfoMap.clear();
  686. CurDebugLoc = DebugLoc();
  687. HasTailCall = false;
  688. }
  689. /// getRoot - Return the current virtual root of the Selection DAG,
  690. /// flushing any PendingLoad items. This must be done before emitting
  691. /// a store or any other node that may need to be ordered after any
  692. /// prior load instructions.
  693. ///
  694. SDValue SelectionDAGBuilder::getRoot() {
  695. if (PendingLoads.empty())
  696. return DAG.getRoot();
  697. if (PendingLoads.size() == 1) {
  698. SDValue Root = PendingLoads[0];
  699. DAG.setRoot(Root);
  700. PendingLoads.clear();
  701. return Root;
  702. }
  703. // Otherwise, we have to make a token factor node.
  704. SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  705. &PendingLoads[0], PendingLoads.size());
  706. PendingLoads.clear();
  707. DAG.setRoot(Root);
  708. return Root;
  709. }
  710. /// getControlRoot - Similar to getRoot, but instead of flushing all the
  711. /// PendingLoad items, flush all the PendingExports items. It is necessary
  712. /// to do this before emitting a terminator instruction.
  713. ///
  714. SDValue SelectionDAGBuilder::getControlRoot() {
  715. SDValue Root = DAG.getRoot();
  716. if (PendingExports.empty())
  717. return Root;
  718. // Turn all of the CopyToReg chains into one factored node.
  719. if (Root.getOpcode() != ISD::EntryToken) {
  720. unsigned i = 0, e = PendingExports.size();
  721. for (; i != e; ++i) {
  722. assert(PendingExports[i].getNode()->getNumOperands() > 1);
  723. if (PendingExports[i].getNode()->getOperand(0) == Root)
  724. break; // Don't add the root if we already indirectly depend on it.
  725. }
  726. if (i == e)
  727. PendingExports.push_back(Root);
  728. }
  729. Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  730. &PendingExports[0],
  731. PendingExports.size());
  732. PendingExports.clear();
  733. DAG.setRoot(Root);
  734. return Root;
  735. }
  736. void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
  737. if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
  738. DAG.AssignOrdering(Node, SDNodeOrder);
  739. for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
  740. AssignOrderingToNode(Node->getOperand(I).getNode());
  741. }
  742. void SelectionDAGBuilder::visit(const Instruction &I) {
  743. // Set up outgoing PHI node register values before emitting the terminator.
  744. if (isa<TerminatorInst>(&I))
  745. HandlePHINodesInSuccessorBlocks(I.getParent());
  746. CurDebugLoc = I.getDebugLoc();
  747. visit(I.getOpcode(), I);
  748. if (!isa<TerminatorInst>(&I) && !HasTailCall)
  749. CopyToExportRegsIfNeeded(&I);
  750. CurDebugLoc = DebugLoc();
  751. }
  752. void SelectionDAGBuilder::visitPHI(const PHINode &) {
  753. llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
  754. }
  755. void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
  756. // Note: this doesn't use InstVisitor, because it has to work with
  757. // ConstantExpr's in addition to instructions.
  758. switch (Opcode) {
  759. default: llvm_unreachable("Unknown instruction type encountered!");
  760. // Build the switch statement using the Instruction.def file.
  761. #define HANDLE_INST(NUM, OPCODE, CLASS) \
  762. case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
  763. #include "llvm/Instruction.def"
  764. }
  765. // Assign the ordering to the freshly created DAG nodes.
  766. if (NodeMap.count(&I)) {
  767. ++SDNodeOrder;
  768. AssignOrderingToNode(getValue(&I).getNode());
  769. }
  770. }
  771. // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
  772. // generate the debug data structures now that we've seen its definition.
  773. void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
  774. SDValue Val) {
  775. DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
  776. if (DDI.getDI()) {
  777. const DbgValueInst *DI = DDI.getDI();
  778. DebugLoc dl = DDI.getdl();
  779. unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
  780. MDNode *Variable = DI->getVariable();
  781. uint64_t Offset = DI->getOffset();
  782. SDDbgValue *SDV;
  783. if (Val.getNode()) {
  784. if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
  785. SDV = DAG.getDbgValue(Variable, Val.getNode(),
  786. Val.getResNo(), Offset, dl, DbgSDNodeOrder);
  787. DAG.AddDbgValue(SDV, Val.getNode(), false);
  788. }
  789. } else
  790. DEBUG(dbgs() << "Dropping debug info for " << DI);
  791. DanglingDebugInfoMap[V] = DanglingDebugInfo();
  792. }
  793. }
  794. // getValue - Return an SDValue for the given Value.
  795. SDValue SelectionDAGBuilder::getValue(const Value *V) {
  796. // If we already have an SDValue for this value, use it. It's important
  797. // to do this first, so that we don't create a CopyFromReg if we already
  798. // have a regular SDValue.
  799. SDValue &N = NodeMap[V];
  800. if (N.getNode()) return N;
  801. // If there's a virtual register allocated and initialized for this
  802. // value, use it.
  803. DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
  804. if (It != FuncInfo.ValueMap.end()) {
  805. unsigned InReg = It->second;
  806. RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
  807. SDValue Chain = DAG.getEntryNode();
  808. N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain,NULL);
  809. resolveDanglingDebugInfo(V, N);
  810. return N;
  811. }
  812. // Otherwise create a new SDValue and remember it.
  813. SDValue Val = getValueImpl(V);
  814. NodeMap[V] = Val;
  815. resolveDanglingDebugInfo(V, Val);
  816. return Val;
  817. }
  818. /// getNonRegisterValue - Return an SDValue for the given Value, but
  819. /// don't look in FuncInfo.ValueMap for a virtual register.
  820. SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
  821. // If we already have an SDValue for this value, use it.
  822. SDValue &N = NodeMap[V];
  823. if (N.getNode()) return N;
  824. // Otherwise create a new SDValue and remember it.
  825. SDValue Val = getValueImpl(V);
  826. NodeMap[V] = Val;
  827. resolveDanglingDebugInfo(V, Val);
  828. return Val;
  829. }
  830. /// getValueImpl - Helper function for getValue and getNonRegisterValue.
  831. /// Create an SDValue for the given value.
  832. SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
  833. if (const Constant *C = dyn_cast<Constant>(V)) {
  834. EVT VT = TLI.getValueType(V->getType(), true);
  835. if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
  836. return DAG.getConstant(*CI, VT);
  837. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
  838. return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT);
  839. if (isa<ConstantPointerNull>(C))
  840. return DAG.getConstant(0, TLI.getPointerTy());
  841. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
  842. return DAG.getConstantFP(*CFP, VT);
  843. if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
  844. return DAG.getUNDEF(VT);
  845. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  846. visit(CE->getOpcode(), *CE);
  847. SDValue N1 = NodeMap[V];
  848. assert(N1.getNode() && "visit didn't populate the NodeMap!");
  849. return N1;
  850. }
  851. if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
  852. SmallVector<SDValue, 4> Constants;
  853. for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
  854. OI != OE; ++OI) {
  855. SDNode *Val = getValue(*OI).getNode();
  856. // If the operand is an empty aggregate, there are no values.
  857. if (!Val) continue;
  858. // Add each leaf value from the operand to the Constants list
  859. // to form a flattened list of all the values.
  860. for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
  861. Constants.push_back(SDValue(Val, i));
  862. }
  863. return DAG.getMergeValues(&Constants[0], Constants.size(),
  864. getCurDebugLoc());
  865. }
  866. if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
  867. assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
  868. "Unknown struct or array constant!");
  869. SmallVector<EVT, 4> ValueVTs;
  870. ComputeValueVTs(TLI, C->getType(), ValueVTs);
  871. unsigned NumElts = ValueVTs.size();
  872. if (NumElts == 0)
  873. return SDValue(); // empty struct
  874. SmallVector<SDValue, 4> Constants(NumElts);
  875. for (unsigned i = 0; i != NumElts; ++i) {
  876. EVT EltVT = ValueVTs[i];
  877. if (isa<UndefValue>(C))
  878. Constants[i] = DAG.getUNDEF(EltVT);
  879. else if (EltVT.isFloatingPoint())
  880. Constants[i] = DAG.getConstantFP(0, EltVT);
  881. else
  882. Constants[i] = DAG.getConstant(0, EltVT);
  883. }
  884. return DAG.getMergeValues(&Constants[0], NumElts,
  885. getCurDebugLoc());
  886. }
  887. if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
  888. return DAG.getBlockAddress(BA, VT);
  889. const VectorType *VecTy = cast<VectorType>(V->getType());
  890. unsigned NumElements = VecTy->getNumElements();
  891. // Now that we know the number and type of the elements, get that number of
  892. // elements into the Ops array based on what kind of constant it is.
  893. SmallVector<SDValue, 16> Ops;
  894. if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
  895. for (unsigned i = 0; i != NumElements; ++i)
  896. Ops.push_back(getValue(CP->getOperand(i)));
  897. } else {
  898. assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
  899. EVT EltVT = TLI.getValueType(VecTy->getElementType());
  900. SDValue Op;
  901. if (EltVT.isFloatingPoint())
  902. Op = DAG.getConstantFP(0, EltVT);
  903. else
  904. Op = DAG.getConstant(0, EltVT);
  905. Ops.assign(NumElements, Op);
  906. }
  907. // Create a BUILD_VECTOR node.
  908. return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
  909. VT, &Ops[0], Ops.size());
  910. }
  911. // If this is a static alloca, generate it as the frameindex instead of
  912. // computation.
  913. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  914. DenseMap<const AllocaInst*, int>::iterator SI =
  915. FuncInfo.StaticAllocaMap.find(AI);
  916. if (SI != FuncInfo.StaticAllocaMap.end())
  917. return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
  918. }
  919. // If this is an instruction which fast-isel has deferred, select it now.
  920. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  921. unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
  922. RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
  923. SDValue Chain = DAG.getEntryNode();
  924. return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
  925. }
  926. llvm_unreachable("Can't get register for value!");
  927. return SDValue();
  928. }
  929. void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
  930. SDValue Chain = getControlRoot();
  931. SmallVector<ISD::OutputArg, 8> Outs;
  932. SmallVector<SDValue, 8> OutVals;
  933. if (!FuncInfo.CanLowerReturn) {
  934. unsigned DemoteReg = FuncInfo.DemoteRegister;
  935. const Function *F = I.getParent()->getParent();
  936. // Emit a store of the return value through the virtual register.
  937. // Leave Outs empty so that LowerReturn won't try to load return
  938. // registers the usual way.
  939. SmallVector<EVT, 1> PtrValueVTs;
  940. ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
  941. PtrValueVTs);
  942. SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
  943. SDValue RetOp = getValue(I.getOperand(0));
  944. SmallVector<EVT, 4> ValueVTs;
  945. SmallVector<uint64_t, 4> Offsets;
  946. ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
  947. unsigned NumValues = ValueVTs.size();
  948. SmallVector<SDValue, 4> Chains(NumValues);
  949. for (unsigned i = 0; i != NumValues; ++i) {
  950. SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  951. RetPtr.getValueType(), RetPtr,
  952. DAG.getIntPtrConstant(Offsets[i]));
  953. Chains[i] =
  954. DAG.getStore(Chain, getCurDebugLoc(),
  955. SDValue(RetOp.getNode(), RetOp.getResNo() + i),
  956. // FIXME: better loc info would be nice.
  957. Add, MachinePointerInfo(), false, false, 0);
  958. }
  959. Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  960. MVT::Other, &Chains[0], NumValues);
  961. } else if (I.getNumOperands() != 0) {
  962. SmallVector<EVT, 4> ValueVTs;
  963. ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
  964. unsigned NumValues = ValueVTs.size();
  965. if (NumValues) {
  966. SDValue RetOp = getValue(I.getOperand(0));
  967. for (unsigned j = 0, f = NumValues; j != f; ++j) {
  968. EVT VT = ValueVTs[j];
  969. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  970. const Function *F = I.getParent()->getParent();
  971. if (F->paramHasAttr(0, Attribute::SExt))
  972. ExtendKind = ISD::SIGN_EXTEND;
  973. else if (F->paramHasAttr(0, Attribute::ZExt))
  974. ExtendKind = ISD::ZERO_EXTEND;
  975. if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
  976. VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
  977. unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
  978. EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
  979. SmallVector<SDValue, 4> Parts(NumParts);
  980. getCopyToParts(DAG, getCurDebugLoc(),
  981. SDValue(RetOp.getNode(), RetOp.getResNo() + j),
  982. &Parts[0], NumParts, PartVT, ExtendKind);
  983. // 'inreg' on function refers to return value
  984. ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
  985. if (F->paramHasAttr(0, Attribute::InReg))
  986. Flags.setInReg();
  987. // Propagate extension type if any
  988. if (ExtendKind == ISD::SIGN_EXTEND)
  989. Flags.setSExt();
  990. else if (ExtendKind == ISD::ZERO_EXTEND)
  991. Flags.setZExt();
  992. for (unsigned i = 0; i < NumParts; ++i) {
  993. Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
  994. /*isfixed=*/true));
  995. OutVals.push_back(Parts[i]);
  996. }
  997. }
  998. }
  999. }
  1000. bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
  1001. CallingConv::ID CallConv =
  1002. DAG.getMachineFunction().getFunction()->getCallingConv();
  1003. Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
  1004. Outs, OutVals, getCurDebugLoc(), DAG);
  1005. // Verify that the target's LowerReturn behaved as expected.
  1006. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  1007. "LowerReturn didn't return a valid chain!");
  1008. // Update the DAG with the new chain value resulting from return lowering.
  1009. DAG.setRoot(Chain);
  1010. }
  1011. /// CopyToExportRegsIfNeeded - If the given value has virtual registers
  1012. /// created for it, emit nodes to copy the value into the virtual
  1013. /// registers.
  1014. void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
  1015. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  1016. if (VMI != FuncInfo.ValueMap.end()) {
  1017. assert(!V->use_empty() && "Unused value assigned virtual registers!");
  1018. CopyValueToVirtualRegister(V, VMI->second);
  1019. }
  1020. }
  1021. /// ExportFromCurrentBlock - If this condition isn't known to be exported from
  1022. /// the current basic block, add it to ValueMap now so that we'll get a
  1023. /// CopyTo/FromReg.
  1024. void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
  1025. // No need to export constants.
  1026. if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
  1027. // Already exported?
  1028. if (FuncInfo.isExportedInst(V)) return;
  1029. unsigned Reg = FuncInfo.InitializeRegForValue(V);
  1030. CopyValueToVirtualRegister(V, Reg);
  1031. }
  1032. bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
  1033. const BasicBlock *FromBB) {
  1034. // The operands of the setcc have to be in this block. We don't know
  1035. // how to export them from some other block.
  1036. if (const Instruction *VI = dyn_cast<Instruction>(V)) {
  1037. // Can export from current BB.
  1038. if (VI->getParent() == FromBB)
  1039. return true;
  1040. // Is already exported, noop.
  1041. return FuncInfo.isExportedInst(V);
  1042. }
  1043. // If this is an argument, we can export it if the BB is the entry block or
  1044. // if it is already exported.
  1045. if (isa<Argument>(V)) {
  1046. if (FromBB == &FromBB->getParent()->getEntryBlock())
  1047. return true;
  1048. // Otherwise, can only export this if it is already exported.
  1049. return FuncInfo.isExportedInst(V);
  1050. }
  1051. // Otherwise, constants can always be exported.
  1052. return true;
  1053. }
  1054. static bool InBlock(const Value *V, const BasicBlock *BB) {
  1055. if (const Instruction *I = dyn_cast<Instruction>(V))
  1056. return I->getParent() == BB;
  1057. return true;
  1058. }
  1059. /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
  1060. /// This function emits a branch and is used at the leaves of an OR or an
  1061. /// AND operator tree.
  1062. ///
  1063. void
  1064. SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
  1065. MachineBasicBlock *TBB,
  1066. MachineBasicBlock *FBB,
  1067. MachineBasicBlock *CurBB,
  1068. MachineBasicBlock *SwitchBB) {
  1069. const BasicBlock *BB = CurBB->getBasicBlock();
  1070. // If the leaf of the tree is a comparison, merge the condition into
  1071. // the caseblock.
  1072. if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
  1073. // The operands of the cmp have to be in this block. We don't know
  1074. // how to export them from some other block. If this is the first block
  1075. // of the sequence, no exporting is needed.
  1076. if (CurBB == SwitchBB ||
  1077. (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
  1078. isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
  1079. ISD::CondCode Condition;
  1080. if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
  1081. Condition = getICmpCondCode(IC->getPredicate());
  1082. } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
  1083. Condition = getFCmpCondCode(FC->getPredicate());
  1084. } else {
  1085. Condition = ISD::SETEQ; // silence warning.
  1086. llvm_unreachable("Unknown compare instruction");
  1087. }
  1088. CaseBlock CB(Condition, BOp->getOperand(0),
  1089. BOp->getOperand(1), NULL, TBB, FBB, CurBB);
  1090. SwitchCases.push_back(CB);
  1091. return;
  1092. }
  1093. }
  1094. // Create a CaseBlock record representing this branch.
  1095. CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
  1096. NULL, TBB, FBB, CurBB);
  1097. SwitchCases.push_back(CB);
  1098. }
  1099. /// FindMergedConditions - If Cond is an expression like
  1100. void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
  1101. MachineBasicBlock *TBB,
  1102. MachineBasicBlock *FBB,
  1103. MachineBasicBlock *CurBB,
  1104. MachineBasicBlock *SwitchBB,
  1105. unsigned Opc) {
  1106. // If this node is not part of the or/and tree, emit it as a branch.
  1107. const Instruction *BOp = dyn_cast<Instruction>(Cond);
  1108. if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
  1109. (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
  1110. BOp->getParent() != CurBB->getBasicBlock() ||
  1111. !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
  1112. !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
  1113. EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
  1114. return;
  1115. }
  1116. // Create TmpBB after CurBB.
  1117. MachineFunction::iterator BBI = CurBB;
  1118. MachineFunction &MF = DAG.getMachineFunction();
  1119. MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
  1120. CurBB->getParent()->insert(++BBI, TmpBB);
  1121. if (Opc == Instruction::Or) {
  1122. // Codegen X | Y as:
  1123. // jmp_if_X TBB
  1124. // jmp TmpBB
  1125. // TmpBB:
  1126. // jmp_if_Y TBB
  1127. // jmp FBB
  1128. //
  1129. // Emit the LHS condition.
  1130. FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
  1131. // Emit the RHS condition into TmpBB.
  1132. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
  1133. } else {
  1134. assert(Opc == Instruction::And && "Unknown merge op!");
  1135. // Codegen X & Y as:
  1136. // jmp_if_X TmpBB
  1137. // jmp FBB
  1138. // TmpBB:
  1139. // jmp_if_Y TBB
  1140. // jmp FBB
  1141. //
  1142. // This requires creation of TmpBB after CurBB.
  1143. // Emit the LHS condition.
  1144. FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
  1145. // Emit the RHS condition into TmpBB.
  1146. FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
  1147. }
  1148. }
  1149. /// If the set of cases should be emitted as a series of branches, return true.
  1150. /// If we should emit this as a bunch of and/or'd together conditions, return
  1151. /// false.
  1152. bool
  1153. SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
  1154. if (Cases.size() != 2) return true;
  1155. // If this is two comparisons of the same values or'd or and'd together, they
  1156. // will get folded into a single comparison, so don't emit two blocks.
  1157. if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
  1158. Cases[0].CmpRHS == Cases[1].CmpRHS) ||
  1159. (Cases[0].CmpRHS == Cases[1].CmpLHS &&
  1160. Cases[0].CmpLHS == Cases[1].CmpRHS)) {
  1161. return false;
  1162. }
  1163. // Handle: (X != null) | (Y != null) --> (X|Y) != 0
  1164. // Handle: (X == null) & (Y == null) --> (X|Y) == 0
  1165. if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
  1166. Cases[0].CC == Cases[1].CC &&
  1167. isa<Constant>(Cases[0].CmpRHS) &&
  1168. cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
  1169. if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
  1170. return false;
  1171. if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
  1172. return false;
  1173. }
  1174. return true;
  1175. }
  1176. void SelectionDAGBuilder::visitBr(const BranchInst &I) {
  1177. MachineBasicBlock *BrMBB = FuncInfo.MBB;
  1178. // Update machine-CFG edges.
  1179. MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
  1180. // Figure out which block is immediately after the current one.
  1181. MachineBasicBlock *NextBlock = 0;
  1182. MachineFunction::iterator BBI = BrMBB;
  1183. if (++BBI != FuncInfo.MF->end())
  1184. NextBlock = BBI;
  1185. if (I.isUnconditional()) {
  1186. // Update machine-CFG edges.
  1187. BrMBB->addSuccessor(Succ0MBB);
  1188. // If this is not a fall-through branch, emit the branch.
  1189. if (Succ0MBB != NextBlock)
  1190. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1191. MVT::Other, getControlRoot(),
  1192. DAG.getBasicBlock(Succ0MBB)));
  1193. return;
  1194. }
  1195. // If this condition is one of the special cases we handle, do special stuff
  1196. // now.
  1197. const Value *CondVal = I.getCondition();
  1198. MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
  1199. // If this is a series of conditions that are or'd or and'd together, emit
  1200. // this as a sequence of branches instead of setcc's with and/or operations.
  1201. // As long as jumps are not expensive, this should improve performance.
  1202. // For example, instead of something like:
  1203. // cmp A, B
  1204. // C = seteq
  1205. // cmp D, E
  1206. // F = setle
  1207. // or C, F
  1208. // jnz foo
  1209. // Emit:
  1210. // cmp A, B
  1211. // je foo
  1212. // cmp D, E
  1213. // jle foo
  1214. //
  1215. if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
  1216. if (!TLI.isJumpExpensive() &&
  1217. BOp->hasOneUse() &&
  1218. (BOp->getOpcode() == Instruction::And ||
  1219. BOp->getOpcode() == Instruction::Or)) {
  1220. FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
  1221. BOp->getOpcode());
  1222. // If the compares in later blocks need to use values not currently
  1223. // exported from this block, export them now. This block should always
  1224. // be the first entry.
  1225. assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
  1226. // Allow some cases to be rejected.
  1227. if (ShouldEmitAsBranches(SwitchCases)) {
  1228. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
  1229. ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
  1230. ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
  1231. }
  1232. // Emit the branch for this block.
  1233. visitSwitchCase(SwitchCases[0], BrMBB);
  1234. SwitchCases.erase(SwitchCases.begin());
  1235. return;
  1236. }
  1237. // Okay, we decided not to do this, remove any inserted MBB's and clear
  1238. // SwitchCases.
  1239. for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
  1240. FuncInfo.MF->erase(SwitchCases[i].ThisBB);
  1241. SwitchCases.clear();
  1242. }
  1243. }
  1244. // Create a CaseBlock record representing this branch.
  1245. CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
  1246. NULL, Succ0MBB, Succ1MBB, BrMBB);
  1247. // Use visitSwitchCase to actually insert the fast branch sequence for this
  1248. // cond branch.
  1249. visitSwitchCase(CB, BrMBB);
  1250. }
  1251. /// visitSwitchCase - Emits the necessary code to represent a single node in
  1252. /// the binary search tree resulting from lowering a switch instruction.
  1253. void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
  1254. MachineBasicBlock *SwitchBB) {
  1255. SDValue Cond;
  1256. SDValue CondLHS = getValue(CB.CmpLHS);
  1257. DebugLoc dl = getCurDebugLoc();
  1258. // Build the setcc now.
  1259. if (CB.CmpMHS == NULL) {
  1260. // Fold "(X == true)" to X and "(X == false)" to !X to
  1261. // handle common cases produced by branch lowering.
  1262. if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
  1263. CB.CC == ISD::SETEQ)
  1264. Cond = CondLHS;
  1265. else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
  1266. CB.CC == ISD::SETEQ) {
  1267. SDValue True = DAG.getConstant(1, CondLHS.getValueType());
  1268. Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
  1269. } else
  1270. Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
  1271. } else {
  1272. assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
  1273. const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
  1274. const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
  1275. SDValue CmpOp = getValue(CB.CmpMHS);
  1276. EVT VT = CmpOp.getValueType();
  1277. if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
  1278. Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
  1279. ISD::SETLE);
  1280. } else {
  1281. SDValue SUB = DAG.getNode(ISD::SUB, dl,
  1282. VT, CmpOp, DAG.getConstant(Low, VT));
  1283. Cond = DAG.getSetCC(dl, MVT::i1, SUB,
  1284. DAG.getConstant(High-Low, VT), ISD::SETULE);
  1285. }
  1286. }
  1287. // Update successor info
  1288. SwitchBB->addSuccessor(CB.TrueBB);
  1289. SwitchBB->addSuccessor(CB.FalseBB);
  1290. // Set NextBlock to be the MBB immediately after the current one, if any.
  1291. // This is used to avoid emitting unnecessary branches to the next block.
  1292. MachineBasicBlock *NextBlock = 0;
  1293. MachineFunction::iterator BBI = SwitchBB;
  1294. if (++BBI != FuncInfo.MF->end())
  1295. NextBlock = BBI;
  1296. // If the lhs block is the next block, invert the condition so that we can
  1297. // fall through to the lhs instead of the rhs block.
  1298. if (CB.TrueBB == NextBlock) {
  1299. std::swap(CB.TrueBB, CB.FalseBB);
  1300. SDValue True = DAG.getConstant(1, Cond.getValueType());
  1301. Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
  1302. }
  1303. SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
  1304. MVT::Other, getControlRoot(), Cond,
  1305. DAG.getBasicBlock(CB.TrueBB));
  1306. // Insert the false branch. Do this even if it's a fall through branch,
  1307. // this makes it easier to do DAG optimizations which require inverting
  1308. // the branch condition.
  1309. BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
  1310. DAG.getBasicBlock(CB.FalseBB));
  1311. DAG.setRoot(BrCond);
  1312. }
  1313. /// visitJumpTable - Emit JumpTable node in the current MBB
  1314. void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
  1315. // Emit the code for the jump table
  1316. assert(JT.Reg != -1U && "Should lower JT Header first!");
  1317. EVT PTy = TLI.getPointerTy();
  1318. SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
  1319. JT.Reg, PTy);
  1320. SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
  1321. SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
  1322. MVT::Other, Index.getValue(1),
  1323. Table, Index);
  1324. DAG.setRoot(BrJumpTable);
  1325. }
  1326. /// visitJumpTableHeader - This function emits necessary code to produce index
  1327. /// in the JumpTable from switch case.
  1328. void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
  1329. JumpTableHeader &JTH,
  1330. MachineBasicBlock *SwitchBB) {
  1331. // Subtract the lowest switch case value from the value being switched on and
  1332. // conditional branch to default mbb if the result is greater than the
  1333. // difference between smallest and largest cases.
  1334. SDValue SwitchOp = getValue(JTH.SValue);
  1335. EVT VT = SwitchOp.getValueType();
  1336. SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
  1337. DAG.getConstant(JTH.First, VT));
  1338. // The SDNode we just created, which holds the value being switched on minus
  1339. // the smallest case value, needs to be copied to a virtual register so it
  1340. // can be used as an index into the jump table in a subsequent basic block.
  1341. // This value may be smaller or larger than the target's pointer type, and
  1342. // therefore require extension or truncating.
  1343. SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
  1344. unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
  1345. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
  1346. JumpTableReg, SwitchOp);
  1347. JT.Reg = JumpTableReg;
  1348. // Emit the range check for the jump table, and branch to the default block
  1349. // for the switch statement if the value being switched on exceeds the largest
  1350. // case in the switch.
  1351. SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
  1352. TLI.getSetCCResultType(Sub.getValueType()), Sub,
  1353. DAG.getConstant(JTH.Last-JTH.First,VT),
  1354. ISD::SETUGT);
  1355. // Set NextBlock to be the MBB immediately after the current one, if any.
  1356. // This is used to avoid emitting unnecessary branches to the next block.
  1357. MachineBasicBlock *NextBlock = 0;
  1358. MachineFunction::iterator BBI = SwitchBB;
  1359. if (++BBI != FuncInfo.MF->end())
  1360. NextBlock = BBI;
  1361. SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1362. MVT::Other, CopyTo, CMP,
  1363. DAG.getBasicBlock(JT.Default));
  1364. if (JT.MBB != NextBlock)
  1365. BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
  1366. DAG.getBasicBlock(JT.MBB));
  1367. DAG.setRoot(BrCond);
  1368. }
  1369. /// visitBitTestHeader - This function emits necessary code to produce value
  1370. /// suitable for "bit tests"
  1371. void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
  1372. MachineBasicBlock *SwitchBB) {
  1373. // Subtract the minimum value
  1374. SDValue SwitchOp = getValue(B.SValue);
  1375. EVT VT = SwitchOp.getValueType();
  1376. SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
  1377. DAG.getConstant(B.First, VT));
  1378. // Check range
  1379. SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
  1380. TLI.getSetCCResultType(Sub.getValueType()),
  1381. Sub, DAG.getConstant(B.Range, VT),
  1382. ISD::SETUGT);
  1383. // Determine the type of the test operands.
  1384. bool UsePtrType = false;
  1385. if (!TLI.isTypeLegal(VT))
  1386. UsePtrType = true;
  1387. else {
  1388. for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
  1389. if ((uint64_t)((int64_t)B.Cases[i].Mask >> VT.getSizeInBits()) + 1 >= 2) {
  1390. // Switch table case range are encoded into series of masks.
  1391. // Just use pointer type, it's guaranteed to fit.
  1392. UsePtrType = true;
  1393. break;
  1394. }
  1395. }
  1396. if (UsePtrType) {
  1397. VT = TLI.getPointerTy();
  1398. Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
  1399. }
  1400. B.RegVT = VT;
  1401. B.Reg = FuncInfo.CreateReg(VT);
  1402. SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
  1403. B.Reg, Sub);
  1404. // Set NextBlock to be the MBB immediately after the current one, if any.
  1405. // This is used to avoid emitting unnecessary branches to the next block.
  1406. MachineBasicBlock *NextBlock = 0;
  1407. MachineFunction::iterator BBI = SwitchBB;
  1408. if (++BBI != FuncInfo.MF->end())
  1409. NextBlock = BBI;
  1410. MachineBasicBlock* MBB = B.Cases[0].ThisBB;
  1411. SwitchBB->addSuccessor(B.Default);
  1412. SwitchBB->addSuccessor(MBB);
  1413. SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1414. MVT::Other, CopyTo, RangeCmp,
  1415. DAG.getBasicBlock(B.Default));
  1416. if (MBB != NextBlock)
  1417. BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
  1418. DAG.getBasicBlock(MBB));
  1419. DAG.setRoot(BrRange);
  1420. }
  1421. /// visitBitTestCase - this function produces one "bit test"
  1422. void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
  1423. MachineBasicBlock* NextMBB,
  1424. unsigned Reg,
  1425. BitTestCase &B,
  1426. MachineBasicBlock *SwitchBB) {
  1427. EVT VT = BB.RegVT;
  1428. SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
  1429. Reg, VT);
  1430. SDValue Cmp;
  1431. if (CountPopulation_64(B.Mask) == 1) {
  1432. // Testing for a single bit; just compare the shift count with what it
  1433. // would need to be to shift a 1 bit in that position.
  1434. Cmp = DAG.getSetCC(getCurDebugLoc(),
  1435. TLI.getSetCCResultType(VT),
  1436. ShiftOp,
  1437. DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
  1438. ISD::SETEQ);
  1439. } else {
  1440. // Make desired shift
  1441. SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
  1442. DAG.getConstant(1, VT), ShiftOp);
  1443. // Emit bit tests and jumps
  1444. SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
  1445. VT, SwitchVal, DAG.getConstant(B.Mask, VT));
  1446. Cmp = DAG.getSetCC(getCurDebugLoc(),
  1447. TLI.getSetCCResultType(VT),
  1448. AndOp, DAG.getConstant(0, VT),
  1449. ISD::SETNE);
  1450. }
  1451. SwitchBB->addSuccessor(B.TargetBB);
  1452. SwitchBB->addSuccessor(NextMBB);
  1453. SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
  1454. MVT::Other, getControlRoot(),
  1455. Cmp, DAG.getBasicBlock(B.TargetBB));
  1456. // Set NextBlock to be the MBB immediately after the current one, if any.
  1457. // This is used to avoid emitting unnecessary branches to the next block.
  1458. MachineBasicBlock *NextBlock = 0;
  1459. MachineFunction::iterator BBI = SwitchBB;
  1460. if (++BBI != FuncInfo.MF->end())
  1461. NextBlock = BBI;
  1462. if (NextMBB != NextBlock)
  1463. BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
  1464. DAG.getBasicBlock(NextMBB));
  1465. DAG.setRoot(BrAnd);
  1466. }
  1467. void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
  1468. MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
  1469. // Retrieve successors.
  1470. MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
  1471. MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
  1472. const Value *Callee(I.getCalledValue());
  1473. if (isa<InlineAsm>(Callee))
  1474. visitInlineAsm(&I);
  1475. else
  1476. LowerCallTo(&I, getValue(Callee), false, LandingPad);
  1477. // If the value of the invoke is used outside of its defining block, make it
  1478. // available as a virtual register.
  1479. CopyToExportRegsIfNeeded(&I);
  1480. // Update successor info
  1481. InvokeMBB->addSuccessor(Return);
  1482. InvokeMBB->addSuccessor(LandingPad);
  1483. // Drop into normal successor.
  1484. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1485. MVT::Other, getControlRoot(),
  1486. DAG.getBasicBlock(Return)));
  1487. }
  1488. void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
  1489. }
  1490. /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
  1491. /// small case ranges).
  1492. bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
  1493. CaseRecVector& WorkList,
  1494. const Value* SV,
  1495. MachineBasicBlock *Default,
  1496. MachineBasicBlock *SwitchBB) {
  1497. Case& BackCase = *(CR.Range.second-1);
  1498. // Size is the number of Cases represented by this range.
  1499. size_t Size = CR.Range.second - CR.Range.first;
  1500. if (Size > 3)
  1501. return false;
  1502. // Get the MachineFunction which holds the current MBB. This is used when
  1503. // inserting any additional MBBs necessary to represent the switch.
  1504. MachineFunction *CurMF = FuncInfo.MF;
  1505. // Figure out which block is immediately after the current one.
  1506. MachineBasicBlock *NextBlock = 0;
  1507. MachineFunction::iterator BBI = CR.CaseBB;
  1508. if (++BBI != FuncInfo.MF->end())
  1509. NextBlock = BBI;
  1510. // If any two of the cases has the same destination, and if one value
  1511. // is the same as the other, but has one bit unset that the other has set,
  1512. // use bit manipulation to do two compares at once. For example:
  1513. // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
  1514. // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
  1515. // TODO: Handle cases where CR.CaseBB != SwitchBB.
  1516. if (Size == 2 && CR.CaseBB == SwitchBB) {
  1517. Case &Small = *CR.Range.first;
  1518. Case &Big = *(CR.Range.second-1);
  1519. if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
  1520. const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
  1521. const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
  1522. // Check that there is only one bit different.
  1523. if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
  1524. (SmallValue | BigValue) == BigValue) {
  1525. // Isolate the common bit.
  1526. APInt CommonBit = BigValue & ~SmallValue;
  1527. assert((SmallValue | CommonBit) == BigValue &&
  1528. CommonBit.countPopulation() == 1 && "Not a common bit?");
  1529. SDValue CondLHS = getValue(SV);
  1530. EVT VT = CondLHS.getValueType();
  1531. DebugLoc DL = getCurDebugLoc();
  1532. SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
  1533. DAG.getConstant(CommonBit, VT));
  1534. SDValue Cond = DAG.getSetCC(DL, MVT::i1,
  1535. Or, DAG.getConstant(BigValue, VT),
  1536. ISD::SETEQ);
  1537. // Update successor info.
  1538. SwitchBB->addSuccessor(Small.BB);
  1539. SwitchBB->addSuccessor(Default);
  1540. // Insert the true branch.
  1541. SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
  1542. getControlRoot(), Cond,
  1543. DAG.getBasicBlock(Small.BB));
  1544. // Insert the false branch.
  1545. BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
  1546. DAG.getBasicBlock(Default));
  1547. DAG.setRoot(BrCond);
  1548. return true;
  1549. }
  1550. }
  1551. }
  1552. // Rearrange the case blocks so that the last one falls through if possible.
  1553. if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
  1554. // The last case block won't fall through into 'NextBlock' if we emit the
  1555. // branches in this order. See if rearranging a case value would help.
  1556. for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
  1557. if (I->BB == NextBlock) {
  1558. std::swap(*I, BackCase);
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. // Create a CaseBlock record representing a conditional branch to
  1564. // the Case's target mbb if the value being switched on SV is equal
  1565. // to C.
  1566. MachineBasicBlock *CurBlock = CR.CaseBB;
  1567. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
  1568. MachineBasicBlock *FallThrough;
  1569. if (I != E-1) {
  1570. FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
  1571. CurMF->insert(BBI, FallThrough);
  1572. // Put SV in a virtual register to make it available from the new blocks.
  1573. ExportFromCurrentBlock(SV);
  1574. } else {
  1575. // If the last case doesn't match, go to the default block.
  1576. FallThrough = Default;
  1577. }
  1578. const Value *RHS, *LHS, *MHS;
  1579. ISD::CondCode CC;
  1580. if (I->High == I->Low) {
  1581. // This is just small small case range :) containing exactly 1 case
  1582. CC = ISD::SETEQ;
  1583. LHS = SV; RHS = I->High; MHS = NULL;
  1584. } else {
  1585. CC = ISD::SETLE;
  1586. LHS = I->Low; MHS = SV; RHS = I->High;
  1587. }
  1588. CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
  1589. // If emitting the first comparison, just call visitSwitchCase to emit the
  1590. // code into the current block. Otherwise, push the CaseBlock onto the
  1591. // vector to be later processed by SDISel, and insert the node's MBB
  1592. // before the next MBB.
  1593. if (CurBlock == SwitchBB)
  1594. visitSwitchCase(CB, SwitchBB);
  1595. else
  1596. SwitchCases.push_back(CB);
  1597. CurBlock = FallThrough;
  1598. }
  1599. return true;
  1600. }
  1601. static inline bool areJTsAllowed(const TargetLowering &TLI) {
  1602. return !DisableJumpTables &&
  1603. (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
  1604. TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
  1605. }
  1606. static APInt ComputeRange(const APInt &First, const APInt &Last) {
  1607. uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
  1608. APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
  1609. return (LastExt - FirstExt + 1ULL);
  1610. }
  1611. /// handleJTSwitchCase - Emit jumptable for current switch case range
  1612. bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
  1613. CaseRecVector& WorkList,
  1614. const Value* SV,
  1615. MachineBasicBlock* Default,
  1616. MachineBasicBlock *SwitchBB) {
  1617. Case& FrontCase = *CR.Range.first;
  1618. Case& BackCase = *(CR.Range.second-1);
  1619. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1620. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  1621. APInt TSize(First.getBitWidth(), 0);
  1622. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1623. I!=E; ++I)
  1624. TSize += I->size();
  1625. if (!areJTsAllowed(TLI) || TSize.ult(4))
  1626. return false;
  1627. APInt Range = ComputeRange(First, Last);
  1628. double Density = TSize.roundToDouble() / Range.roundToDouble();
  1629. if (Density < 0.4)
  1630. return false;
  1631. DEBUG(dbgs() << "Lowering jump table\n"
  1632. << "First entry: " << First << ". Last entry: " << Last << '\n'
  1633. << "Range: " << Range
  1634. << ". Size: " << TSize << ". Density: " << Density << "\n\n");
  1635. // Get the MachineFunction which holds the current MBB. This is used when
  1636. // inserting any additional MBBs necessary to represent the switch.
  1637. MachineFunction *CurMF = FuncInfo.MF;
  1638. // Figure out which block is immediately after the current one.
  1639. MachineFunction::iterator BBI = CR.CaseBB;
  1640. ++BBI;
  1641. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1642. // Create a new basic block to hold the code for loading the address
  1643. // of the jump table, and jumping to it. Update successor information;
  1644. // we will either branch to the default case for the switch, or the jump
  1645. // table.
  1646. MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1647. CurMF->insert(BBI, JumpTableBB);
  1648. CR.CaseBB->addSuccessor(Default);
  1649. CR.CaseBB->addSuccessor(JumpTableBB);
  1650. // Build a vector of destination BBs, corresponding to each target
  1651. // of the jump table. If the value of the jump table slot corresponds to
  1652. // a case statement, push the case's BB onto the vector, otherwise, push
  1653. // the default BB.
  1654. std::vector<MachineBasicBlock*> DestBBs;
  1655. APInt TEI = First;
  1656. for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
  1657. const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
  1658. const APInt &High = cast<ConstantInt>(I->High)->getValue();
  1659. if (Low.sle(TEI) && TEI.sle(High)) {
  1660. DestBBs.push_back(I->BB);
  1661. if (TEI==High)
  1662. ++I;
  1663. } else {
  1664. DestBBs.push_back(Default);
  1665. }
  1666. }
  1667. // Update successor info. Add one edge to each unique successor.
  1668. BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
  1669. for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
  1670. E = DestBBs.end(); I != E; ++I) {
  1671. if (!SuccsHandled[(*I)->getNumber()]) {
  1672. SuccsHandled[(*I)->getNumber()] = true;
  1673. JumpTableBB->addSuccessor(*I);
  1674. }
  1675. }
  1676. // Create a jump table index for this jump table.
  1677. unsigned JTEncoding = TLI.getJumpTableEncoding();
  1678. unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
  1679. ->createJumpTableIndex(DestBBs);
  1680. // Set the jump table information so that we can codegen it as a second
  1681. // MachineBasicBlock
  1682. JumpTable JT(-1U, JTI, JumpTableBB, Default);
  1683. JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
  1684. if (CR.CaseBB == SwitchBB)
  1685. visitJumpTableHeader(JT, JTH, SwitchBB);
  1686. JTCases.push_back(JumpTableBlock(JTH, JT));
  1687. return true;
  1688. }
  1689. /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
  1690. /// 2 subtrees.
  1691. bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
  1692. CaseRecVector& WorkList,
  1693. const Value* SV,
  1694. MachineBasicBlock *Default,
  1695. MachineBasicBlock *SwitchBB) {
  1696. // Get the MachineFunction which holds the current MBB. This is used when
  1697. // inserting any additional MBBs necessary to represent the switch.
  1698. MachineFunction *CurMF = FuncInfo.MF;
  1699. // Figure out which block is immediately after the current one.
  1700. MachineFunction::iterator BBI = CR.CaseBB;
  1701. ++BBI;
  1702. Case& FrontCase = *CR.Range.first;
  1703. Case& BackCase = *(CR.Range.second-1);
  1704. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1705. // Size is the number of Cases represented by this range.
  1706. unsigned Size = CR.Range.second - CR.Range.first;
  1707. const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
  1708. const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
  1709. double FMetric = 0;
  1710. CaseItr Pivot = CR.Range.first + Size/2;
  1711. // Select optimal pivot, maximizing sum density of LHS and RHS. This will
  1712. // (heuristically) allow us to emit JumpTable's later.
  1713. APInt TSize(First.getBitWidth(), 0);
  1714. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1715. I!=E; ++I)
  1716. TSize += I->size();
  1717. APInt LSize = FrontCase.size();
  1718. APInt RSize = TSize-LSize;
  1719. DEBUG(dbgs() << "Selecting best pivot: \n"
  1720. << "First: " << First << ", Last: " << Last <<'\n'
  1721. << "LSize: " << LSize << ", RSize: " << RSize << '\n');
  1722. for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
  1723. J!=E; ++I, ++J) {
  1724. const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
  1725. const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
  1726. APInt Range = ComputeRange(LEnd, RBegin);
  1727. assert((Range - 2ULL).isNonNegative() &&
  1728. "Invalid case distance");
  1729. // Use volatile double here to avoid excess precision issues on some hosts,
  1730. // e.g. that use 80-bit X87 registers.
  1731. volatile double LDensity =
  1732. (double)LSize.roundToDouble() /
  1733. (LEnd - First + 1ULL).roundToDouble();
  1734. volatile double RDensity =
  1735. (double)RSize.roundToDouble() /
  1736. (Last - RBegin + 1ULL).roundToDouble();
  1737. double Metric = Range.logBase2()*(LDensity+RDensity);
  1738. // Should always split in some non-trivial place
  1739. DEBUG(dbgs() <<"=>Step\n"
  1740. << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
  1741. << "LDensity: " << LDensity
  1742. << ", RDensity: " << RDensity << '\n'
  1743. << "Metric: " << Metric << '\n');
  1744. if (FMetric < Metric) {
  1745. Pivot = J;
  1746. FMetric = Metric;
  1747. DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
  1748. }
  1749. LSize += J->size();
  1750. RSize -= J->size();
  1751. }
  1752. if (areJTsAllowed(TLI)) {
  1753. // If our case is dense we *really* should handle it earlier!
  1754. assert((FMetric > 0) && "Should handle dense range earlier!");
  1755. } else {
  1756. Pivot = CR.Range.first + Size/2;
  1757. }
  1758. CaseRange LHSR(CR.Range.first, Pivot);
  1759. CaseRange RHSR(Pivot, CR.Range.second);
  1760. Constant *C = Pivot->Low;
  1761. MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
  1762. // We know that we branch to the LHS if the Value being switched on is
  1763. // less than the Pivot value, C. We use this to optimize our binary
  1764. // tree a bit, by recognizing that if SV is greater than or equal to the
  1765. // LHS's Case Value, and that Case Value is exactly one less than the
  1766. // Pivot's Value, then we can branch directly to the LHS's Target,
  1767. // rather than creating a leaf node for it.
  1768. if ((LHSR.second - LHSR.first) == 1 &&
  1769. LHSR.first->High == CR.GE &&
  1770. cast<ConstantInt>(C)->getValue() ==
  1771. (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
  1772. TrueBB = LHSR.first->BB;
  1773. } else {
  1774. TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1775. CurMF->insert(BBI, TrueBB);
  1776. WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
  1777. // Put SV in a virtual register to make it available from the new blocks.
  1778. ExportFromCurrentBlock(SV);
  1779. }
  1780. // Similar to the optimization above, if the Value being switched on is
  1781. // known to be less than the Constant CR.LT, and the current Case Value
  1782. // is CR.LT - 1, then we can branch directly to the target block for
  1783. // the current Case Value, rather than emitting a RHS leaf node for it.
  1784. if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
  1785. cast<ConstantInt>(RHSR.first->Low)->getValue() ==
  1786. (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
  1787. FalseBB = RHSR.first->BB;
  1788. } else {
  1789. FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1790. CurMF->insert(BBI, FalseBB);
  1791. WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
  1792. // Put SV in a virtual register to make it available from the new blocks.
  1793. ExportFromCurrentBlock(SV);
  1794. }
  1795. // Create a CaseBlock record representing a conditional branch to
  1796. // the LHS node if the value being switched on SV is less than C.
  1797. // Otherwise, branch to LHS.
  1798. CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
  1799. if (CR.CaseBB == SwitchBB)
  1800. visitSwitchCase(CB, SwitchBB);
  1801. else
  1802. SwitchCases.push_back(CB);
  1803. return true;
  1804. }
  1805. /// handleBitTestsSwitchCase - if current case range has few destination and
  1806. /// range span less, than machine word bitwidth, encode case range into series
  1807. /// of masks and emit bit tests with these masks.
  1808. bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
  1809. CaseRecVector& WorkList,
  1810. const Value* SV,
  1811. MachineBasicBlock* Default,
  1812. MachineBasicBlock *SwitchBB){
  1813. EVT PTy = TLI.getPointerTy();
  1814. unsigned IntPtrBits = PTy.getSizeInBits();
  1815. Case& FrontCase = *CR.Range.first;
  1816. Case& BackCase = *(CR.Range.second-1);
  1817. // Get the MachineFunction which holds the current MBB. This is used when
  1818. // inserting any additional MBBs necessary to represent the switch.
  1819. MachineFunction *CurMF = FuncInfo.MF;
  1820. // If target does not have legal shift left, do not emit bit tests at all.
  1821. if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
  1822. return false;
  1823. size_t numCmps = 0;
  1824. for (CaseItr I = CR.Range.first, E = CR.Range.second;
  1825. I!=E; ++I) {
  1826. // Single case counts one, case range - two.
  1827. numCmps += (I->Low == I->High ? 1 : 2);
  1828. }
  1829. // Count unique destinations
  1830. SmallSet<MachineBasicBlock*, 4> Dests;
  1831. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  1832. Dests.insert(I->BB);
  1833. if (Dests.size() > 3)
  1834. // Don't bother the code below, if there are too much unique destinations
  1835. return false;
  1836. }
  1837. DEBUG(dbgs() << "Total number of unique destinations: "
  1838. << Dests.size() << '\n'
  1839. << "Total number of comparisons: " << numCmps << '\n');
  1840. // Compute span of values.
  1841. const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
  1842. const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
  1843. APInt cmpRange = maxValue - minValue;
  1844. DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
  1845. << "Low bound: " << minValue << '\n'
  1846. << "High bound: " << maxValue << '\n');
  1847. if (cmpRange.uge(IntPtrBits) ||
  1848. (!(Dests.size() == 1 && numCmps >= 3) &&
  1849. !(Dests.size() == 2 && numCmps >= 5) &&
  1850. !(Dests.size() >= 3 && numCmps >= 6)))
  1851. return false;
  1852. DEBUG(dbgs() << "Emitting bit tests\n");
  1853. APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
  1854. // Optimize the case where all the case values fit in a
  1855. // word without having to subtract minValue. In this case,
  1856. // we can optimize away the subtraction.
  1857. if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
  1858. cmpRange = maxValue;
  1859. } else {
  1860. lowBound = minValue;
  1861. }
  1862. CaseBitsVector CasesBits;
  1863. unsigned i, count = 0;
  1864. for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
  1865. MachineBasicBlock* Dest = I->BB;
  1866. for (i = 0; i < count; ++i)
  1867. if (Dest == CasesBits[i].BB)
  1868. break;
  1869. if (i == count) {
  1870. assert((count < 3) && "Too much destinations to test!");
  1871. CasesBits.push_back(CaseBits(0, Dest, 0));
  1872. count++;
  1873. }
  1874. const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
  1875. const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
  1876. uint64_t lo = (lowValue - lowBound).getZExtValue();
  1877. uint64_t hi = (highValue - lowBound).getZExtValue();
  1878. for (uint64_t j = lo; j <= hi; j++) {
  1879. CasesBits[i].Mask |= 1ULL << j;
  1880. CasesBits[i].Bits++;
  1881. }
  1882. }
  1883. std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
  1884. BitTestInfo BTC;
  1885. // Figure out which block is immediately after the current one.
  1886. MachineFunction::iterator BBI = CR.CaseBB;
  1887. ++BBI;
  1888. const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
  1889. DEBUG(dbgs() << "Cases:\n");
  1890. for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
  1891. DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
  1892. << ", Bits: " << CasesBits[i].Bits
  1893. << ", BB: " << CasesBits[i].BB << '\n');
  1894. MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
  1895. CurMF->insert(BBI, CaseBB);
  1896. BTC.push_back(BitTestCase(CasesBits[i].Mask,
  1897. CaseBB,
  1898. CasesBits[i].BB));
  1899. // Put SV in a virtual register to make it available from the new blocks.
  1900. ExportFromCurrentBlock(SV);
  1901. }
  1902. BitTestBlock BTB(lowBound, cmpRange, SV,
  1903. -1U, MVT::Other, (CR.CaseBB == SwitchBB),
  1904. CR.CaseBB, Default, BTC);
  1905. if (CR.CaseBB == SwitchBB)
  1906. visitBitTestHeader(BTB, SwitchBB);
  1907. BitTestCases.push_back(BTB);
  1908. return true;
  1909. }
  1910. /// Clusterify - Transform simple list of Cases into list of CaseRange's
  1911. size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
  1912. const SwitchInst& SI) {
  1913. size_t numCmps = 0;
  1914. // Start with "simple" cases
  1915. for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
  1916. MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
  1917. Cases.push_back(Case(SI.getSuccessorValue(i),
  1918. SI.getSuccessorValue(i),
  1919. SMBB));
  1920. }
  1921. std::sort(Cases.begin(), Cases.end(), CaseCmp());
  1922. // Merge case into clusters
  1923. if (Cases.size() >= 2)
  1924. // Must recompute end() each iteration because it may be
  1925. // invalidated by erase if we hold on to it
  1926. for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
  1927. J != Cases.end(); ) {
  1928. const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
  1929. const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
  1930. MachineBasicBlock* nextBB = J->BB;
  1931. MachineBasicBlock* currentBB = I->BB;
  1932. // If the two neighboring cases go to the same destination, merge them
  1933. // into a single case.
  1934. if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
  1935. I->High = J->High;
  1936. J = Cases.erase(J);
  1937. } else {
  1938. I = J++;
  1939. }
  1940. }
  1941. for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
  1942. if (I->Low != I->High)
  1943. // A range counts double, since it requires two compares.
  1944. ++numCmps;
  1945. }
  1946. return numCmps;
  1947. }
  1948. void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
  1949. MachineBasicBlock *Last) {
  1950. // Update JTCases.
  1951. for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
  1952. if (JTCases[i].first.HeaderBB == First)
  1953. JTCases[i].first.HeaderBB = Last;
  1954. // Update BitTestCases.
  1955. for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
  1956. if (BitTestCases[i].Parent == First)
  1957. BitTestCases[i].Parent = Last;
  1958. }
  1959. void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
  1960. MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
  1961. // Figure out which block is immediately after the current one.
  1962. MachineBasicBlock *NextBlock = 0;
  1963. MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
  1964. // If there is only the default destination, branch to it if it is not the
  1965. // next basic block. Otherwise, just fall through.
  1966. if (SI.getNumOperands() == 2) {
  1967. // Update machine-CFG edges.
  1968. // If this is not a fall-through branch, emit the branch.
  1969. SwitchMBB->addSuccessor(Default);
  1970. if (Default != NextBlock)
  1971. DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
  1972. MVT::Other, getControlRoot(),
  1973. DAG.getBasicBlock(Default)));
  1974. return;
  1975. }
  1976. // If there are any non-default case statements, create a vector of Cases
  1977. // representing each one, and sort the vector so that we can efficiently
  1978. // create a binary search tree from them.
  1979. CaseVector Cases;
  1980. size_t numCmps = Clusterify(Cases, SI);
  1981. DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
  1982. << ". Total compares: " << numCmps << '\n');
  1983. numCmps = 0;
  1984. // Get the Value to be switched on and default basic blocks, which will be
  1985. // inserted into CaseBlock records, representing basic blocks in the binary
  1986. // search tree.
  1987. const Value *SV = SI.getOperand(0);
  1988. // Push the initial CaseRec onto the worklist
  1989. CaseRecVector WorkList;
  1990. WorkList.push_back(CaseRec(SwitchMBB,0,0,
  1991. CaseRange(Cases.begin(),Cases.end())));
  1992. while (!WorkList.empty()) {
  1993. // Grab a record representing a case range to process off the worklist
  1994. CaseRec CR = WorkList.back();
  1995. WorkList.pop_back();
  1996. if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
  1997. continue;
  1998. // If the range has few cases (two or less) emit a series of specific
  1999. // tests.
  2000. if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
  2001. continue;
  2002. // If the switch has more than 5 blocks, and at least 40% dense, and the
  2003. // target supports indirect branches, then emit a jump table rather than
  2004. // lowering the switch to a binary tree of conditional branches.
  2005. if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
  2006. continue;
  2007. // Emit binary tree. We need to pick a pivot, and push left and right ranges
  2008. // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
  2009. handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
  2010. }
  2011. }
  2012. void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
  2013. MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
  2014. // Update machine-CFG edges with unique successors.
  2015. SmallVector<BasicBlock*, 32> succs;
  2016. succs.reserve(I.getNumSuccessors());
  2017. for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
  2018. succs.push_back(I.getSuccessor(i));
  2019. array_pod_sort(succs.begin(), succs.end());
  2020. succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
  2021. for (unsigned i = 0, e = succs.size(); i != e; ++i)
  2022. IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
  2023. DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
  2024. MVT::Other, getControlRoot(),
  2025. getValue(I.getAddress())));
  2026. }
  2027. void SelectionDAGBuilder::visitFSub(const User &I) {
  2028. // -0.0 - X --> fneg
  2029. const Type *Ty = I.getType();
  2030. if (isa<Constant>(I.getOperand(0)) &&
  2031. I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
  2032. SDValue Op2 = getValue(I.getOperand(1));
  2033. setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
  2034. Op2.getValueType(), Op2));
  2035. return;
  2036. }
  2037. visitBinary(I, ISD::FSUB);
  2038. }
  2039. void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
  2040. SDValue Op1 = getValue(I.getOperand(0));
  2041. SDValue Op2 = getValue(I.getOperand(1));
  2042. setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
  2043. Op1.getValueType(), Op1, Op2));
  2044. }
  2045. void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
  2046. SDValue Op1 = getValue(I.getOperand(0));
  2047. SDValue Op2 = getValue(I.getOperand(1));
  2048. MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
  2049. // Coerce the shift amount to the right type if we can.
  2050. if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
  2051. unsigned ShiftSize = ShiftTy.getSizeInBits();
  2052. unsigned Op2Size = Op2.getValueType().getSizeInBits();
  2053. DebugLoc DL = getCurDebugLoc();
  2054. // If the operand is smaller than the shift count type, promote it.
  2055. if (ShiftSize > Op2Size)
  2056. Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
  2057. // If the operand is larger than the shift count type but the shift
  2058. // count type has enough bits to represent any shift value, truncate
  2059. // it now. This is a common case and it exposes the truncate to
  2060. // optimization early.
  2061. else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
  2062. Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
  2063. // Otherwise we'll need to temporarily settle for some other convenient
  2064. // type. Type legalization will make adjustments once the shiftee is split.
  2065. else
  2066. Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
  2067. }
  2068. setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
  2069. Op1.getValueType(), Op1, Op2));
  2070. }
  2071. void SelectionDAGBuilder::visitICmp(const User &I) {
  2072. ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
  2073. if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
  2074. predicate = IC->getPredicate();
  2075. else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
  2076. predicate = ICmpInst::Predicate(IC->getPredicate());
  2077. SDValue Op1 = getValue(I.getOperand(0));
  2078. SDValue Op2 = getValue(I.getOperand(1));
  2079. ISD::CondCode Opcode = getICmpCondCode(predicate);
  2080. EVT DestVT = TLI.getValueType(I.getType());
  2081. setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
  2082. }
  2083. void SelectionDAGBuilder::visitFCmp(const User &I) {
  2084. FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
  2085. if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
  2086. predicate = FC->getPredicate();
  2087. else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
  2088. predicate = FCmpInst::Predicate(FC->getPredicate());
  2089. SDValue Op1 = getValue(I.getOperand(0));
  2090. SDValue Op2 = getValue(I.getOperand(1));
  2091. ISD::CondCode Condition = getFCmpCondCode(predicate);
  2092. EVT DestVT = TLI.getValueType(I.getType());
  2093. setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
  2094. }
  2095. void SelectionDAGBuilder::visitSelect(const User &I) {
  2096. SmallVector<EVT, 4> ValueVTs;
  2097. ComputeValueVTs(TLI, I.getType(), ValueVTs);
  2098. unsigned NumValues = ValueVTs.size();
  2099. if (NumValues == 0) return;
  2100. SmallVector<SDValue, 4> Values(NumValues);
  2101. SDValue Cond = getValue(I.getOperand(0));
  2102. SDValue TrueVal = getValue(I.getOperand(1));
  2103. SDValue FalseVal = getValue(I.getOperand(2));
  2104. for (unsigned i = 0; i != NumValues; ++i)
  2105. Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
  2106. TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
  2107. Cond,
  2108. SDValue(TrueVal.getNode(),
  2109. TrueVal.getResNo() + i),
  2110. SDValue(FalseVal.getNode(),
  2111. FalseVal.getResNo() + i));
  2112. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2113. DAG.getVTList(&ValueVTs[0], NumValues),
  2114. &Values[0], NumValues));
  2115. }
  2116. void SelectionDAGBuilder::visitTrunc(const User &I) {
  2117. // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
  2118. SDValue N = getValue(I.getOperand(0));
  2119. EVT DestVT = TLI.getValueType(I.getType());
  2120. setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
  2121. }
  2122. void SelectionDAGBuilder::visitZExt(const User &I) {
  2123. // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2124. // ZExt also can't be a cast to bool for same reason. So, nothing much to do
  2125. SDValue N = getValue(I.getOperand(0));
  2126. EVT DestVT = TLI.getValueType(I.getType());
  2127. setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
  2128. }
  2129. void SelectionDAGBuilder::visitSExt(const User &I) {
  2130. // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
  2131. // SExt also can't be a cast to bool for same reason. So, nothing much to do
  2132. SDValue N = getValue(I.getOperand(0));
  2133. EVT DestVT = TLI.getValueType(I.getType());
  2134. setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
  2135. }
  2136. void SelectionDAGBuilder::visitFPTrunc(const User &I) {
  2137. // FPTrunc is never a no-op cast, no need to check
  2138. SDValue N = getValue(I.getOperand(0));
  2139. EVT DestVT = TLI.getValueType(I.getType());
  2140. setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
  2141. DestVT, N, DAG.getIntPtrConstant(0)));
  2142. }
  2143. void SelectionDAGBuilder::visitFPExt(const User &I){
  2144. // FPTrunc is never a no-op cast, no need to check
  2145. SDValue N = getValue(I.getOperand(0));
  2146. EVT DestVT = TLI.getValueType(I.getType());
  2147. setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
  2148. }
  2149. void SelectionDAGBuilder::visitFPToUI(const User &I) {
  2150. // FPToUI is never a no-op cast, no need to check
  2151. SDValue N = getValue(I.getOperand(0));
  2152. EVT DestVT = TLI.getValueType(I.getType());
  2153. setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
  2154. }
  2155. void SelectionDAGBuilder::visitFPToSI(const User &I) {
  2156. // FPToSI is never a no-op cast, no need to check
  2157. SDValue N = getValue(I.getOperand(0));
  2158. EVT DestVT = TLI.getValueType(I.getType());
  2159. setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
  2160. }
  2161. void SelectionDAGBuilder::visitUIToFP(const User &I) {
  2162. // UIToFP is never a no-op cast, no need to check
  2163. SDValue N = getValue(I.getOperand(0));
  2164. EVT DestVT = TLI.getValueType(I.getType());
  2165. setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
  2166. }
  2167. void SelectionDAGBuilder::visitSIToFP(const User &I){
  2168. // SIToFP is never a no-op cast, no need to check
  2169. SDValue N = getValue(I.getOperand(0));
  2170. EVT DestVT = TLI.getValueType(I.getType());
  2171. setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
  2172. }
  2173. void SelectionDAGBuilder::visitPtrToInt(const User &I) {
  2174. // What to do depends on the size of the integer and the size of the pointer.
  2175. // We can either truncate, zero extend, or no-op, accordingly.
  2176. SDValue N = getValue(I.getOperand(0));
  2177. EVT DestVT = TLI.getValueType(I.getType());
  2178. setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
  2179. }
  2180. void SelectionDAGBuilder::visitIntToPtr(const User &I) {
  2181. // What to do depends on the size of the integer and the size of the pointer.
  2182. // We can either truncate, zero extend, or no-op, accordingly.
  2183. SDValue N = getValue(I.getOperand(0));
  2184. EVT DestVT = TLI.getValueType(I.getType());
  2185. setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
  2186. }
  2187. void SelectionDAGBuilder::visitBitCast(const User &I) {
  2188. SDValue N = getValue(I.getOperand(0));
  2189. EVT DestVT = TLI.getValueType(I.getType());
  2190. // BitCast assures us that source and destination are the same size so this is
  2191. // either a BITCAST or a no-op.
  2192. if (DestVT != N.getValueType())
  2193. setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
  2194. DestVT, N)); // convert types.
  2195. else
  2196. setValue(&I, N); // noop cast.
  2197. }
  2198. void SelectionDAGBuilder::visitInsertElement(const User &I) {
  2199. SDValue InVec = getValue(I.getOperand(0));
  2200. SDValue InVal = getValue(I.getOperand(1));
  2201. SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  2202. TLI.getPointerTy(),
  2203. getValue(I.getOperand(2)));
  2204. setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
  2205. TLI.getValueType(I.getType()),
  2206. InVec, InVal, InIdx));
  2207. }
  2208. void SelectionDAGBuilder::visitExtractElement(const User &I) {
  2209. SDValue InVec = getValue(I.getOperand(0));
  2210. SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
  2211. TLI.getPointerTy(),
  2212. getValue(I.getOperand(1)));
  2213. setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  2214. TLI.getValueType(I.getType()), InVec, InIdx));
  2215. }
  2216. // Utility for visitShuffleVector - Returns true if the mask is mask starting
  2217. // from SIndx and increasing to the element length (undefs are allowed).
  2218. static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
  2219. unsigned MaskNumElts = Mask.size();
  2220. for (unsigned i = 0; i != MaskNumElts; ++i)
  2221. if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
  2222. return false;
  2223. return true;
  2224. }
  2225. void SelectionDAGBuilder::visitShuffleVector(const User &I) {
  2226. SmallVector<int, 8> Mask;
  2227. SDValue Src1 = getValue(I.getOperand(0));
  2228. SDValue Src2 = getValue(I.getOperand(1));
  2229. // Convert the ConstantVector mask operand into an array of ints, with -1
  2230. // representing undef values.
  2231. SmallVector<Constant*, 8> MaskElts;
  2232. cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
  2233. unsigned MaskNumElts = MaskElts.size();
  2234. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2235. if (isa<UndefValue>(MaskElts[i]))
  2236. Mask.push_back(-1);
  2237. else
  2238. Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
  2239. }
  2240. EVT VT = TLI.getValueType(I.getType());
  2241. EVT SrcVT = Src1.getValueType();
  2242. unsigned SrcNumElts = SrcVT.getVectorNumElements();
  2243. if (SrcNumElts == MaskNumElts) {
  2244. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2245. &Mask[0]));
  2246. return;
  2247. }
  2248. // Normalize the shuffle vector since mask and vector length don't match.
  2249. if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
  2250. // Mask is longer than the source vectors and is a multiple of the source
  2251. // vectors. We can use concatenate vector to make the mask and vectors
  2252. // lengths match.
  2253. if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
  2254. // The shuffle is concatenating two vectors together.
  2255. setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
  2256. VT, Src1, Src2));
  2257. return;
  2258. }
  2259. // Pad both vectors with undefs to make them the same length as the mask.
  2260. unsigned NumConcat = MaskNumElts / SrcNumElts;
  2261. bool Src1U = Src1.getOpcode() == ISD::UNDEF;
  2262. bool Src2U = Src2.getOpcode() == ISD::UNDEF;
  2263. SDValue UndefVal = DAG.getUNDEF(SrcVT);
  2264. SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
  2265. SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
  2266. MOps1[0] = Src1;
  2267. MOps2[0] = Src2;
  2268. Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2269. getCurDebugLoc(), VT,
  2270. &MOps1[0], NumConcat);
  2271. Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
  2272. getCurDebugLoc(), VT,
  2273. &MOps2[0], NumConcat);
  2274. // Readjust mask for new input vector length.
  2275. SmallVector<int, 8> MappedOps;
  2276. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2277. int Idx = Mask[i];
  2278. if (Idx < (int)SrcNumElts)
  2279. MappedOps.push_back(Idx);
  2280. else
  2281. MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
  2282. }
  2283. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2284. &MappedOps[0]));
  2285. return;
  2286. }
  2287. if (SrcNumElts > MaskNumElts) {
  2288. // Analyze the access pattern of the vector to see if we can extract
  2289. // two subvectors and do the shuffle. The analysis is done by calculating
  2290. // the range of elements the mask access on both vectors.
  2291. int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
  2292. int MaxRange[2] = {-1, -1};
  2293. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2294. int Idx = Mask[i];
  2295. int Input = 0;
  2296. if (Idx < 0)
  2297. continue;
  2298. if (Idx >= (int)SrcNumElts) {
  2299. Input = 1;
  2300. Idx -= SrcNumElts;
  2301. }
  2302. if (Idx > MaxRange[Input])
  2303. MaxRange[Input] = Idx;
  2304. if (Idx < MinRange[Input])
  2305. MinRange[Input] = Idx;
  2306. }
  2307. // Check if the access is smaller than the vector size and can we find
  2308. // a reasonable extract index.
  2309. int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
  2310. // Extract.
  2311. int StartIdx[2]; // StartIdx to extract from
  2312. for (int Input=0; Input < 2; ++Input) {
  2313. if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
  2314. RangeUse[Input] = 0; // Unused
  2315. StartIdx[Input] = 0;
  2316. } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
  2317. // Fits within range but we should see if we can find a good
  2318. // start index that is a multiple of the mask length.
  2319. if (MaxRange[Input] < (int)MaskNumElts) {
  2320. RangeUse[Input] = 1; // Extract from beginning of the vector
  2321. StartIdx[Input] = 0;
  2322. } else {
  2323. StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
  2324. if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
  2325. StartIdx[Input] + MaskNumElts <= SrcNumElts)
  2326. RangeUse[Input] = 1; // Extract from a multiple of the mask length.
  2327. }
  2328. }
  2329. }
  2330. if (RangeUse[0] == 0 && RangeUse[1] == 0) {
  2331. setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
  2332. return;
  2333. }
  2334. else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
  2335. // Extract appropriate subvector and generate a vector shuffle
  2336. for (int Input=0; Input < 2; ++Input) {
  2337. SDValue &Src = Input == 0 ? Src1 : Src2;
  2338. if (RangeUse[Input] == 0)
  2339. Src = DAG.getUNDEF(VT);
  2340. else
  2341. Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
  2342. Src, DAG.getIntPtrConstant(StartIdx[Input]));
  2343. }
  2344. // Calculate new mask.
  2345. SmallVector<int, 8> MappedOps;
  2346. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2347. int Idx = Mask[i];
  2348. if (Idx < 0)
  2349. MappedOps.push_back(Idx);
  2350. else if (Idx < (int)SrcNumElts)
  2351. MappedOps.push_back(Idx - StartIdx[0]);
  2352. else
  2353. MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
  2354. }
  2355. setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
  2356. &MappedOps[0]));
  2357. return;
  2358. }
  2359. }
  2360. // We can't use either concat vectors or extract subvectors so fall back to
  2361. // replacing the shuffle with extract and build vector.
  2362. // to insert and build vector.
  2363. EVT EltVT = VT.getVectorElementType();
  2364. EVT PtrVT = TLI.getPointerTy();
  2365. SmallVector<SDValue,8> Ops;
  2366. for (unsigned i = 0; i != MaskNumElts; ++i) {
  2367. if (Mask[i] < 0) {
  2368. Ops.push_back(DAG.getUNDEF(EltVT));
  2369. } else {
  2370. int Idx = Mask[i];
  2371. SDValue Res;
  2372. if (Idx < (int)SrcNumElts)
  2373. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  2374. EltVT, Src1, DAG.getConstant(Idx, PtrVT));
  2375. else
  2376. Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
  2377. EltVT, Src2,
  2378. DAG.getConstant(Idx - SrcNumElts, PtrVT));
  2379. Ops.push_back(Res);
  2380. }
  2381. }
  2382. setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
  2383. VT, &Ops[0], Ops.size()));
  2384. }
  2385. void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
  2386. const Value *Op0 = I.getOperand(0);
  2387. const Value *Op1 = I.getOperand(1);
  2388. const Type *AggTy = I.getType();
  2389. const Type *ValTy = Op1->getType();
  2390. bool IntoUndef = isa<UndefValue>(Op0);
  2391. bool FromUndef = isa<UndefValue>(Op1);
  2392. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end());
  2393. SmallVector<EVT, 4> AggValueVTs;
  2394. ComputeValueVTs(TLI, AggTy, AggValueVTs);
  2395. SmallVector<EVT, 4> ValValueVTs;
  2396. ComputeValueVTs(TLI, ValTy, ValValueVTs);
  2397. unsigned NumAggValues = AggValueVTs.size();
  2398. unsigned NumValValues = ValValueVTs.size();
  2399. SmallVector<SDValue, 4> Values(NumAggValues);
  2400. SDValue Agg = getValue(Op0);
  2401. SDValue Val = getValue(Op1);
  2402. unsigned i = 0;
  2403. // Copy the beginning value(s) from the original aggregate.
  2404. for (; i != LinearIndex; ++i)
  2405. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2406. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2407. // Copy values from the inserted value(s).
  2408. for (; i != LinearIndex + NumValValues; ++i)
  2409. Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2410. SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
  2411. // Copy remaining value(s) from the original aggregate.
  2412. for (; i != NumAggValues; ++i)
  2413. Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
  2414. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2415. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2416. DAG.getVTList(&AggValueVTs[0], NumAggValues),
  2417. &Values[0], NumAggValues));
  2418. }
  2419. void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
  2420. const Value *Op0 = I.getOperand(0);
  2421. const Type *AggTy = Op0->getType();
  2422. const Type *ValTy = I.getType();
  2423. bool OutOfUndef = isa<UndefValue>(Op0);
  2424. unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end());
  2425. SmallVector<EVT, 4> ValValueVTs;
  2426. ComputeValueVTs(TLI, ValTy, ValValueVTs);
  2427. unsigned NumValValues = ValValueVTs.size();
  2428. SmallVector<SDValue, 4> Values(NumValValues);
  2429. SDValue Agg = getValue(Op0);
  2430. // Copy out the selected value(s).
  2431. for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
  2432. Values[i - LinearIndex] =
  2433. OutOfUndef ?
  2434. DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
  2435. SDValue(Agg.getNode(), Agg.getResNo() + i);
  2436. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2437. DAG.getVTList(&ValValueVTs[0], NumValValues),
  2438. &Values[0], NumValValues));
  2439. }
  2440. void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
  2441. SDValue N = getValue(I.getOperand(0));
  2442. const Type *Ty = I.getOperand(0)->getType();
  2443. for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
  2444. OI != E; ++OI) {
  2445. const Value *Idx = *OI;
  2446. if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
  2447. unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
  2448. if (Field) {
  2449. // N = N + Offset
  2450. uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
  2451. N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
  2452. DAG.getIntPtrConstant(Offset));
  2453. }
  2454. Ty = StTy->getElementType(Field);
  2455. } else {
  2456. Ty = cast<SequentialType>(Ty)->getElementType();
  2457. // If this is a constant subscript, handle it quickly.
  2458. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
  2459. if (CI->isZero()) continue;
  2460. uint64_t Offs =
  2461. TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
  2462. SDValue OffsVal;
  2463. EVT PTy = TLI.getPointerTy();
  2464. unsigned PtrBits = PTy.getSizeInBits();
  2465. if (PtrBits < 64)
  2466. OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
  2467. TLI.getPointerTy(),
  2468. DAG.getConstant(Offs, MVT::i64));
  2469. else
  2470. OffsVal = DAG.getIntPtrConstant(Offs);
  2471. N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
  2472. OffsVal);
  2473. continue;
  2474. }
  2475. // N = N + Idx * ElementSize;
  2476. APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
  2477. TD->getTypeAllocSize(Ty));
  2478. SDValue IdxN = getValue(Idx);
  2479. // If the index is smaller or larger than intptr_t, truncate or extend
  2480. // it.
  2481. IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
  2482. // If this is a multiply by a power of two, turn it into a shl
  2483. // immediately. This is a very common case.
  2484. if (ElementSize != 1) {
  2485. if (ElementSize.isPowerOf2()) {
  2486. unsigned Amt = ElementSize.logBase2();
  2487. IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
  2488. N.getValueType(), IdxN,
  2489. DAG.getConstant(Amt, TLI.getPointerTy()));
  2490. } else {
  2491. SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
  2492. IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
  2493. N.getValueType(), IdxN, Scale);
  2494. }
  2495. }
  2496. N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2497. N.getValueType(), N, IdxN);
  2498. }
  2499. }
  2500. setValue(&I, N);
  2501. }
  2502. void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
  2503. // If this is a fixed sized alloca in the entry block of the function,
  2504. // allocate it statically on the stack.
  2505. if (FuncInfo.StaticAllocaMap.count(&I))
  2506. return; // getValue will auto-populate this.
  2507. const Type *Ty = I.getAllocatedType();
  2508. uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
  2509. unsigned Align =
  2510. std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
  2511. I.getAlignment());
  2512. SDValue AllocSize = getValue(I.getArraySize());
  2513. EVT IntPtr = TLI.getPointerTy();
  2514. if (AllocSize.getValueType() != IntPtr)
  2515. AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
  2516. AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
  2517. AllocSize,
  2518. DAG.getConstant(TySize, IntPtr));
  2519. // Handle alignment. If the requested alignment is less than or equal to
  2520. // the stack alignment, ignore it. If the size is greater than or equal to
  2521. // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
  2522. unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
  2523. if (Align <= StackAlign)
  2524. Align = 0;
  2525. // Round the size of the allocation up to the stack alignment size
  2526. // by add SA-1 to the size.
  2527. AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2528. AllocSize.getValueType(), AllocSize,
  2529. DAG.getIntPtrConstant(StackAlign-1));
  2530. // Mask out the low bits for alignment purposes.
  2531. AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
  2532. AllocSize.getValueType(), AllocSize,
  2533. DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
  2534. SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
  2535. SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
  2536. SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
  2537. VTs, Ops, 3);
  2538. setValue(&I, DSA);
  2539. DAG.setRoot(DSA.getValue(1));
  2540. // Inform the Frame Information that we have just allocated a variable-sized
  2541. // object.
  2542. FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
  2543. }
  2544. void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
  2545. const Value *SV = I.getOperand(0);
  2546. SDValue Ptr = getValue(SV);
  2547. const Type *Ty = I.getType();
  2548. bool isVolatile = I.isVolatile();
  2549. bool isNonTemporal = I.getMetadata("nontemporal") != 0;
  2550. unsigned Alignment = I.getAlignment();
  2551. const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
  2552. SmallVector<EVT, 4> ValueVTs;
  2553. SmallVector<uint64_t, 4> Offsets;
  2554. ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
  2555. unsigned NumValues = ValueVTs.size();
  2556. if (NumValues == 0)
  2557. return;
  2558. SDValue Root;
  2559. bool ConstantMemory = false;
  2560. if (I.isVolatile() || NumValues > MaxParallelChains)
  2561. // Serialize volatile loads with other side effects.
  2562. Root = getRoot();
  2563. else if (AA->pointsToConstantMemory(
  2564. AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
  2565. // Do not serialize (non-volatile) loads of constant memory with anything.
  2566. Root = DAG.getEntryNode();
  2567. ConstantMemory = true;
  2568. } else {
  2569. // Do not serialize non-volatile loads against each other.
  2570. Root = DAG.getRoot();
  2571. }
  2572. SmallVector<SDValue, 4> Values(NumValues);
  2573. SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
  2574. NumValues));
  2575. EVT PtrVT = Ptr.getValueType();
  2576. unsigned ChainI = 0;
  2577. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  2578. // Serializing loads here may result in excessive register pressure, and
  2579. // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
  2580. // could recover a bit by hoisting nodes upward in the chain by recognizing
  2581. // they are side-effect free or do not alias. The optimizer should really
  2582. // avoid this case by converting large object/array copies to llvm.memcpy
  2583. // (MaxParallelChains should always remain as failsafe).
  2584. if (ChainI == MaxParallelChains) {
  2585. assert(PendingLoads.empty() && "PendingLoads must be serialized first");
  2586. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  2587. MVT::Other, &Chains[0], ChainI);
  2588. Root = Chain;
  2589. ChainI = 0;
  2590. }
  2591. SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
  2592. PtrVT, Ptr,
  2593. DAG.getConstant(Offsets[i], PtrVT));
  2594. SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
  2595. A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
  2596. isNonTemporal, Alignment, TBAAInfo);
  2597. Values[i] = L;
  2598. Chains[ChainI] = L.getValue(1);
  2599. }
  2600. if (!ConstantMemory) {
  2601. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  2602. MVT::Other, &Chains[0], ChainI);
  2603. if (isVolatile)
  2604. DAG.setRoot(Chain);
  2605. else
  2606. PendingLoads.push_back(Chain);
  2607. }
  2608. setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  2609. DAG.getVTList(&ValueVTs[0], NumValues),
  2610. &Values[0], NumValues));
  2611. }
  2612. void SelectionDAGBuilder::visitStore(const StoreInst &I) {
  2613. const Value *SrcV = I.getOperand(0);
  2614. const Value *PtrV = I.getOperand(1);
  2615. SmallVector<EVT, 4> ValueVTs;
  2616. SmallVector<uint64_t, 4> Offsets;
  2617. ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
  2618. unsigned NumValues = ValueVTs.size();
  2619. if (NumValues == 0)
  2620. return;
  2621. // Get the lowered operands. Note that we do this after
  2622. // checking if NumResults is zero, because with zero results
  2623. // the operands won't have values in the map.
  2624. SDValue Src = getValue(SrcV);
  2625. SDValue Ptr = getValue(PtrV);
  2626. SDValue Root = getRoot();
  2627. SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
  2628. NumValues));
  2629. EVT PtrVT = Ptr.getValueType();
  2630. bool isVolatile = I.isVolatile();
  2631. bool isNonTemporal = I.getMetadata("nontemporal") != 0;
  2632. unsigned Alignment = I.getAlignment();
  2633. const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
  2634. unsigned ChainI = 0;
  2635. for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
  2636. // See visitLoad comments.
  2637. if (ChainI == MaxParallelChains) {
  2638. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  2639. MVT::Other, &Chains[0], ChainI);
  2640. Root = Chain;
  2641. ChainI = 0;
  2642. }
  2643. SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
  2644. DAG.getConstant(Offsets[i], PtrVT));
  2645. SDValue St = DAG.getStore(Root, getCurDebugLoc(),
  2646. SDValue(Src.getNode(), Src.getResNo() + i),
  2647. Add, MachinePointerInfo(PtrV, Offsets[i]),
  2648. isVolatile, isNonTemporal, Alignment, TBAAInfo);
  2649. Chains[ChainI] = St;
  2650. }
  2651. SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  2652. MVT::Other, &Chains[0], ChainI);
  2653. ++SDNodeOrder;
  2654. AssignOrderingToNode(StoreNode.getNode());
  2655. DAG.setRoot(StoreNode);
  2656. }
  2657. /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
  2658. /// node.
  2659. void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
  2660. unsigned Intrinsic) {
  2661. bool HasChain = !I.doesNotAccessMemory();
  2662. bool OnlyLoad = HasChain && I.onlyReadsMemory();
  2663. // Build the operand list.
  2664. SmallVector<SDValue, 8> Ops;
  2665. if (HasChain) { // If this intrinsic has side-effects, chainify it.
  2666. if (OnlyLoad) {
  2667. // We don't need to serialize loads against other loads.
  2668. Ops.push_back(DAG.getRoot());
  2669. } else {
  2670. Ops.push_back(getRoot());
  2671. }
  2672. }
  2673. // Info is set by getTgtMemInstrinsic
  2674. TargetLowering::IntrinsicInfo Info;
  2675. bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
  2676. // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
  2677. if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
  2678. Info.opc == ISD::INTRINSIC_W_CHAIN)
  2679. Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
  2680. // Add all operands of the call to the operand list.
  2681. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  2682. SDValue Op = getValue(I.getArgOperand(i));
  2683. assert(TLI.isTypeLegal(Op.getValueType()) &&
  2684. "Intrinsic uses a non-legal type?");
  2685. Ops.push_back(Op);
  2686. }
  2687. SmallVector<EVT, 4> ValueVTs;
  2688. ComputeValueVTs(TLI, I.getType(), ValueVTs);
  2689. #ifndef NDEBUG
  2690. for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
  2691. assert(TLI.isTypeLegal(ValueVTs[Val]) &&
  2692. "Intrinsic uses a non-legal type?");
  2693. }
  2694. #endif // NDEBUG
  2695. if (HasChain)
  2696. ValueVTs.push_back(MVT::Other);
  2697. SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
  2698. // Create the node.
  2699. SDValue Result;
  2700. if (IsTgtIntrinsic) {
  2701. // This is target intrinsic that touches memory
  2702. Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
  2703. VTs, &Ops[0], Ops.size(),
  2704. Info.memVT,
  2705. MachinePointerInfo(Info.ptrVal, Info.offset),
  2706. Info.align, Info.vol,
  2707. Info.readMem, Info.writeMem);
  2708. } else if (!HasChain) {
  2709. Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
  2710. VTs, &Ops[0], Ops.size());
  2711. } else if (!I.getType()->isVoidTy()) {
  2712. Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
  2713. VTs, &Ops[0], Ops.size());
  2714. } else {
  2715. Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
  2716. VTs, &Ops[0], Ops.size());
  2717. }
  2718. if (HasChain) {
  2719. SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
  2720. if (OnlyLoad)
  2721. PendingLoads.push_back(Chain);
  2722. else
  2723. DAG.setRoot(Chain);
  2724. }
  2725. if (!I.getType()->isVoidTy()) {
  2726. if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
  2727. EVT VT = TLI.getValueType(PTy);
  2728. Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
  2729. }
  2730. setValue(&I, Result);
  2731. }
  2732. }
  2733. /// GetSignificand - Get the significand and build it into a floating-point
  2734. /// number with exponent of 1:
  2735. ///
  2736. /// Op = (Op & 0x007fffff) | 0x3f800000;
  2737. ///
  2738. /// where Op is the hexidecimal representation of floating point value.
  2739. static SDValue
  2740. GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
  2741. SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  2742. DAG.getConstant(0x007fffff, MVT::i32));
  2743. SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
  2744. DAG.getConstant(0x3f800000, MVT::i32));
  2745. return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
  2746. }
  2747. /// GetExponent - Get the exponent:
  2748. ///
  2749. /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
  2750. ///
  2751. /// where Op is the hexidecimal representation of floating point value.
  2752. static SDValue
  2753. GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
  2754. DebugLoc dl) {
  2755. SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
  2756. DAG.getConstant(0x7f800000, MVT::i32));
  2757. SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
  2758. DAG.getConstant(23, TLI.getPointerTy()));
  2759. SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
  2760. DAG.getConstant(127, MVT::i32));
  2761. return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
  2762. }
  2763. /// getF32Constant - Get 32-bit floating point constant.
  2764. static SDValue
  2765. getF32Constant(SelectionDAG &DAG, unsigned Flt) {
  2766. return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
  2767. }
  2768. /// Inlined utility function to implement binary input atomic intrinsics for
  2769. /// visitIntrinsicCall: I is a call instruction
  2770. /// Op is the associated NodeType for I
  2771. const char *
  2772. SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
  2773. ISD::NodeType Op) {
  2774. SDValue Root = getRoot();
  2775. SDValue L =
  2776. DAG.getAtomic(Op, getCurDebugLoc(),
  2777. getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
  2778. Root,
  2779. getValue(I.getArgOperand(0)),
  2780. getValue(I.getArgOperand(1)),
  2781. I.getArgOperand(0));
  2782. setValue(&I, L);
  2783. DAG.setRoot(L.getValue(1));
  2784. return 0;
  2785. }
  2786. // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
  2787. const char *
  2788. SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
  2789. SDValue Op1 = getValue(I.getArgOperand(0));
  2790. SDValue Op2 = getValue(I.getArgOperand(1));
  2791. SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
  2792. setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
  2793. return 0;
  2794. }
  2795. /// visitExp - Lower an exp intrinsic. Handles the special sequences for
  2796. /// limited-precision mode.
  2797. void
  2798. SelectionDAGBuilder::visitExp(const CallInst &I) {
  2799. SDValue result;
  2800. DebugLoc dl = getCurDebugLoc();
  2801. if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
  2802. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2803. SDValue Op = getValue(I.getArgOperand(0));
  2804. // Put the exponent in the right bit position for later addition to the
  2805. // final result:
  2806. //
  2807. // #define LOG2OFe 1.4426950f
  2808. // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
  2809. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  2810. getF32Constant(DAG, 0x3fb8aa3b));
  2811. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  2812. // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
  2813. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  2814. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  2815. // IntegerPartOfX <<= 23;
  2816. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  2817. DAG.getConstant(23, TLI.getPointerTy()));
  2818. if (LimitFloatPrecision <= 6) {
  2819. // For floating-point precision of 6:
  2820. //
  2821. // TwoToFractionalPartOfX =
  2822. // 0.997535578f +
  2823. // (0.735607626f + 0.252464424f * x) * x;
  2824. //
  2825. // error 0.0144103317, which is 6 bits
  2826. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2827. getF32Constant(DAG, 0x3e814304));
  2828. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2829. getF32Constant(DAG, 0x3f3c50c8));
  2830. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2831. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2832. getF32Constant(DAG, 0x3f7f5e7e));
  2833. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
  2834. // Add the exponent into the result in integer domain.
  2835. SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2836. TwoToFracPartOfX, IntegerPartOfX);
  2837. result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
  2838. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2839. // For floating-point precision of 12:
  2840. //
  2841. // TwoToFractionalPartOfX =
  2842. // 0.999892986f +
  2843. // (0.696457318f +
  2844. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  2845. //
  2846. // 0.000107046256 error, which is 13 to 14 bits
  2847. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2848. getF32Constant(DAG, 0x3da235e3));
  2849. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2850. getF32Constant(DAG, 0x3e65b8f3));
  2851. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2852. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2853. getF32Constant(DAG, 0x3f324b07));
  2854. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2855. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  2856. getF32Constant(DAG, 0x3f7ff8fd));
  2857. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
  2858. // Add the exponent into the result in integer domain.
  2859. SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2860. TwoToFracPartOfX, IntegerPartOfX);
  2861. result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
  2862. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  2863. // For floating-point precision of 18:
  2864. //
  2865. // TwoToFractionalPartOfX =
  2866. // 0.999999982f +
  2867. // (0.693148872f +
  2868. // (0.240227044f +
  2869. // (0.554906021e-1f +
  2870. // (0.961591928e-2f +
  2871. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  2872. //
  2873. // error 2.47208000*10^(-7), which is better than 18 bits
  2874. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2875. getF32Constant(DAG, 0x3924b03e));
  2876. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  2877. getF32Constant(DAG, 0x3ab24b87));
  2878. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2879. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2880. getF32Constant(DAG, 0x3c1d8c17));
  2881. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2882. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  2883. getF32Constant(DAG, 0x3d634a1d));
  2884. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  2885. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  2886. getF32Constant(DAG, 0x3e75fe14));
  2887. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  2888. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  2889. getF32Constant(DAG, 0x3f317234));
  2890. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  2891. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  2892. getF32Constant(DAG, 0x3f800000));
  2893. SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
  2894. MVT::i32, t13);
  2895. // Add the exponent into the result in integer domain.
  2896. SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
  2897. TwoToFracPartOfX, IntegerPartOfX);
  2898. result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
  2899. }
  2900. } else {
  2901. // No special expansion.
  2902. result = DAG.getNode(ISD::FEXP, dl,
  2903. getValue(I.getArgOperand(0)).getValueType(),
  2904. getValue(I.getArgOperand(0)));
  2905. }
  2906. setValue(&I, result);
  2907. }
  2908. /// visitLog - Lower a log intrinsic. Handles the special sequences for
  2909. /// limited-precision mode.
  2910. void
  2911. SelectionDAGBuilder::visitLog(const CallInst &I) {
  2912. SDValue result;
  2913. DebugLoc dl = getCurDebugLoc();
  2914. if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
  2915. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  2916. SDValue Op = getValue(I.getArgOperand(0));
  2917. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  2918. // Scale the exponent by log(2) [0.69314718f].
  2919. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  2920. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  2921. getF32Constant(DAG, 0x3f317218));
  2922. // Get the significand and build it into a floating-point number with
  2923. // exponent of 1.
  2924. SDValue X = GetSignificand(DAG, Op1, dl);
  2925. if (LimitFloatPrecision <= 6) {
  2926. // For floating-point precision of 6:
  2927. //
  2928. // LogofMantissa =
  2929. // -1.1609546f +
  2930. // (1.4034025f - 0.23903021f * x) * x;
  2931. //
  2932. // error 0.0034276066, which is better than 8 bits
  2933. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2934. getF32Constant(DAG, 0xbe74c456));
  2935. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2936. getF32Constant(DAG, 0x3fb3a2b1));
  2937. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2938. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2939. getF32Constant(DAG, 0x3f949a29));
  2940. result = DAG.getNode(ISD::FADD, dl,
  2941. MVT::f32, LogOfExponent, LogOfMantissa);
  2942. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  2943. // For floating-point precision of 12:
  2944. //
  2945. // LogOfMantissa =
  2946. // -1.7417939f +
  2947. // (2.8212026f +
  2948. // (-1.4699568f +
  2949. // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
  2950. //
  2951. // error 0.000061011436, which is 14 bits
  2952. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2953. getF32Constant(DAG, 0xbd67b6d6));
  2954. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2955. getF32Constant(DAG, 0x3ee4f4b8));
  2956. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2957. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2958. getF32Constant(DAG, 0x3fbc278b));
  2959. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2960. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2961. getF32Constant(DAG, 0x40348e95));
  2962. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2963. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  2964. getF32Constant(DAG, 0x3fdef31a));
  2965. result = DAG.getNode(ISD::FADD, dl,
  2966. MVT::f32, LogOfExponent, LogOfMantissa);
  2967. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  2968. // For floating-point precision of 18:
  2969. //
  2970. // LogOfMantissa =
  2971. // -2.1072184f +
  2972. // (4.2372794f +
  2973. // (-3.7029485f +
  2974. // (2.2781945f +
  2975. // (-0.87823314f +
  2976. // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
  2977. //
  2978. // error 0.0000023660568, which is better than 18 bits
  2979. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  2980. getF32Constant(DAG, 0xbc91e5ac));
  2981. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  2982. getF32Constant(DAG, 0x3e4350aa));
  2983. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  2984. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  2985. getF32Constant(DAG, 0x3f60d3e3));
  2986. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  2987. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  2988. getF32Constant(DAG, 0x4011cdf0));
  2989. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  2990. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  2991. getF32Constant(DAG, 0x406cfd1c));
  2992. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  2993. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  2994. getF32Constant(DAG, 0x408797cb));
  2995. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  2996. SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  2997. getF32Constant(DAG, 0x4006dcab));
  2998. result = DAG.getNode(ISD::FADD, dl,
  2999. MVT::f32, LogOfExponent, LogOfMantissa);
  3000. }
  3001. } else {
  3002. // No special expansion.
  3003. result = DAG.getNode(ISD::FLOG, dl,
  3004. getValue(I.getArgOperand(0)).getValueType(),
  3005. getValue(I.getArgOperand(0)));
  3006. }
  3007. setValue(&I, result);
  3008. }
  3009. /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
  3010. /// limited-precision mode.
  3011. void
  3012. SelectionDAGBuilder::visitLog2(const CallInst &I) {
  3013. SDValue result;
  3014. DebugLoc dl = getCurDebugLoc();
  3015. if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
  3016. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3017. SDValue Op = getValue(I.getArgOperand(0));
  3018. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3019. // Get the exponent.
  3020. SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
  3021. // Get the significand and build it into a floating-point number with
  3022. // exponent of 1.
  3023. SDValue X = GetSignificand(DAG, Op1, dl);
  3024. // Different possible minimax approximations of significand in
  3025. // floating-point for various degrees of accuracy over [1,2].
  3026. if (LimitFloatPrecision <= 6) {
  3027. // For floating-point precision of 6:
  3028. //
  3029. // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
  3030. //
  3031. // error 0.0049451742, which is more than 7 bits
  3032. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3033. getF32Constant(DAG, 0xbeb08fe0));
  3034. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3035. getF32Constant(DAG, 0x40019463));
  3036. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3037. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3038. getF32Constant(DAG, 0x3fd6633d));
  3039. result = DAG.getNode(ISD::FADD, dl,
  3040. MVT::f32, LogOfExponent, Log2ofMantissa);
  3041. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  3042. // For floating-point precision of 12:
  3043. //
  3044. // Log2ofMantissa =
  3045. // -2.51285454f +
  3046. // (4.07009056f +
  3047. // (-2.12067489f +
  3048. // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
  3049. //
  3050. // error 0.0000876136000, which is better than 13 bits
  3051. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3052. getF32Constant(DAG, 0xbda7262e));
  3053. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3054. getF32Constant(DAG, 0x3f25280b));
  3055. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3056. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3057. getF32Constant(DAG, 0x4007b923));
  3058. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3059. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3060. getF32Constant(DAG, 0x40823e2f));
  3061. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3062. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3063. getF32Constant(DAG, 0x4020d29c));
  3064. result = DAG.getNode(ISD::FADD, dl,
  3065. MVT::f32, LogOfExponent, Log2ofMantissa);
  3066. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3067. // For floating-point precision of 18:
  3068. //
  3069. // Log2ofMantissa =
  3070. // -3.0400495f +
  3071. // (6.1129976f +
  3072. // (-5.3420409f +
  3073. // (3.2865683f +
  3074. // (-1.2669343f +
  3075. // (0.27515199f -
  3076. // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
  3077. //
  3078. // error 0.0000018516, which is better than 18 bits
  3079. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3080. getF32Constant(DAG, 0xbcd2769e));
  3081. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3082. getF32Constant(DAG, 0x3e8ce0b9));
  3083. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3084. SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3085. getF32Constant(DAG, 0x3fa22ae7));
  3086. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3087. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3088. getF32Constant(DAG, 0x40525723));
  3089. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3090. SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
  3091. getF32Constant(DAG, 0x40aaf200));
  3092. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3093. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3094. getF32Constant(DAG, 0x40c39dad));
  3095. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3096. SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
  3097. getF32Constant(DAG, 0x4042902c));
  3098. result = DAG.getNode(ISD::FADD, dl,
  3099. MVT::f32, LogOfExponent, Log2ofMantissa);
  3100. }
  3101. } else {
  3102. // No special expansion.
  3103. result = DAG.getNode(ISD::FLOG2, dl,
  3104. getValue(I.getArgOperand(0)).getValueType(),
  3105. getValue(I.getArgOperand(0)));
  3106. }
  3107. setValue(&I, result);
  3108. }
  3109. /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
  3110. /// limited-precision mode.
  3111. void
  3112. SelectionDAGBuilder::visitLog10(const CallInst &I) {
  3113. SDValue result;
  3114. DebugLoc dl = getCurDebugLoc();
  3115. if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
  3116. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3117. SDValue Op = getValue(I.getArgOperand(0));
  3118. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
  3119. // Scale the exponent by log10(2) [0.30102999f].
  3120. SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
  3121. SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
  3122. getF32Constant(DAG, 0x3e9a209a));
  3123. // Get the significand and build it into a floating-point number with
  3124. // exponent of 1.
  3125. SDValue X = GetSignificand(DAG, Op1, dl);
  3126. if (LimitFloatPrecision <= 6) {
  3127. // For floating-point precision of 6:
  3128. //
  3129. // Log10ofMantissa =
  3130. // -0.50419619f +
  3131. // (0.60948995f - 0.10380950f * x) * x;
  3132. //
  3133. // error 0.0014886165, which is 6 bits
  3134. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3135. getF32Constant(DAG, 0xbdd49a13));
  3136. SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
  3137. getF32Constant(DAG, 0x3f1c0789));
  3138. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3139. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
  3140. getF32Constant(DAG, 0x3f011300));
  3141. result = DAG.getNode(ISD::FADD, dl,
  3142. MVT::f32, LogOfExponent, Log10ofMantissa);
  3143. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  3144. // For floating-point precision of 12:
  3145. //
  3146. // Log10ofMantissa =
  3147. // -0.64831180f +
  3148. // (0.91751397f +
  3149. // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
  3150. //
  3151. // error 0.00019228036, which is better than 12 bits
  3152. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3153. getF32Constant(DAG, 0x3d431f31));
  3154. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3155. getF32Constant(DAG, 0x3ea21fb2));
  3156. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3157. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3158. getF32Constant(DAG, 0x3f6ae232));
  3159. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3160. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3161. getF32Constant(DAG, 0x3f25f7c3));
  3162. result = DAG.getNode(ISD::FADD, dl,
  3163. MVT::f32, LogOfExponent, Log10ofMantissa);
  3164. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3165. // For floating-point precision of 18:
  3166. //
  3167. // Log10ofMantissa =
  3168. // -0.84299375f +
  3169. // (1.5327582f +
  3170. // (-1.0688956f +
  3171. // (0.49102474f +
  3172. // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
  3173. //
  3174. // error 0.0000037995730, which is better than 18 bits
  3175. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3176. getF32Constant(DAG, 0x3c5d51ce));
  3177. SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
  3178. getF32Constant(DAG, 0x3e00685a));
  3179. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
  3180. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3181. getF32Constant(DAG, 0x3efb6798));
  3182. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3183. SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
  3184. getF32Constant(DAG, 0x3f88d192));
  3185. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3186. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3187. getF32Constant(DAG, 0x3fc4316c));
  3188. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3189. SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
  3190. getF32Constant(DAG, 0x3f57ce70));
  3191. result = DAG.getNode(ISD::FADD, dl,
  3192. MVT::f32, LogOfExponent, Log10ofMantissa);
  3193. }
  3194. } else {
  3195. // No special expansion.
  3196. result = DAG.getNode(ISD::FLOG10, dl,
  3197. getValue(I.getArgOperand(0)).getValueType(),
  3198. getValue(I.getArgOperand(0)));
  3199. }
  3200. setValue(&I, result);
  3201. }
  3202. /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
  3203. /// limited-precision mode.
  3204. void
  3205. SelectionDAGBuilder::visitExp2(const CallInst &I) {
  3206. SDValue result;
  3207. DebugLoc dl = getCurDebugLoc();
  3208. if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
  3209. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3210. SDValue Op = getValue(I.getArgOperand(0));
  3211. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
  3212. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3213. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3214. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
  3215. // IntegerPartOfX <<= 23;
  3216. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3217. DAG.getConstant(23, TLI.getPointerTy()));
  3218. if (LimitFloatPrecision <= 6) {
  3219. // For floating-point precision of 6:
  3220. //
  3221. // TwoToFractionalPartOfX =
  3222. // 0.997535578f +
  3223. // (0.735607626f + 0.252464424f * x) * x;
  3224. //
  3225. // error 0.0144103317, which is 6 bits
  3226. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3227. getF32Constant(DAG, 0x3e814304));
  3228. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3229. getF32Constant(DAG, 0x3f3c50c8));
  3230. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3231. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3232. getF32Constant(DAG, 0x3f7f5e7e));
  3233. SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
  3234. SDValue TwoToFractionalPartOfX =
  3235. DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
  3236. result = DAG.getNode(ISD::BITCAST, dl,
  3237. MVT::f32, TwoToFractionalPartOfX);
  3238. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  3239. // For floating-point precision of 12:
  3240. //
  3241. // TwoToFractionalPartOfX =
  3242. // 0.999892986f +
  3243. // (0.696457318f +
  3244. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3245. //
  3246. // error 0.000107046256, which is 13 to 14 bits
  3247. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3248. getF32Constant(DAG, 0x3da235e3));
  3249. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3250. getF32Constant(DAG, 0x3e65b8f3));
  3251. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3252. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3253. getF32Constant(DAG, 0x3f324b07));
  3254. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3255. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3256. getF32Constant(DAG, 0x3f7ff8fd));
  3257. SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
  3258. SDValue TwoToFractionalPartOfX =
  3259. DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
  3260. result = DAG.getNode(ISD::BITCAST, dl,
  3261. MVT::f32, TwoToFractionalPartOfX);
  3262. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3263. // For floating-point precision of 18:
  3264. //
  3265. // TwoToFractionalPartOfX =
  3266. // 0.999999982f +
  3267. // (0.693148872f +
  3268. // (0.240227044f +
  3269. // (0.554906021e-1f +
  3270. // (0.961591928e-2f +
  3271. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3272. // error 2.47208000*10^(-7), which is better than 18 bits
  3273. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3274. getF32Constant(DAG, 0x3924b03e));
  3275. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3276. getF32Constant(DAG, 0x3ab24b87));
  3277. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3278. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3279. getF32Constant(DAG, 0x3c1d8c17));
  3280. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3281. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3282. getF32Constant(DAG, 0x3d634a1d));
  3283. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3284. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3285. getF32Constant(DAG, 0x3e75fe14));
  3286. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3287. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3288. getF32Constant(DAG, 0x3f317234));
  3289. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3290. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3291. getF32Constant(DAG, 0x3f800000));
  3292. SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
  3293. SDValue TwoToFractionalPartOfX =
  3294. DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
  3295. result = DAG.getNode(ISD::BITCAST, dl,
  3296. MVT::f32, TwoToFractionalPartOfX);
  3297. }
  3298. } else {
  3299. // No special expansion.
  3300. result = DAG.getNode(ISD::FEXP2, dl,
  3301. getValue(I.getArgOperand(0)).getValueType(),
  3302. getValue(I.getArgOperand(0)));
  3303. }
  3304. setValue(&I, result);
  3305. }
  3306. /// visitPow - Lower a pow intrinsic. Handles the special sequences for
  3307. /// limited-precision mode with x == 10.0f.
  3308. void
  3309. SelectionDAGBuilder::visitPow(const CallInst &I) {
  3310. SDValue result;
  3311. const Value *Val = I.getArgOperand(0);
  3312. DebugLoc dl = getCurDebugLoc();
  3313. bool IsExp10 = false;
  3314. if (getValue(Val).getValueType() == MVT::f32 &&
  3315. getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
  3316. LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3317. if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
  3318. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  3319. APFloat Ten(10.0f);
  3320. IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
  3321. }
  3322. }
  3323. }
  3324. if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
  3325. SDValue Op = getValue(I.getArgOperand(1));
  3326. // Put the exponent in the right bit position for later addition to the
  3327. // final result:
  3328. //
  3329. // #define LOG2OF10 3.3219281f
  3330. // IntegerPartOfX = (int32_t)(x * LOG2OF10);
  3331. SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
  3332. getF32Constant(DAG, 0x40549a78));
  3333. SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
  3334. // FractionalPartOfX = x - (float)IntegerPartOfX;
  3335. SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
  3336. SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
  3337. // IntegerPartOfX <<= 23;
  3338. IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
  3339. DAG.getConstant(23, TLI.getPointerTy()));
  3340. if (LimitFloatPrecision <= 6) {
  3341. // For floating-point precision of 6:
  3342. //
  3343. // twoToFractionalPartOfX =
  3344. // 0.997535578f +
  3345. // (0.735607626f + 0.252464424f * x) * x;
  3346. //
  3347. // error 0.0144103317, which is 6 bits
  3348. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3349. getF32Constant(DAG, 0x3e814304));
  3350. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3351. getF32Constant(DAG, 0x3f3c50c8));
  3352. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3353. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3354. getF32Constant(DAG, 0x3f7f5e7e));
  3355. SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
  3356. SDValue TwoToFractionalPartOfX =
  3357. DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
  3358. result = DAG.getNode(ISD::BITCAST, dl,
  3359. MVT::f32, TwoToFractionalPartOfX);
  3360. } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
  3361. // For floating-point precision of 12:
  3362. //
  3363. // TwoToFractionalPartOfX =
  3364. // 0.999892986f +
  3365. // (0.696457318f +
  3366. // (0.224338339f + 0.792043434e-1f * x) * x) * x;
  3367. //
  3368. // error 0.000107046256, which is 13 to 14 bits
  3369. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3370. getF32Constant(DAG, 0x3da235e3));
  3371. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3372. getF32Constant(DAG, 0x3e65b8f3));
  3373. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3374. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3375. getF32Constant(DAG, 0x3f324b07));
  3376. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3377. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3378. getF32Constant(DAG, 0x3f7ff8fd));
  3379. SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
  3380. SDValue TwoToFractionalPartOfX =
  3381. DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
  3382. result = DAG.getNode(ISD::BITCAST, dl,
  3383. MVT::f32, TwoToFractionalPartOfX);
  3384. } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
  3385. // For floating-point precision of 18:
  3386. //
  3387. // TwoToFractionalPartOfX =
  3388. // 0.999999982f +
  3389. // (0.693148872f +
  3390. // (0.240227044f +
  3391. // (0.554906021e-1f +
  3392. // (0.961591928e-2f +
  3393. // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
  3394. // error 2.47208000*10^(-7), which is better than 18 bits
  3395. SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
  3396. getF32Constant(DAG, 0x3924b03e));
  3397. SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
  3398. getF32Constant(DAG, 0x3ab24b87));
  3399. SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
  3400. SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
  3401. getF32Constant(DAG, 0x3c1d8c17));
  3402. SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
  3403. SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
  3404. getF32Constant(DAG, 0x3d634a1d));
  3405. SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
  3406. SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
  3407. getF32Constant(DAG, 0x3e75fe14));
  3408. SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
  3409. SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
  3410. getF32Constant(DAG, 0x3f317234));
  3411. SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
  3412. SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
  3413. getF32Constant(DAG, 0x3f800000));
  3414. SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
  3415. SDValue TwoToFractionalPartOfX =
  3416. DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
  3417. result = DAG.getNode(ISD::BITCAST, dl,
  3418. MVT::f32, TwoToFractionalPartOfX);
  3419. }
  3420. } else {
  3421. // No special expansion.
  3422. result = DAG.getNode(ISD::FPOW, dl,
  3423. getValue(I.getArgOperand(0)).getValueType(),
  3424. getValue(I.getArgOperand(0)),
  3425. getValue(I.getArgOperand(1)));
  3426. }
  3427. setValue(&I, result);
  3428. }
  3429. /// ExpandPowI - Expand a llvm.powi intrinsic.
  3430. static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
  3431. SelectionDAG &DAG) {
  3432. // If RHS is a constant, we can expand this out to a multiplication tree,
  3433. // otherwise we end up lowering to a call to __powidf2 (for example). When
  3434. // optimizing for size, we only want to do this if the expansion would produce
  3435. // a small number of multiplies, otherwise we do the full expansion.
  3436. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  3437. // Get the exponent as a positive value.
  3438. unsigned Val = RHSC->getSExtValue();
  3439. if ((int)Val < 0) Val = -Val;
  3440. // powi(x, 0) -> 1.0
  3441. if (Val == 0)
  3442. return DAG.getConstantFP(1.0, LHS.getValueType());
  3443. const Function *F = DAG.getMachineFunction().getFunction();
  3444. if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
  3445. // If optimizing for size, don't insert too many multiplies. This
  3446. // inserts up to 5 multiplies.
  3447. CountPopulation_32(Val)+Log2_32(Val) < 7) {
  3448. // We use the simple binary decomposition method to generate the multiply
  3449. // sequence. There are more optimal ways to do this (for example,
  3450. // powi(x,15) generates one more multiply than it should), but this has
  3451. // the benefit of being both really simple and much better than a libcall.
  3452. SDValue Res; // Logically starts equal to 1.0
  3453. SDValue CurSquare = LHS;
  3454. while (Val) {
  3455. if (Val & 1) {
  3456. if (Res.getNode())
  3457. Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
  3458. else
  3459. Res = CurSquare; // 1.0*CurSquare.
  3460. }
  3461. CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
  3462. CurSquare, CurSquare);
  3463. Val >>= 1;
  3464. }
  3465. // If the original was negative, invert the result, producing 1/(x*x*x).
  3466. if (RHSC->getSExtValue() < 0)
  3467. Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
  3468. DAG.getConstantFP(1.0, LHS.getValueType()), Res);
  3469. return Res;
  3470. }
  3471. }
  3472. // Otherwise, expand to a libcall.
  3473. return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
  3474. }
  3475. /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
  3476. /// argument, create the corresponding DBG_VALUE machine instruction for it now.
  3477. /// At the end of instruction selection, they will be inserted to the entry BB.
  3478. bool
  3479. SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
  3480. int64_t Offset,
  3481. const SDValue &N) {
  3482. const Argument *Arg = dyn_cast<Argument>(V);
  3483. if (!Arg)
  3484. return false;
  3485. MachineFunction &MF = DAG.getMachineFunction();
  3486. const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
  3487. const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
  3488. // Ignore inlined function arguments here.
  3489. DIVariable DV(Variable);
  3490. if (DV.isInlinedFnArgument(MF.getFunction()))
  3491. return false;
  3492. MachineBasicBlock *MBB = FuncInfo.MBB;
  3493. if (MBB != &MF.front())
  3494. return false;
  3495. unsigned Reg = 0;
  3496. if (Arg->hasByValAttr()) {
  3497. // Byval arguments' frame index is recorded during argument lowering.
  3498. // Use this info directly.
  3499. Reg = TRI->getFrameRegister(MF);
  3500. Offset = FuncInfo.getByValArgumentFrameIndex(Arg);
  3501. // If byval argument ofset is not recorded then ignore this.
  3502. if (!Offset)
  3503. Reg = 0;
  3504. }
  3505. if (N.getNode() && N.getOpcode() == ISD::CopyFromReg) {
  3506. Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
  3507. if (TargetRegisterInfo::isVirtualRegister(Reg)) {
  3508. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  3509. unsigned PR = RegInfo.getLiveInPhysReg(Reg);
  3510. if (PR)
  3511. Reg = PR;
  3512. }
  3513. }
  3514. if (!Reg) {
  3515. // Check if ValueMap has reg number.
  3516. DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
  3517. if (VMI != FuncInfo.ValueMap.end())
  3518. Reg = VMI->second;
  3519. }
  3520. if (!Reg && N.getNode()) {
  3521. // Check if frame index is available.
  3522. if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
  3523. if (FrameIndexSDNode *FINode =
  3524. dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
  3525. Reg = TRI->getFrameRegister(MF);
  3526. Offset = FINode->getIndex();
  3527. }
  3528. }
  3529. if (!Reg)
  3530. return false;
  3531. MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
  3532. TII->get(TargetOpcode::DBG_VALUE))
  3533. .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
  3534. FuncInfo.ArgDbgValues.push_back(&*MIB);
  3535. return true;
  3536. }
  3537. // VisualStudio defines setjmp as _setjmp
  3538. #if defined(_MSC_VER) && defined(setjmp) && \
  3539. !defined(setjmp_undefined_for_msvc)
  3540. # pragma push_macro("setjmp")
  3541. # undef setjmp
  3542. # define setjmp_undefined_for_msvc
  3543. #endif
  3544. /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
  3545. /// we want to emit this as a call to a named external function, return the name
  3546. /// otherwise lower it and return null.
  3547. const char *
  3548. SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
  3549. DebugLoc dl = getCurDebugLoc();
  3550. SDValue Res;
  3551. switch (Intrinsic) {
  3552. default:
  3553. // By default, turn this into a target intrinsic node.
  3554. visitTargetIntrinsic(I, Intrinsic);
  3555. return 0;
  3556. case Intrinsic::vastart: visitVAStart(I); return 0;
  3557. case Intrinsic::vaend: visitVAEnd(I); return 0;
  3558. case Intrinsic::vacopy: visitVACopy(I); return 0;
  3559. case Intrinsic::returnaddress:
  3560. setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
  3561. getValue(I.getArgOperand(0))));
  3562. return 0;
  3563. case Intrinsic::frameaddress:
  3564. setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
  3565. getValue(I.getArgOperand(0))));
  3566. return 0;
  3567. case Intrinsic::setjmp:
  3568. return "_setjmp"+!TLI.usesUnderscoreSetJmp();
  3569. case Intrinsic::longjmp:
  3570. return "_longjmp"+!TLI.usesUnderscoreLongJmp();
  3571. case Intrinsic::memcpy: {
  3572. // Assert for address < 256 since we support only user defined address
  3573. // spaces.
  3574. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  3575. < 256 &&
  3576. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  3577. < 256 &&
  3578. "Unknown address space");
  3579. SDValue Op1 = getValue(I.getArgOperand(0));
  3580. SDValue Op2 = getValue(I.getArgOperand(1));
  3581. SDValue Op3 = getValue(I.getArgOperand(2));
  3582. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  3583. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  3584. DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
  3585. MachinePointerInfo(I.getArgOperand(0)),
  3586. MachinePointerInfo(I.getArgOperand(1))));
  3587. return 0;
  3588. }
  3589. case Intrinsic::memset: {
  3590. // Assert for address < 256 since we support only user defined address
  3591. // spaces.
  3592. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  3593. < 256 &&
  3594. "Unknown address space");
  3595. SDValue Op1 = getValue(I.getArgOperand(0));
  3596. SDValue Op2 = getValue(I.getArgOperand(1));
  3597. SDValue Op3 = getValue(I.getArgOperand(2));
  3598. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  3599. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  3600. DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
  3601. MachinePointerInfo(I.getArgOperand(0))));
  3602. return 0;
  3603. }
  3604. case Intrinsic::memmove: {
  3605. // Assert for address < 256 since we support only user defined address
  3606. // spaces.
  3607. assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
  3608. < 256 &&
  3609. cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
  3610. < 256 &&
  3611. "Unknown address space");
  3612. SDValue Op1 = getValue(I.getArgOperand(0));
  3613. SDValue Op2 = getValue(I.getArgOperand(1));
  3614. SDValue Op3 = getValue(I.getArgOperand(2));
  3615. unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
  3616. bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
  3617. DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
  3618. MachinePointerInfo(I.getArgOperand(0)),
  3619. MachinePointerInfo(I.getArgOperand(1))));
  3620. return 0;
  3621. }
  3622. case Intrinsic::dbg_declare: {
  3623. const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
  3624. MDNode *Variable = DI.getVariable();
  3625. const Value *Address = DI.getAddress();
  3626. if (!Address || !DIVariable(DI.getVariable()).Verify())
  3627. return 0;
  3628. // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
  3629. // but do not always have a corresponding SDNode built. The SDNodeOrder
  3630. // absolute, but not relative, values are different depending on whether
  3631. // debug info exists.
  3632. ++SDNodeOrder;
  3633. // Check if address has undef value.
  3634. if (isa<UndefValue>(Address) ||
  3635. (Address->use_empty() && !isa<Argument>(Address))) {
  3636. DEBUG(dbgs() << "Dropping debug info for " << DI);
  3637. return 0;
  3638. }
  3639. SDValue &N = NodeMap[Address];
  3640. if (!N.getNode() && isa<Argument>(Address))
  3641. // Check unused arguments map.
  3642. N = UnusedArgNodeMap[Address];
  3643. SDDbgValue *SDV;
  3644. if (N.getNode()) {
  3645. // Parameters are handled specially.
  3646. bool isParameter =
  3647. DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
  3648. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
  3649. Address = BCI->getOperand(0);
  3650. const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
  3651. if (isParameter && !AI) {
  3652. FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
  3653. if (FINode)
  3654. // Byval parameter. We have a frame index at this point.
  3655. SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
  3656. 0, dl, SDNodeOrder);
  3657. else {
  3658. // Can't do anything with other non-AI cases yet. This might be a
  3659. // parameter of a callee function that got inlined, for example.
  3660. DEBUG(dbgs() << "Dropping debug info for " << DI);
  3661. return 0;
  3662. }
  3663. } else if (AI)
  3664. SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
  3665. 0, dl, SDNodeOrder);
  3666. else {
  3667. // Can't do anything with other non-AI cases yet.
  3668. DEBUG(dbgs() << "Dropping debug info for " << DI);
  3669. return 0;
  3670. }
  3671. DAG.AddDbgValue(SDV, N.getNode(), isParameter);
  3672. } else {
  3673. // If Address is an argument then try to emit its dbg value using
  3674. // virtual register info from the FuncInfo.ValueMap.
  3675. if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
  3676. // If variable is pinned by a alloca in dominating bb then
  3677. // use StaticAllocaMap.
  3678. if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
  3679. if (AI->getParent() != DI.getParent()) {
  3680. DenseMap<const AllocaInst*, int>::iterator SI =
  3681. FuncInfo.StaticAllocaMap.find(AI);
  3682. if (SI != FuncInfo.StaticAllocaMap.end()) {
  3683. SDV = DAG.getDbgValue(Variable, SI->second,
  3684. 0, dl, SDNodeOrder);
  3685. DAG.AddDbgValue(SDV, 0, false);
  3686. return 0;
  3687. }
  3688. }
  3689. }
  3690. DEBUG(dbgs() << "Dropping debug info for " << DI);
  3691. }
  3692. }
  3693. return 0;
  3694. }
  3695. case Intrinsic::dbg_value: {
  3696. const DbgValueInst &DI = cast<DbgValueInst>(I);
  3697. if (!DIVariable(DI.getVariable()).Verify())
  3698. return 0;
  3699. MDNode *Variable = DI.getVariable();
  3700. uint64_t Offset = DI.getOffset();
  3701. const Value *V = DI.getValue();
  3702. if (!V)
  3703. return 0;
  3704. // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
  3705. // but do not always have a corresponding SDNode built. The SDNodeOrder
  3706. // absolute, but not relative, values are different depending on whether
  3707. // debug info exists.
  3708. ++SDNodeOrder;
  3709. SDDbgValue *SDV;
  3710. if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
  3711. SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
  3712. DAG.AddDbgValue(SDV, 0, false);
  3713. } else {
  3714. // Do not use getValue() in here; we don't want to generate code at
  3715. // this point if it hasn't been done yet.
  3716. SDValue N = NodeMap[V];
  3717. if (!N.getNode() && isa<Argument>(V))
  3718. // Check unused arguments map.
  3719. N = UnusedArgNodeMap[V];
  3720. if (N.getNode()) {
  3721. if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
  3722. SDV = DAG.getDbgValue(Variable, N.getNode(),
  3723. N.getResNo(), Offset, dl, SDNodeOrder);
  3724. DAG.AddDbgValue(SDV, N.getNode(), false);
  3725. }
  3726. } else if (!V->use_empty() ) {
  3727. // Do not call getValue(V) yet, as we don't want to generate code.
  3728. // Remember it for later.
  3729. DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
  3730. DanglingDebugInfoMap[V] = DDI;
  3731. } else {
  3732. // We may expand this to cover more cases. One case where we have no
  3733. // data available is an unreferenced parameter.
  3734. DEBUG(dbgs() << "Dropping debug info for " << DI);
  3735. }
  3736. }
  3737. // Build a debug info table entry.
  3738. if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
  3739. V = BCI->getOperand(0);
  3740. const AllocaInst *AI = dyn_cast<AllocaInst>(V);
  3741. // Don't handle byval struct arguments or VLAs, for example.
  3742. if (!AI)
  3743. return 0;
  3744. DenseMap<const AllocaInst*, int>::iterator SI =
  3745. FuncInfo.StaticAllocaMap.find(AI);
  3746. if (SI == FuncInfo.StaticAllocaMap.end())
  3747. return 0; // VLAs.
  3748. int FI = SI->second;
  3749. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  3750. if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
  3751. MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
  3752. return 0;
  3753. }
  3754. case Intrinsic::eh_exception: {
  3755. // Insert the EXCEPTIONADDR instruction.
  3756. assert(FuncInfo.MBB->isLandingPad() &&
  3757. "Call to eh.exception not in landing pad!");
  3758. SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
  3759. SDValue Ops[1];
  3760. Ops[0] = DAG.getRoot();
  3761. SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
  3762. setValue(&I, Op);
  3763. DAG.setRoot(Op.getValue(1));
  3764. return 0;
  3765. }
  3766. case Intrinsic::eh_selector: {
  3767. MachineBasicBlock *CallMBB = FuncInfo.MBB;
  3768. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  3769. if (CallMBB->isLandingPad())
  3770. AddCatchInfo(I, &MMI, CallMBB);
  3771. else {
  3772. #ifndef NDEBUG
  3773. FuncInfo.CatchInfoLost.insert(&I);
  3774. #endif
  3775. // FIXME: Mark exception selector register as live in. Hack for PR1508.
  3776. unsigned Reg = TLI.getExceptionSelectorRegister();
  3777. if (Reg) FuncInfo.MBB->addLiveIn(Reg);
  3778. }
  3779. // Insert the EHSELECTION instruction.
  3780. SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
  3781. SDValue Ops[2];
  3782. Ops[0] = getValue(I.getArgOperand(0));
  3783. Ops[1] = getRoot();
  3784. SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
  3785. DAG.setRoot(Op.getValue(1));
  3786. setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
  3787. return 0;
  3788. }
  3789. case Intrinsic::eh_typeid_for: {
  3790. // Find the type id for the given typeinfo.
  3791. GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
  3792. unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
  3793. Res = DAG.getConstant(TypeID, MVT::i32);
  3794. setValue(&I, Res);
  3795. return 0;
  3796. }
  3797. case Intrinsic::eh_return_i32:
  3798. case Intrinsic::eh_return_i64:
  3799. DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
  3800. DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
  3801. MVT::Other,
  3802. getControlRoot(),
  3803. getValue(I.getArgOperand(0)),
  3804. getValue(I.getArgOperand(1))));
  3805. return 0;
  3806. case Intrinsic::eh_unwind_init:
  3807. DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
  3808. return 0;
  3809. case Intrinsic::eh_dwarf_cfa: {
  3810. SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
  3811. TLI.getPointerTy());
  3812. SDValue Offset = DAG.getNode(ISD::ADD, dl,
  3813. TLI.getPointerTy(),
  3814. DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
  3815. TLI.getPointerTy()),
  3816. CfaArg);
  3817. SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
  3818. TLI.getPointerTy(),
  3819. DAG.getConstant(0, TLI.getPointerTy()));
  3820. setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
  3821. FA, Offset));
  3822. return 0;
  3823. }
  3824. case Intrinsic::eh_sjlj_callsite: {
  3825. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  3826. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
  3827. assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
  3828. assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
  3829. MMI.setCurrentCallSite(CI->getZExtValue());
  3830. return 0;
  3831. }
  3832. case Intrinsic::eh_sjlj_setjmp: {
  3833. setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(),
  3834. getValue(I.getArgOperand(0))));
  3835. return 0;
  3836. }
  3837. case Intrinsic::eh_sjlj_longjmp: {
  3838. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
  3839. getRoot(), getValue(I.getArgOperand(0))));
  3840. return 0;
  3841. }
  3842. case Intrinsic::eh_sjlj_dispatch_setup: {
  3843. DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
  3844. getRoot()));
  3845. return 0;
  3846. }
  3847. case Intrinsic::x86_mmx_pslli_w:
  3848. case Intrinsic::x86_mmx_pslli_d:
  3849. case Intrinsic::x86_mmx_pslli_q:
  3850. case Intrinsic::x86_mmx_psrli_w:
  3851. case Intrinsic::x86_mmx_psrli_d:
  3852. case Intrinsic::x86_mmx_psrli_q:
  3853. case Intrinsic::x86_mmx_psrai_w:
  3854. case Intrinsic::x86_mmx_psrai_d: {
  3855. SDValue ShAmt = getValue(I.getArgOperand(1));
  3856. if (isa<ConstantSDNode>(ShAmt)) {
  3857. visitTargetIntrinsic(I, Intrinsic);
  3858. return 0;
  3859. }
  3860. unsigned NewIntrinsic = 0;
  3861. EVT ShAmtVT = MVT::v2i32;
  3862. switch (Intrinsic) {
  3863. case Intrinsic::x86_mmx_pslli_w:
  3864. NewIntrinsic = Intrinsic::x86_mmx_psll_w;
  3865. break;
  3866. case Intrinsic::x86_mmx_pslli_d:
  3867. NewIntrinsic = Intrinsic::x86_mmx_psll_d;
  3868. break;
  3869. case Intrinsic::x86_mmx_pslli_q:
  3870. NewIntrinsic = Intrinsic::x86_mmx_psll_q;
  3871. break;
  3872. case Intrinsic::x86_mmx_psrli_w:
  3873. NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
  3874. break;
  3875. case Intrinsic::x86_mmx_psrli_d:
  3876. NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
  3877. break;
  3878. case Intrinsic::x86_mmx_psrli_q:
  3879. NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
  3880. break;
  3881. case Intrinsic::x86_mmx_psrai_w:
  3882. NewIntrinsic = Intrinsic::x86_mmx_psra_w;
  3883. break;
  3884. case Intrinsic::x86_mmx_psrai_d:
  3885. NewIntrinsic = Intrinsic::x86_mmx_psra_d;
  3886. break;
  3887. default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
  3888. }
  3889. // The vector shift intrinsics with scalars uses 32b shift amounts but
  3890. // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
  3891. // to be zero.
  3892. // We must do this early because v2i32 is not a legal type.
  3893. DebugLoc dl = getCurDebugLoc();
  3894. SDValue ShOps[2];
  3895. ShOps[0] = ShAmt;
  3896. ShOps[1] = DAG.getConstant(0, MVT::i32);
  3897. ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
  3898. EVT DestVT = TLI.getValueType(I.getType());
  3899. ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
  3900. Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
  3901. DAG.getConstant(NewIntrinsic, MVT::i32),
  3902. getValue(I.getArgOperand(0)), ShAmt);
  3903. setValue(&I, Res);
  3904. return 0;
  3905. }
  3906. case Intrinsic::convertff:
  3907. case Intrinsic::convertfsi:
  3908. case Intrinsic::convertfui:
  3909. case Intrinsic::convertsif:
  3910. case Intrinsic::convertuif:
  3911. case Intrinsic::convertss:
  3912. case Intrinsic::convertsu:
  3913. case Intrinsic::convertus:
  3914. case Intrinsic::convertuu: {
  3915. ISD::CvtCode Code = ISD::CVT_INVALID;
  3916. switch (Intrinsic) {
  3917. case Intrinsic::convertff: Code = ISD::CVT_FF; break;
  3918. case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
  3919. case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
  3920. case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
  3921. case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
  3922. case Intrinsic::convertss: Code = ISD::CVT_SS; break;
  3923. case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
  3924. case Intrinsic::convertus: Code = ISD::CVT_US; break;
  3925. case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
  3926. }
  3927. EVT DestVT = TLI.getValueType(I.getType());
  3928. const Value *Op1 = I.getArgOperand(0);
  3929. Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
  3930. DAG.getValueType(DestVT),
  3931. DAG.getValueType(getValue(Op1).getValueType()),
  3932. getValue(I.getArgOperand(1)),
  3933. getValue(I.getArgOperand(2)),
  3934. Code);
  3935. setValue(&I, Res);
  3936. return 0;
  3937. }
  3938. case Intrinsic::sqrt:
  3939. setValue(&I, DAG.getNode(ISD::FSQRT, dl,
  3940. getValue(I.getArgOperand(0)).getValueType(),
  3941. getValue(I.getArgOperand(0))));
  3942. return 0;
  3943. case Intrinsic::powi:
  3944. setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
  3945. getValue(I.getArgOperand(1)), DAG));
  3946. return 0;
  3947. case Intrinsic::sin:
  3948. setValue(&I, DAG.getNode(ISD::FSIN, dl,
  3949. getValue(I.getArgOperand(0)).getValueType(),
  3950. getValue(I.getArgOperand(0))));
  3951. return 0;
  3952. case Intrinsic::cos:
  3953. setValue(&I, DAG.getNode(ISD::FCOS, dl,
  3954. getValue(I.getArgOperand(0)).getValueType(),
  3955. getValue(I.getArgOperand(0))));
  3956. return 0;
  3957. case Intrinsic::log:
  3958. visitLog(I);
  3959. return 0;
  3960. case Intrinsic::log2:
  3961. visitLog2(I);
  3962. return 0;
  3963. case Intrinsic::log10:
  3964. visitLog10(I);
  3965. return 0;
  3966. case Intrinsic::exp:
  3967. visitExp(I);
  3968. return 0;
  3969. case Intrinsic::exp2:
  3970. visitExp2(I);
  3971. return 0;
  3972. case Intrinsic::pow:
  3973. visitPow(I);
  3974. return 0;
  3975. case Intrinsic::convert_to_fp16:
  3976. setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
  3977. MVT::i16, getValue(I.getArgOperand(0))));
  3978. return 0;
  3979. case Intrinsic::convert_from_fp16:
  3980. setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
  3981. MVT::f32, getValue(I.getArgOperand(0))));
  3982. return 0;
  3983. case Intrinsic::pcmarker: {
  3984. SDValue Tmp = getValue(I.getArgOperand(0));
  3985. DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
  3986. return 0;
  3987. }
  3988. case Intrinsic::readcyclecounter: {
  3989. SDValue Op = getRoot();
  3990. Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
  3991. DAG.getVTList(MVT::i64, MVT::Other),
  3992. &Op, 1);
  3993. setValue(&I, Res);
  3994. DAG.setRoot(Res.getValue(1));
  3995. return 0;
  3996. }
  3997. case Intrinsic::bswap:
  3998. setValue(&I, DAG.getNode(ISD::BSWAP, dl,
  3999. getValue(I.getArgOperand(0)).getValueType(),
  4000. getValue(I.getArgOperand(0))));
  4001. return 0;
  4002. case Intrinsic::cttz: {
  4003. SDValue Arg = getValue(I.getArgOperand(0));
  4004. EVT Ty = Arg.getValueType();
  4005. setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
  4006. return 0;
  4007. }
  4008. case Intrinsic::ctlz: {
  4009. SDValue Arg = getValue(I.getArgOperand(0));
  4010. EVT Ty = Arg.getValueType();
  4011. setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
  4012. return 0;
  4013. }
  4014. case Intrinsic::ctpop: {
  4015. SDValue Arg = getValue(I.getArgOperand(0));
  4016. EVT Ty = Arg.getValueType();
  4017. setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
  4018. return 0;
  4019. }
  4020. case Intrinsic::stacksave: {
  4021. SDValue Op = getRoot();
  4022. Res = DAG.getNode(ISD::STACKSAVE, dl,
  4023. DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
  4024. setValue(&I, Res);
  4025. DAG.setRoot(Res.getValue(1));
  4026. return 0;
  4027. }
  4028. case Intrinsic::stackrestore: {
  4029. Res = getValue(I.getArgOperand(0));
  4030. DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
  4031. return 0;
  4032. }
  4033. case Intrinsic::stackprotector: {
  4034. // Emit code into the DAG to store the stack guard onto the stack.
  4035. MachineFunction &MF = DAG.getMachineFunction();
  4036. MachineFrameInfo *MFI = MF.getFrameInfo();
  4037. EVT PtrTy = TLI.getPointerTy();
  4038. SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
  4039. AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
  4040. int FI = FuncInfo.StaticAllocaMap[Slot];
  4041. MFI->setStackProtectorIndex(FI);
  4042. SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
  4043. // Store the stack protector onto the stack.
  4044. Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
  4045. MachinePointerInfo::getFixedStack(FI),
  4046. true, false, 0);
  4047. setValue(&I, Res);
  4048. DAG.setRoot(Res);
  4049. return 0;
  4050. }
  4051. case Intrinsic::objectsize: {
  4052. // If we don't know by now, we're never going to know.
  4053. ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
  4054. assert(CI && "Non-constant type in __builtin_object_size?");
  4055. SDValue Arg = getValue(I.getCalledValue());
  4056. EVT Ty = Arg.getValueType();
  4057. if (CI->isZero())
  4058. Res = DAG.getConstant(-1ULL, Ty);
  4059. else
  4060. Res = DAG.getConstant(0, Ty);
  4061. setValue(&I, Res);
  4062. return 0;
  4063. }
  4064. case Intrinsic::var_annotation:
  4065. // Discard annotate attributes
  4066. return 0;
  4067. case Intrinsic::init_trampoline: {
  4068. const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
  4069. SDValue Ops[6];
  4070. Ops[0] = getRoot();
  4071. Ops[1] = getValue(I.getArgOperand(0));
  4072. Ops[2] = getValue(I.getArgOperand(1));
  4073. Ops[3] = getValue(I.getArgOperand(2));
  4074. Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
  4075. Ops[5] = DAG.getSrcValue(F);
  4076. Res = DAG.getNode(ISD::TRAMPOLINE, dl,
  4077. DAG.getVTList(TLI.getPointerTy(), MVT::Other),
  4078. Ops, 6);
  4079. setValue(&I, Res);
  4080. DAG.setRoot(Res.getValue(1));
  4081. return 0;
  4082. }
  4083. case Intrinsic::gcroot:
  4084. if (GFI) {
  4085. const Value *Alloca = I.getArgOperand(0);
  4086. const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
  4087. FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
  4088. GFI->addStackRoot(FI->getIndex(), TypeMap);
  4089. }
  4090. return 0;
  4091. case Intrinsic::gcread:
  4092. case Intrinsic::gcwrite:
  4093. llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
  4094. return 0;
  4095. case Intrinsic::flt_rounds:
  4096. setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
  4097. return 0;
  4098. case Intrinsic::trap: {
  4099. StringRef TrapFuncName = getTrapFunctionName();
  4100. if (TrapFuncName.empty()) {
  4101. DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
  4102. return 0;
  4103. }
  4104. TargetLowering::ArgListTy Args;
  4105. std::pair<SDValue, SDValue> Result =
  4106. TLI.LowerCallTo(getRoot(), I.getType(),
  4107. false, false, false, false, 0, CallingConv::C,
  4108. /*isTailCall=*/false, /*isReturnValueUsed=*/true,
  4109. DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
  4110. Args, DAG, getCurDebugLoc());
  4111. DAG.setRoot(Result.second);
  4112. return 0;
  4113. }
  4114. case Intrinsic::uadd_with_overflow:
  4115. return implVisitAluOverflow(I, ISD::UADDO);
  4116. case Intrinsic::sadd_with_overflow:
  4117. return implVisitAluOverflow(I, ISD::SADDO);
  4118. case Intrinsic::usub_with_overflow:
  4119. return implVisitAluOverflow(I, ISD::USUBO);
  4120. case Intrinsic::ssub_with_overflow:
  4121. return implVisitAluOverflow(I, ISD::SSUBO);
  4122. case Intrinsic::umul_with_overflow:
  4123. return implVisitAluOverflow(I, ISD::UMULO);
  4124. case Intrinsic::smul_with_overflow:
  4125. return implVisitAluOverflow(I, ISD::SMULO);
  4126. case Intrinsic::prefetch: {
  4127. SDValue Ops[4];
  4128. unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
  4129. Ops[0] = getRoot();
  4130. Ops[1] = getValue(I.getArgOperand(0));
  4131. Ops[2] = getValue(I.getArgOperand(1));
  4132. Ops[3] = getValue(I.getArgOperand(2));
  4133. DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
  4134. DAG.getVTList(MVT::Other),
  4135. &Ops[0], 4,
  4136. EVT::getIntegerVT(*Context, 8),
  4137. MachinePointerInfo(I.getArgOperand(0)),
  4138. 0, /* align */
  4139. false, /* volatile */
  4140. rw==0, /* read */
  4141. rw==1)); /* write */
  4142. return 0;
  4143. }
  4144. case Intrinsic::memory_barrier: {
  4145. SDValue Ops[6];
  4146. Ops[0] = getRoot();
  4147. for (int x = 1; x < 6; ++x)
  4148. Ops[x] = getValue(I.getArgOperand(x - 1));
  4149. DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
  4150. return 0;
  4151. }
  4152. case Intrinsic::atomic_cmp_swap: {
  4153. SDValue Root = getRoot();
  4154. SDValue L =
  4155. DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
  4156. getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
  4157. Root,
  4158. getValue(I.getArgOperand(0)),
  4159. getValue(I.getArgOperand(1)),
  4160. getValue(I.getArgOperand(2)),
  4161. MachinePointerInfo(I.getArgOperand(0)));
  4162. setValue(&I, L);
  4163. DAG.setRoot(L.getValue(1));
  4164. return 0;
  4165. }
  4166. case Intrinsic::atomic_load_add:
  4167. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
  4168. case Intrinsic::atomic_load_sub:
  4169. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
  4170. case Intrinsic::atomic_load_or:
  4171. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
  4172. case Intrinsic::atomic_load_xor:
  4173. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
  4174. case Intrinsic::atomic_load_and:
  4175. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
  4176. case Intrinsic::atomic_load_nand:
  4177. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
  4178. case Intrinsic::atomic_load_max:
  4179. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
  4180. case Intrinsic::atomic_load_min:
  4181. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
  4182. case Intrinsic::atomic_load_umin:
  4183. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
  4184. case Intrinsic::atomic_load_umax:
  4185. return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
  4186. case Intrinsic::atomic_swap:
  4187. return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
  4188. case Intrinsic::invariant_start:
  4189. case Intrinsic::lifetime_start:
  4190. // Discard region information.
  4191. setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
  4192. return 0;
  4193. case Intrinsic::invariant_end:
  4194. case Intrinsic::lifetime_end:
  4195. // Discard region information.
  4196. return 0;
  4197. }
  4198. }
  4199. void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
  4200. bool isTailCall,
  4201. MachineBasicBlock *LandingPad) {
  4202. const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
  4203. const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
  4204. const Type *RetTy = FTy->getReturnType();
  4205. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4206. MCSymbol *BeginLabel = 0;
  4207. TargetLowering::ArgListTy Args;
  4208. TargetLowering::ArgListEntry Entry;
  4209. Args.reserve(CS.arg_size());
  4210. // Check whether the function can return without sret-demotion.
  4211. SmallVector<ISD::OutputArg, 4> Outs;
  4212. SmallVector<uint64_t, 4> Offsets;
  4213. GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
  4214. Outs, TLI, &Offsets);
  4215. bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
  4216. FTy->isVarArg(), Outs, FTy->getContext());
  4217. SDValue DemoteStackSlot;
  4218. int DemoteStackIdx = -100;
  4219. if (!CanLowerReturn) {
  4220. uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
  4221. FTy->getReturnType());
  4222. unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
  4223. FTy->getReturnType());
  4224. MachineFunction &MF = DAG.getMachineFunction();
  4225. DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  4226. const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
  4227. DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
  4228. Entry.Node = DemoteStackSlot;
  4229. Entry.Ty = StackSlotPtrType;
  4230. Entry.isSExt = false;
  4231. Entry.isZExt = false;
  4232. Entry.isInReg = false;
  4233. Entry.isSRet = true;
  4234. Entry.isNest = false;
  4235. Entry.isByVal = false;
  4236. Entry.Alignment = Align;
  4237. Args.push_back(Entry);
  4238. RetTy = Type::getVoidTy(FTy->getContext());
  4239. }
  4240. for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
  4241. i != e; ++i) {
  4242. SDValue ArgNode = getValue(*i);
  4243. Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
  4244. unsigned attrInd = i - CS.arg_begin() + 1;
  4245. Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
  4246. Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
  4247. Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
  4248. Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
  4249. Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
  4250. Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
  4251. Entry.Alignment = CS.getParamAlignment(attrInd);
  4252. Args.push_back(Entry);
  4253. }
  4254. if (LandingPad) {
  4255. // Insert a label before the invoke call to mark the try range. This can be
  4256. // used to detect deletion of the invoke via the MachineModuleInfo.
  4257. BeginLabel = MMI.getContext().CreateTempSymbol();
  4258. // For SjLj, keep track of which landing pads go with which invokes
  4259. // so as to maintain the ordering of pads in the LSDA.
  4260. unsigned CallSiteIndex = MMI.getCurrentCallSite();
  4261. if (CallSiteIndex) {
  4262. MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
  4263. // Now that the call site is handled, stop tracking it.
  4264. MMI.setCurrentCallSite(0);
  4265. }
  4266. // Both PendingLoads and PendingExports must be flushed here;
  4267. // this call might not return.
  4268. (void)getRoot();
  4269. DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
  4270. }
  4271. // Check if target-independent constraints permit a tail call here.
  4272. // Target-dependent constraints are checked within TLI.LowerCallTo.
  4273. if (isTailCall &&
  4274. !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
  4275. isTailCall = false;
  4276. // If there's a possibility that fast-isel has already selected some amount
  4277. // of the current basic block, don't emit a tail call.
  4278. if (isTailCall && EnableFastISel)
  4279. isTailCall = false;
  4280. std::pair<SDValue,SDValue> Result =
  4281. TLI.LowerCallTo(getRoot(), RetTy,
  4282. CS.paramHasAttr(0, Attribute::SExt),
  4283. CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
  4284. CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
  4285. CS.getCallingConv(),
  4286. isTailCall,
  4287. !CS.getInstruction()->use_empty(),
  4288. Callee, Args, DAG, getCurDebugLoc());
  4289. assert((isTailCall || Result.second.getNode()) &&
  4290. "Non-null chain expected with non-tail call!");
  4291. assert((Result.second.getNode() || !Result.first.getNode()) &&
  4292. "Null value expected with tail call!");
  4293. if (Result.first.getNode()) {
  4294. setValue(CS.getInstruction(), Result.first);
  4295. } else if (!CanLowerReturn && Result.second.getNode()) {
  4296. // The instruction result is the result of loading from the
  4297. // hidden sret parameter.
  4298. SmallVector<EVT, 1> PVTs;
  4299. const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
  4300. ComputeValueVTs(TLI, PtrRetTy, PVTs);
  4301. assert(PVTs.size() == 1 && "Pointers should fit in one register");
  4302. EVT PtrVT = PVTs[0];
  4303. unsigned NumValues = Outs.size();
  4304. SmallVector<SDValue, 4> Values(NumValues);
  4305. SmallVector<SDValue, 4> Chains(NumValues);
  4306. for (unsigned i = 0; i < NumValues; ++i) {
  4307. SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
  4308. DemoteStackSlot,
  4309. DAG.getConstant(Offsets[i], PtrVT));
  4310. SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second,
  4311. Add,
  4312. MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
  4313. false, false, 1);
  4314. Values[i] = L;
  4315. Chains[i] = L.getValue(1);
  4316. }
  4317. SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
  4318. MVT::Other, &Chains[0], NumValues);
  4319. PendingLoads.push_back(Chain);
  4320. // Collect the legal value parts into potentially illegal values
  4321. // that correspond to the original function's return values.
  4322. SmallVector<EVT, 4> RetTys;
  4323. RetTy = FTy->getReturnType();
  4324. ComputeValueVTs(TLI, RetTy, RetTys);
  4325. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  4326. SmallVector<SDValue, 4> ReturnValues;
  4327. unsigned CurReg = 0;
  4328. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  4329. EVT VT = RetTys[I];
  4330. EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
  4331. unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
  4332. SDValue ReturnValue =
  4333. getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
  4334. RegisterVT, VT, AssertOp);
  4335. ReturnValues.push_back(ReturnValue);
  4336. CurReg += NumRegs;
  4337. }
  4338. setValue(CS.getInstruction(),
  4339. DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
  4340. DAG.getVTList(&RetTys[0], RetTys.size()),
  4341. &ReturnValues[0], ReturnValues.size()));
  4342. }
  4343. // Assign order to nodes here. If the call does not produce a result, it won't
  4344. // be mapped to a SDNode and visit() will not assign it an order number.
  4345. if (!Result.second.getNode()) {
  4346. // As a special case, a null chain means that a tail call has been emitted and
  4347. // the DAG root is already updated.
  4348. HasTailCall = true;
  4349. ++SDNodeOrder;
  4350. AssignOrderingToNode(DAG.getRoot().getNode());
  4351. } else {
  4352. DAG.setRoot(Result.second);
  4353. ++SDNodeOrder;
  4354. AssignOrderingToNode(Result.second.getNode());
  4355. }
  4356. if (LandingPad) {
  4357. // Insert a label at the end of the invoke call to mark the try range. This
  4358. // can be used to detect deletion of the invoke via the MachineModuleInfo.
  4359. MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
  4360. DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
  4361. // Inform MachineModuleInfo of range.
  4362. MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
  4363. }
  4364. }
  4365. /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
  4366. /// value is equal or not-equal to zero.
  4367. static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
  4368. for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
  4369. UI != E; ++UI) {
  4370. if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
  4371. if (IC->isEquality())
  4372. if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  4373. if (C->isNullValue())
  4374. continue;
  4375. // Unknown instruction.
  4376. return false;
  4377. }
  4378. return true;
  4379. }
  4380. static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
  4381. const Type *LoadTy,
  4382. SelectionDAGBuilder &Builder) {
  4383. // Check to see if this load can be trivially constant folded, e.g. if the
  4384. // input is from a string literal.
  4385. if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
  4386. // Cast pointer to the type we really want to load.
  4387. LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
  4388. PointerType::getUnqual(LoadTy));
  4389. if (const Constant *LoadCst =
  4390. ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
  4391. Builder.TD))
  4392. return Builder.getValue(LoadCst);
  4393. }
  4394. // Otherwise, we have to emit the load. If the pointer is to unfoldable but
  4395. // still constant memory, the input chain can be the entry node.
  4396. SDValue Root;
  4397. bool ConstantMemory = false;
  4398. // Do not serialize (non-volatile) loads of constant memory with anything.
  4399. if (Builder.AA->pointsToConstantMemory(PtrVal)) {
  4400. Root = Builder.DAG.getEntryNode();
  4401. ConstantMemory = true;
  4402. } else {
  4403. // Do not serialize non-volatile loads against each other.
  4404. Root = Builder.DAG.getRoot();
  4405. }
  4406. SDValue Ptr = Builder.getValue(PtrVal);
  4407. SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
  4408. Ptr, MachinePointerInfo(PtrVal),
  4409. false /*volatile*/,
  4410. false /*nontemporal*/, 1 /* align=1 */);
  4411. if (!ConstantMemory)
  4412. Builder.PendingLoads.push_back(LoadVal.getValue(1));
  4413. return LoadVal;
  4414. }
  4415. /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
  4416. /// If so, return true and lower it, otherwise return false and it will be
  4417. /// lowered like a normal call.
  4418. bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
  4419. // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
  4420. if (I.getNumArgOperands() != 3)
  4421. return false;
  4422. const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
  4423. if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
  4424. !I.getArgOperand(2)->getType()->isIntegerTy() ||
  4425. !I.getType()->isIntegerTy())
  4426. return false;
  4427. const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
  4428. // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
  4429. // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
  4430. if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
  4431. bool ActuallyDoIt = true;
  4432. MVT LoadVT;
  4433. const Type *LoadTy;
  4434. switch (Size->getZExtValue()) {
  4435. default:
  4436. LoadVT = MVT::Other;
  4437. LoadTy = 0;
  4438. ActuallyDoIt = false;
  4439. break;
  4440. case 2:
  4441. LoadVT = MVT::i16;
  4442. LoadTy = Type::getInt16Ty(Size->getContext());
  4443. break;
  4444. case 4:
  4445. LoadVT = MVT::i32;
  4446. LoadTy = Type::getInt32Ty(Size->getContext());
  4447. break;
  4448. case 8:
  4449. LoadVT = MVT::i64;
  4450. LoadTy = Type::getInt64Ty(Size->getContext());
  4451. break;
  4452. /*
  4453. case 16:
  4454. LoadVT = MVT::v4i32;
  4455. LoadTy = Type::getInt32Ty(Size->getContext());
  4456. LoadTy = VectorType::get(LoadTy, 4);
  4457. break;
  4458. */
  4459. }
  4460. // This turns into unaligned loads. We only do this if the target natively
  4461. // supports the MVT we'll be loading or if it is small enough (<= 4) that
  4462. // we'll only produce a small number of byte loads.
  4463. // Require that we can find a legal MVT, and only do this if the target
  4464. // supports unaligned loads of that type. Expanding into byte loads would
  4465. // bloat the code.
  4466. if (ActuallyDoIt && Size->getZExtValue() > 4) {
  4467. // TODO: Handle 5 byte compare as 4-byte + 1 byte.
  4468. // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
  4469. if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
  4470. ActuallyDoIt = false;
  4471. }
  4472. if (ActuallyDoIt) {
  4473. SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
  4474. SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
  4475. SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
  4476. ISD::SETNE);
  4477. EVT CallVT = TLI.getValueType(I.getType(), true);
  4478. setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
  4479. return true;
  4480. }
  4481. }
  4482. return false;
  4483. }
  4484. void SelectionDAGBuilder::visitCall(const CallInst &I) {
  4485. // Handle inline assembly differently.
  4486. if (isa<InlineAsm>(I.getCalledValue())) {
  4487. visitInlineAsm(&I);
  4488. return;
  4489. }
  4490. // See if any floating point values are being passed to this function. This is
  4491. // used to emit an undefined reference to fltused on Windows.
  4492. const FunctionType *FT =
  4493. cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
  4494. MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
  4495. if (FT->isVarArg() &&
  4496. !MMI.callsExternalVAFunctionWithFloatingPointArguments()) {
  4497. for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
  4498. const Type* T = I.getArgOperand(i)->getType();
  4499. for (po_iterator<const Type*> i = po_begin(T), e = po_end(T);
  4500. i != e; ++i) {
  4501. if (!i->isFloatingPointTy()) continue;
  4502. MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true);
  4503. break;
  4504. }
  4505. }
  4506. }
  4507. const char *RenameFn = 0;
  4508. if (Function *F = I.getCalledFunction()) {
  4509. if (F->isDeclaration()) {
  4510. if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
  4511. if (unsigned IID = II->getIntrinsicID(F)) {
  4512. RenameFn = visitIntrinsicCall(I, IID);
  4513. if (!RenameFn)
  4514. return;
  4515. }
  4516. }
  4517. if (unsigned IID = F->getIntrinsicID()) {
  4518. RenameFn = visitIntrinsicCall(I, IID);
  4519. if (!RenameFn)
  4520. return;
  4521. }
  4522. }
  4523. // Check for well-known libc/libm calls. If the function is internal, it
  4524. // can't be a library call.
  4525. if (!F->hasLocalLinkage() && F->hasName()) {
  4526. StringRef Name = F->getName();
  4527. if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
  4528. if (I.getNumArgOperands() == 2 && // Basic sanity checks.
  4529. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  4530. I.getType() == I.getArgOperand(0)->getType() &&
  4531. I.getType() == I.getArgOperand(1)->getType()) {
  4532. SDValue LHS = getValue(I.getArgOperand(0));
  4533. SDValue RHS = getValue(I.getArgOperand(1));
  4534. setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
  4535. LHS.getValueType(), LHS, RHS));
  4536. return;
  4537. }
  4538. } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
  4539. if (I.getNumArgOperands() == 1 && // Basic sanity checks.
  4540. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  4541. I.getType() == I.getArgOperand(0)->getType()) {
  4542. SDValue Tmp = getValue(I.getArgOperand(0));
  4543. setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
  4544. Tmp.getValueType(), Tmp));
  4545. return;
  4546. }
  4547. } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
  4548. if (I.getNumArgOperands() == 1 && // Basic sanity checks.
  4549. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  4550. I.getType() == I.getArgOperand(0)->getType() &&
  4551. I.onlyReadsMemory()) {
  4552. SDValue Tmp = getValue(I.getArgOperand(0));
  4553. setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
  4554. Tmp.getValueType(), Tmp));
  4555. return;
  4556. }
  4557. } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
  4558. if (I.getNumArgOperands() == 1 && // Basic sanity checks.
  4559. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  4560. I.getType() == I.getArgOperand(0)->getType() &&
  4561. I.onlyReadsMemory()) {
  4562. SDValue Tmp = getValue(I.getArgOperand(0));
  4563. setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
  4564. Tmp.getValueType(), Tmp));
  4565. return;
  4566. }
  4567. } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
  4568. if (I.getNumArgOperands() == 1 && // Basic sanity checks.
  4569. I.getArgOperand(0)->getType()->isFloatingPointTy() &&
  4570. I.getType() == I.getArgOperand(0)->getType() &&
  4571. I.onlyReadsMemory()) {
  4572. SDValue Tmp = getValue(I.getArgOperand(0));
  4573. setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
  4574. Tmp.getValueType(), Tmp));
  4575. return;
  4576. }
  4577. } else if (Name == "memcmp") {
  4578. if (visitMemCmpCall(I))
  4579. return;
  4580. }
  4581. }
  4582. }
  4583. SDValue Callee;
  4584. if (!RenameFn)
  4585. Callee = getValue(I.getCalledValue());
  4586. else
  4587. Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
  4588. // Check if we can potentially perform a tail call. More detailed checking is
  4589. // be done within LowerCallTo, after more information about the call is known.
  4590. LowerCallTo(&I, Callee, I.isTailCall());
  4591. }
  4592. namespace {
  4593. /// AsmOperandInfo - This contains information for each constraint that we are
  4594. /// lowering.
  4595. class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
  4596. public:
  4597. /// CallOperand - If this is the result output operand or a clobber
  4598. /// this is null, otherwise it is the incoming operand to the CallInst.
  4599. /// This gets modified as the asm is processed.
  4600. SDValue CallOperand;
  4601. /// AssignedRegs - If this is a register or register class operand, this
  4602. /// contains the set of register corresponding to the operand.
  4603. RegsForValue AssignedRegs;
  4604. explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
  4605. : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
  4606. }
  4607. /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
  4608. /// busy in OutputRegs/InputRegs.
  4609. void MarkAllocatedRegs(bool isOutReg, bool isInReg,
  4610. std::set<unsigned> &OutputRegs,
  4611. std::set<unsigned> &InputRegs,
  4612. const TargetRegisterInfo &TRI) const {
  4613. if (isOutReg) {
  4614. for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
  4615. MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
  4616. }
  4617. if (isInReg) {
  4618. for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
  4619. MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
  4620. }
  4621. }
  4622. /// getCallOperandValEVT - Return the EVT of the Value* that this operand
  4623. /// corresponds to. If there is no Value* for this operand, it returns
  4624. /// MVT::Other.
  4625. EVT getCallOperandValEVT(LLVMContext &Context,
  4626. const TargetLowering &TLI,
  4627. const TargetData *TD) const {
  4628. if (CallOperandVal == 0) return MVT::Other;
  4629. if (isa<BasicBlock>(CallOperandVal))
  4630. return TLI.getPointerTy();
  4631. const llvm::Type *OpTy = CallOperandVal->getType();
  4632. // If this is an indirect operand, the operand is a pointer to the
  4633. // accessed type.
  4634. if (isIndirect) {
  4635. const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
  4636. if (!PtrTy)
  4637. report_fatal_error("Indirect operand for inline asm not a pointer!");
  4638. OpTy = PtrTy->getElementType();
  4639. }
  4640. // If OpTy is not a single value, it may be a struct/union that we
  4641. // can tile with integers.
  4642. if (!OpTy->isSingleValueType() && OpTy->isSized()) {
  4643. unsigned BitSize = TD->getTypeSizeInBits(OpTy);
  4644. switch (BitSize) {
  4645. default: break;
  4646. case 1:
  4647. case 8:
  4648. case 16:
  4649. case 32:
  4650. case 64:
  4651. case 128:
  4652. OpTy = IntegerType::get(Context, BitSize);
  4653. break;
  4654. }
  4655. }
  4656. return TLI.getValueType(OpTy, true);
  4657. }
  4658. private:
  4659. /// MarkRegAndAliases - Mark the specified register and all aliases in the
  4660. /// specified set.
  4661. static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
  4662. const TargetRegisterInfo &TRI) {
  4663. assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
  4664. Regs.insert(Reg);
  4665. if (const unsigned *Aliases = TRI.getAliasSet(Reg))
  4666. for (; *Aliases; ++Aliases)
  4667. Regs.insert(*Aliases);
  4668. }
  4669. };
  4670. typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
  4671. } // end anonymous namespace
  4672. /// isAllocatableRegister - If the specified register is safe to allocate,
  4673. /// i.e. it isn't a stack pointer or some other special register, return the
  4674. /// register class for the register. Otherwise, return null.
  4675. static const TargetRegisterClass *
  4676. isAllocatableRegister(unsigned Reg, MachineFunction &MF,
  4677. const TargetLowering &TLI,
  4678. const TargetRegisterInfo *TRI) {
  4679. EVT FoundVT = MVT::Other;
  4680. const TargetRegisterClass *FoundRC = 0;
  4681. for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
  4682. E = TRI->regclass_end(); RCI != E; ++RCI) {
  4683. EVT ThisVT = MVT::Other;
  4684. const TargetRegisterClass *RC = *RCI;
  4685. // If none of the value types for this register class are valid, we
  4686. // can't use it. For example, 64-bit reg classes on 32-bit targets.
  4687. for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
  4688. I != E; ++I) {
  4689. if (TLI.isTypeLegal(*I)) {
  4690. // If we have already found this register in a different register class,
  4691. // choose the one with the largest VT specified. For example, on
  4692. // PowerPC, we favor f64 register classes over f32.
  4693. if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
  4694. ThisVT = *I;
  4695. break;
  4696. }
  4697. }
  4698. }
  4699. if (ThisVT == MVT::Other) continue;
  4700. // NOTE: This isn't ideal. In particular, this might allocate the
  4701. // frame pointer in functions that need it (due to them not being taken
  4702. // out of allocation, because a variable sized allocation hasn't been seen
  4703. // yet). This is a slight code pessimization, but should still work.
  4704. for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
  4705. E = RC->allocation_order_end(MF); I != E; ++I)
  4706. if (*I == Reg) {
  4707. // We found a matching register class. Keep looking at others in case
  4708. // we find one with larger registers that this physreg is also in.
  4709. FoundRC = RC;
  4710. FoundVT = ThisVT;
  4711. break;
  4712. }
  4713. }
  4714. return FoundRC;
  4715. }
  4716. /// GetRegistersForValue - Assign registers (virtual or physical) for the
  4717. /// specified operand. We prefer to assign virtual registers, to allow the
  4718. /// register allocator to handle the assignment process. However, if the asm
  4719. /// uses features that we can't model on machineinstrs, we have SDISel do the
  4720. /// allocation. This produces generally horrible, but correct, code.
  4721. ///
  4722. /// OpInfo describes the operand.
  4723. /// Input and OutputRegs are the set of already allocated physical registers.
  4724. ///
  4725. static void GetRegistersForValue(SelectionDAG &DAG,
  4726. const TargetLowering &TLI,
  4727. DebugLoc DL,
  4728. SDISelAsmOperandInfo &OpInfo,
  4729. std::set<unsigned> &OutputRegs,
  4730. std::set<unsigned> &InputRegs) {
  4731. LLVMContext &Context = *DAG.getContext();
  4732. // Compute whether this value requires an input register, an output register,
  4733. // or both.
  4734. bool isOutReg = false;
  4735. bool isInReg = false;
  4736. switch (OpInfo.Type) {
  4737. case InlineAsm::isOutput:
  4738. isOutReg = true;
  4739. // If there is an input constraint that matches this, we need to reserve
  4740. // the input register so no other inputs allocate to it.
  4741. isInReg = OpInfo.hasMatchingInput();
  4742. break;
  4743. case InlineAsm::isInput:
  4744. isInReg = true;
  4745. isOutReg = false;
  4746. break;
  4747. case InlineAsm::isClobber:
  4748. isOutReg = true;
  4749. isInReg = true;
  4750. break;
  4751. }
  4752. MachineFunction &MF = DAG.getMachineFunction();
  4753. SmallVector<unsigned, 4> Regs;
  4754. // If this is a constraint for a single physreg, or a constraint for a
  4755. // register class, find it.
  4756. std::pair<unsigned, const TargetRegisterClass*> PhysReg =
  4757. TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
  4758. OpInfo.ConstraintVT);
  4759. unsigned NumRegs = 1;
  4760. if (OpInfo.ConstraintVT != MVT::Other) {
  4761. // If this is a FP input in an integer register (or visa versa) insert a bit
  4762. // cast of the input value. More generally, handle any case where the input
  4763. // value disagrees with the register class we plan to stick this in.
  4764. if (OpInfo.Type == InlineAsm::isInput &&
  4765. PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
  4766. // Try to convert to the first EVT that the reg class contains. If the
  4767. // types are identical size, use a bitcast to convert (e.g. two differing
  4768. // vector types).
  4769. EVT RegVT = *PhysReg.second->vt_begin();
  4770. if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
  4771. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  4772. RegVT, OpInfo.CallOperand);
  4773. OpInfo.ConstraintVT = RegVT;
  4774. } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
  4775. // If the input is a FP value and we want it in FP registers, do a
  4776. // bitcast to the corresponding integer type. This turns an f64 value
  4777. // into i64, which can be passed with two i32 values on a 32-bit
  4778. // machine.
  4779. RegVT = EVT::getIntegerVT(Context,
  4780. OpInfo.ConstraintVT.getSizeInBits());
  4781. OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
  4782. RegVT, OpInfo.CallOperand);
  4783. OpInfo.ConstraintVT = RegVT;
  4784. }
  4785. }
  4786. NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
  4787. }
  4788. EVT RegVT;
  4789. EVT ValueVT = OpInfo.ConstraintVT;
  4790. // If this is a constraint for a specific physical register, like {r17},
  4791. // assign it now.
  4792. if (unsigned AssignedReg = PhysReg.first) {
  4793. const TargetRegisterClass *RC = PhysReg.second;
  4794. if (OpInfo.ConstraintVT == MVT::Other)
  4795. ValueVT = *RC->vt_begin();
  4796. // Get the actual register value type. This is important, because the user
  4797. // may have asked for (e.g.) the AX register in i32 type. We need to
  4798. // remember that AX is actually i16 to get the right extension.
  4799. RegVT = *RC->vt_begin();
  4800. // This is a explicit reference to a physical register.
  4801. Regs.push_back(AssignedReg);
  4802. // If this is an expanded reference, add the rest of the regs to Regs.
  4803. if (NumRegs != 1) {
  4804. TargetRegisterClass::iterator I = RC->begin();
  4805. for (; *I != AssignedReg; ++I)
  4806. assert(I != RC->end() && "Didn't find reg!");
  4807. // Already added the first reg.
  4808. --NumRegs; ++I;
  4809. for (; NumRegs; --NumRegs, ++I) {
  4810. assert(I != RC->end() && "Ran out of registers to allocate!");
  4811. Regs.push_back(*I);
  4812. }
  4813. }
  4814. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  4815. const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
  4816. OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
  4817. return;
  4818. }
  4819. // Otherwise, if this was a reference to an LLVM register class, create vregs
  4820. // for this reference.
  4821. if (const TargetRegisterClass *RC = PhysReg.second) {
  4822. RegVT = *RC->vt_begin();
  4823. if (OpInfo.ConstraintVT == MVT::Other)
  4824. ValueVT = RegVT;
  4825. // Create the appropriate number of virtual registers.
  4826. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  4827. for (; NumRegs; --NumRegs)
  4828. Regs.push_back(RegInfo.createVirtualRegister(RC));
  4829. OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
  4830. return;
  4831. }
  4832. // This is a reference to a register class that doesn't directly correspond
  4833. // to an LLVM register class. Allocate NumRegs consecutive, available,
  4834. // registers from the class.
  4835. std::vector<unsigned> RegClassRegs
  4836. = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
  4837. OpInfo.ConstraintVT);
  4838. const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
  4839. unsigned NumAllocated = 0;
  4840. for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
  4841. unsigned Reg = RegClassRegs[i];
  4842. // See if this register is available.
  4843. if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
  4844. (isInReg && InputRegs.count(Reg))) { // Already used.
  4845. // Make sure we find consecutive registers.
  4846. NumAllocated = 0;
  4847. continue;
  4848. }
  4849. // Check to see if this register is allocatable (i.e. don't give out the
  4850. // stack pointer).
  4851. const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
  4852. if (!RC) { // Couldn't allocate this register.
  4853. // Reset NumAllocated to make sure we return consecutive registers.
  4854. NumAllocated = 0;
  4855. continue;
  4856. }
  4857. // Okay, this register is good, we can use it.
  4858. ++NumAllocated;
  4859. // If we allocated enough consecutive registers, succeed.
  4860. if (NumAllocated == NumRegs) {
  4861. unsigned RegStart = (i-NumAllocated)+1;
  4862. unsigned RegEnd = i+1;
  4863. // Mark all of the allocated registers used.
  4864. for (unsigned i = RegStart; i != RegEnd; ++i)
  4865. Regs.push_back(RegClassRegs[i]);
  4866. OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
  4867. OpInfo.ConstraintVT);
  4868. OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
  4869. return;
  4870. }
  4871. }
  4872. // Otherwise, we couldn't allocate enough registers for this.
  4873. }
  4874. /// visitInlineAsm - Handle a call to an InlineAsm object.
  4875. ///
  4876. void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
  4877. const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
  4878. /// ConstraintOperands - Information about all of the constraints.
  4879. SDISelAsmOperandInfoVector ConstraintOperands;
  4880. std::set<unsigned> OutputRegs, InputRegs;
  4881. TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(CS);
  4882. bool hasMemory = false;
  4883. unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
  4884. unsigned ResNo = 0; // ResNo - The result number of the next output.
  4885. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  4886. ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
  4887. SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
  4888. EVT OpVT = MVT::Other;
  4889. // Compute the value type for each operand.
  4890. switch (OpInfo.Type) {
  4891. case InlineAsm::isOutput:
  4892. // Indirect outputs just consume an argument.
  4893. if (OpInfo.isIndirect) {
  4894. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  4895. break;
  4896. }
  4897. // The return value of the call is this value. As such, there is no
  4898. // corresponding argument.
  4899. assert(!CS.getType()->isVoidTy() &&
  4900. "Bad inline asm!");
  4901. if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
  4902. OpVT = TLI.getValueType(STy->getElementType(ResNo));
  4903. } else {
  4904. assert(ResNo == 0 && "Asm only has one result!");
  4905. OpVT = TLI.getValueType(CS.getType());
  4906. }
  4907. ++ResNo;
  4908. break;
  4909. case InlineAsm::isInput:
  4910. OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
  4911. break;
  4912. case InlineAsm::isClobber:
  4913. // Nothing to do.
  4914. break;
  4915. }
  4916. // If this is an input or an indirect output, process the call argument.
  4917. // BasicBlocks are labels, currently appearing only in asm's.
  4918. if (OpInfo.CallOperandVal) {
  4919. if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
  4920. OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
  4921. } else {
  4922. OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
  4923. }
  4924. OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
  4925. }
  4926. OpInfo.ConstraintVT = OpVT;
  4927. // Indirect operand accesses access memory.
  4928. if (OpInfo.isIndirect)
  4929. hasMemory = true;
  4930. else {
  4931. for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
  4932. TargetLowering::ConstraintType CType = TLI.getConstraintType(OpInfo.Codes[j]);
  4933. if (CType == TargetLowering::C_Memory) {
  4934. hasMemory = true;
  4935. break;
  4936. }
  4937. }
  4938. }
  4939. }
  4940. SDValue Chain, Flag;
  4941. // We won't need to flush pending loads if this asm doesn't touch
  4942. // memory and is nonvolatile.
  4943. if (hasMemory || IA->hasSideEffects())
  4944. Chain = getRoot();
  4945. else
  4946. Chain = DAG.getRoot();
  4947. // Second pass over the constraints: compute which constraint option to use
  4948. // and assign registers to constraints that want a specific physreg.
  4949. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  4950. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  4951. // If this is an output operand with a matching input operand, look up the
  4952. // matching input. If their types mismatch, e.g. one is an integer, the
  4953. // other is floating point, or their sizes are different, flag it as an
  4954. // error.
  4955. if (OpInfo.hasMatchingInput()) {
  4956. SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
  4957. if (OpInfo.ConstraintVT != Input.ConstraintVT) {
  4958. if ((OpInfo.ConstraintVT.isInteger() !=
  4959. Input.ConstraintVT.isInteger()) ||
  4960. (OpInfo.ConstraintVT.getSizeInBits() !=
  4961. Input.ConstraintVT.getSizeInBits())) {
  4962. report_fatal_error("Unsupported asm: input constraint"
  4963. " with a matching output constraint of"
  4964. " incompatible type!");
  4965. }
  4966. Input.ConstraintVT = OpInfo.ConstraintVT;
  4967. }
  4968. }
  4969. // Compute the constraint code and ConstraintType to use.
  4970. TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
  4971. // If this is a memory input, and if the operand is not indirect, do what we
  4972. // need to to provide an address for the memory input.
  4973. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  4974. !OpInfo.isIndirect) {
  4975. assert((OpInfo.isMultipleAlternative || (OpInfo.Type == InlineAsm::isInput)) &&
  4976. "Can only indirectify direct input operands!");
  4977. // Memory operands really want the address of the value. If we don't have
  4978. // an indirect input, put it in the constpool if we can, otherwise spill
  4979. // it to a stack slot.
  4980. // If the operand is a float, integer, or vector constant, spill to a
  4981. // constant pool entry to get its address.
  4982. const Value *OpVal = OpInfo.CallOperandVal;
  4983. if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
  4984. isa<ConstantVector>(OpVal)) {
  4985. OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
  4986. TLI.getPointerTy());
  4987. } else {
  4988. // Otherwise, create a stack slot and emit a store to it before the
  4989. // asm.
  4990. const Type *Ty = OpVal->getType();
  4991. uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
  4992. unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
  4993. MachineFunction &MF = DAG.getMachineFunction();
  4994. int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
  4995. SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
  4996. Chain = DAG.getStore(Chain, getCurDebugLoc(),
  4997. OpInfo.CallOperand, StackSlot,
  4998. MachinePointerInfo::getFixedStack(SSFI),
  4999. false, false, 0);
  5000. OpInfo.CallOperand = StackSlot;
  5001. }
  5002. // There is no longer a Value* corresponding to this operand.
  5003. OpInfo.CallOperandVal = 0;
  5004. // It is now an indirect operand.
  5005. OpInfo.isIndirect = true;
  5006. }
  5007. // If this constraint is for a specific register, allocate it before
  5008. // anything else.
  5009. if (OpInfo.ConstraintType == TargetLowering::C_Register)
  5010. GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
  5011. InputRegs);
  5012. }
  5013. // Second pass - Loop over all of the operands, assigning virtual or physregs
  5014. // to register class operands.
  5015. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5016. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5017. // C_Register operands have already been allocated, Other/Memory don't need
  5018. // to be.
  5019. if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
  5020. GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
  5021. InputRegs);
  5022. }
  5023. // AsmNodeOperands - The operands for the ISD::INLINEASM node.
  5024. std::vector<SDValue> AsmNodeOperands;
  5025. AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
  5026. AsmNodeOperands.push_back(
  5027. DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
  5028. TLI.getPointerTy()));
  5029. // If we have a !srcloc metadata node associated with it, we want to attach
  5030. // this to the ultimately generated inline asm machineinstr. To do this, we
  5031. // pass in the third operand as this (potentially null) inline asm MDNode.
  5032. const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
  5033. AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
  5034. // Remember the HasSideEffect and AlignStack bits as operand 3.
  5035. unsigned ExtraInfo = 0;
  5036. if (IA->hasSideEffects())
  5037. ExtraInfo |= InlineAsm::Extra_HasSideEffects;
  5038. if (IA->isAlignStack())
  5039. ExtraInfo |= InlineAsm::Extra_IsAlignStack;
  5040. AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
  5041. TLI.getPointerTy()));
  5042. // Loop over all of the inputs, copying the operand values into the
  5043. // appropriate registers and processing the output regs.
  5044. RegsForValue RetValRegs;
  5045. // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
  5046. std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
  5047. for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
  5048. SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
  5049. switch (OpInfo.Type) {
  5050. case InlineAsm::isOutput: {
  5051. if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
  5052. OpInfo.ConstraintType != TargetLowering::C_Register) {
  5053. // Memory output, or 'other' output (e.g. 'X' constraint).
  5054. assert(OpInfo.isIndirect && "Memory output must be indirect operand");
  5055. // Add information to the INLINEASM node to know about this output.
  5056. unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5057. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
  5058. TLI.getPointerTy()));
  5059. AsmNodeOperands.push_back(OpInfo.CallOperand);
  5060. break;
  5061. }
  5062. // Otherwise, this is a register or register class output.
  5063. // Copy the output from the appropriate register. Find a register that
  5064. // we can use.
  5065. if (OpInfo.AssignedRegs.Regs.empty())
  5066. report_fatal_error("Couldn't allocate output reg for constraint '" +
  5067. Twine(OpInfo.ConstraintCode) + "'!");
  5068. // If this is an indirect operand, store through the pointer after the
  5069. // asm.
  5070. if (OpInfo.isIndirect) {
  5071. IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
  5072. OpInfo.CallOperandVal));
  5073. } else {
  5074. // This is the result value of the call.
  5075. assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
  5076. // Concatenate this output onto the outputs list.
  5077. RetValRegs.append(OpInfo.AssignedRegs);
  5078. }
  5079. // Add information to the INLINEASM node to know that this register is
  5080. // set.
  5081. OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
  5082. InlineAsm::Kind_RegDefEarlyClobber :
  5083. InlineAsm::Kind_RegDef,
  5084. false,
  5085. 0,
  5086. DAG,
  5087. AsmNodeOperands);
  5088. break;
  5089. }
  5090. case InlineAsm::isInput: {
  5091. SDValue InOperandVal = OpInfo.CallOperand;
  5092. if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
  5093. // If this is required to match an output register we have already set,
  5094. // just use its register.
  5095. unsigned OperandNo = OpInfo.getMatchedOperand();
  5096. // Scan until we find the definition we already emitted of this operand.
  5097. // When we find it, create a RegsForValue operand.
  5098. unsigned CurOp = InlineAsm::Op_FirstOperand;
  5099. for (; OperandNo; --OperandNo) {
  5100. // Advance to the next operand.
  5101. unsigned OpFlag =
  5102. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5103. assert((InlineAsm::isRegDefKind(OpFlag) ||
  5104. InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
  5105. InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
  5106. CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
  5107. }
  5108. unsigned OpFlag =
  5109. cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
  5110. if (InlineAsm::isRegDefKind(OpFlag) ||
  5111. InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
  5112. // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
  5113. if (OpInfo.isIndirect) {
  5114. // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
  5115. LLVMContext &Ctx = *DAG.getContext();
  5116. Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
  5117. " don't know how to handle tied "
  5118. "indirect register inputs");
  5119. }
  5120. RegsForValue MatchedRegs;
  5121. MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
  5122. EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
  5123. MatchedRegs.RegVTs.push_back(RegVT);
  5124. MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
  5125. for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
  5126. i != e; ++i)
  5127. MatchedRegs.Regs.push_back
  5128. (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
  5129. // Use the produced MatchedRegs object to
  5130. MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
  5131. Chain, &Flag);
  5132. MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
  5133. true, OpInfo.getMatchedOperand(),
  5134. DAG, AsmNodeOperands);
  5135. break;
  5136. }
  5137. assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
  5138. assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
  5139. "Unexpected number of operands");
  5140. // Add information to the INLINEASM node to know about this input.
  5141. // See InlineAsm.h isUseOperandTiedToDef.
  5142. OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
  5143. OpInfo.getMatchedOperand());
  5144. AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
  5145. TLI.getPointerTy()));
  5146. AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
  5147. break;
  5148. }
  5149. // Treat indirect 'X' constraint as memory.
  5150. if (OpInfo.ConstraintType == TargetLowering::C_Other &&
  5151. OpInfo.isIndirect)
  5152. OpInfo.ConstraintType = TargetLowering::C_Memory;
  5153. if (OpInfo.ConstraintType == TargetLowering::C_Other) {
  5154. std::vector<SDValue> Ops;
  5155. TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
  5156. Ops, DAG);
  5157. if (Ops.empty())
  5158. report_fatal_error("Invalid operand for inline asm constraint '" +
  5159. Twine(OpInfo.ConstraintCode) + "'!");
  5160. // Add information to the INLINEASM node to know about this input.
  5161. unsigned ResOpType =
  5162. InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
  5163. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5164. TLI.getPointerTy()));
  5165. AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
  5166. break;
  5167. }
  5168. if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
  5169. assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
  5170. assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
  5171. "Memory operands expect pointer values");
  5172. // Add information to the INLINEASM node to know about this input.
  5173. unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
  5174. AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
  5175. TLI.getPointerTy()));
  5176. AsmNodeOperands.push_back(InOperandVal);
  5177. break;
  5178. }
  5179. assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
  5180. OpInfo.ConstraintType == TargetLowering::C_Register) &&
  5181. "Unknown constraint type!");
  5182. assert(!OpInfo.isIndirect &&
  5183. "Don't know how to handle indirect register inputs yet!");
  5184. // Copy the input into the appropriate registers.
  5185. if (OpInfo.AssignedRegs.Regs.empty() ||
  5186. !OpInfo.AssignedRegs.areValueTypesLegal(TLI))
  5187. report_fatal_error("Couldn't allocate input reg for constraint '" +
  5188. Twine(OpInfo.ConstraintCode) + "'!");
  5189. OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
  5190. Chain, &Flag);
  5191. OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
  5192. DAG, AsmNodeOperands);
  5193. break;
  5194. }
  5195. case InlineAsm::isClobber: {
  5196. // Add the clobbered value to the operand list, so that the register
  5197. // allocator is aware that the physreg got clobbered.
  5198. if (!OpInfo.AssignedRegs.Regs.empty())
  5199. OpInfo.AssignedRegs.AddInlineAsmOperands(
  5200. InlineAsm::Kind_RegDefEarlyClobber,
  5201. false, 0, DAG,
  5202. AsmNodeOperands);
  5203. break;
  5204. }
  5205. }
  5206. }
  5207. // Finish up input operands. Set the input chain and add the flag last.
  5208. AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
  5209. if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
  5210. Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
  5211. DAG.getVTList(MVT::Other, MVT::Glue),
  5212. &AsmNodeOperands[0], AsmNodeOperands.size());
  5213. Flag = Chain.getValue(1);
  5214. // If this asm returns a register value, copy the result from that register
  5215. // and set it as the value of the call.
  5216. if (!RetValRegs.Regs.empty()) {
  5217. SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
  5218. Chain, &Flag);
  5219. // FIXME: Why don't we do this for inline asms with MRVs?
  5220. if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
  5221. EVT ResultType = TLI.getValueType(CS.getType());
  5222. // If any of the results of the inline asm is a vector, it may have the
  5223. // wrong width/num elts. This can happen for register classes that can
  5224. // contain multiple different value types. The preg or vreg allocated may
  5225. // not have the same VT as was expected. Convert it to the right type
  5226. // with bit_convert.
  5227. if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
  5228. Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
  5229. ResultType, Val);
  5230. } else if (ResultType != Val.getValueType() &&
  5231. ResultType.isInteger() && Val.getValueType().isInteger()) {
  5232. // If a result value was tied to an input value, the computed result may
  5233. // have a wider width than the expected result. Extract the relevant
  5234. // portion.
  5235. Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
  5236. }
  5237. assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
  5238. }
  5239. setValue(CS.getInstruction(), Val);
  5240. // Don't need to use this as a chain in this case.
  5241. if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
  5242. return;
  5243. }
  5244. std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
  5245. // Process indirect outputs, first output all of the flagged copies out of
  5246. // physregs.
  5247. for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
  5248. RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
  5249. const Value *Ptr = IndirectStoresToEmit[i].second;
  5250. SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
  5251. Chain, &Flag);
  5252. StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
  5253. }
  5254. // Emit the non-flagged stores from the physregs.
  5255. SmallVector<SDValue, 8> OutChains;
  5256. for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
  5257. SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
  5258. StoresToEmit[i].first,
  5259. getValue(StoresToEmit[i].second),
  5260. MachinePointerInfo(StoresToEmit[i].second),
  5261. false, false, 0);
  5262. OutChains.push_back(Val);
  5263. }
  5264. if (!OutChains.empty())
  5265. Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
  5266. &OutChains[0], OutChains.size());
  5267. DAG.setRoot(Chain);
  5268. }
  5269. void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
  5270. DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
  5271. MVT::Other, getRoot(),
  5272. getValue(I.getArgOperand(0)),
  5273. DAG.getSrcValue(I.getArgOperand(0))));
  5274. }
  5275. void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
  5276. const TargetData &TD = *TLI.getTargetData();
  5277. SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
  5278. getRoot(), getValue(I.getOperand(0)),
  5279. DAG.getSrcValue(I.getOperand(0)),
  5280. TD.getABITypeAlignment(I.getType()));
  5281. setValue(&I, V);
  5282. DAG.setRoot(V.getValue(1));
  5283. }
  5284. void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
  5285. DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
  5286. MVT::Other, getRoot(),
  5287. getValue(I.getArgOperand(0)),
  5288. DAG.getSrcValue(I.getArgOperand(0))));
  5289. }
  5290. void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
  5291. DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
  5292. MVT::Other, getRoot(),
  5293. getValue(I.getArgOperand(0)),
  5294. getValue(I.getArgOperand(1)),
  5295. DAG.getSrcValue(I.getArgOperand(0)),
  5296. DAG.getSrcValue(I.getArgOperand(1))));
  5297. }
  5298. /// TargetLowering::LowerCallTo - This is the default LowerCallTo
  5299. /// implementation, which just calls LowerCall.
  5300. /// FIXME: When all targets are
  5301. /// migrated to using LowerCall, this hook should be integrated into SDISel.
  5302. std::pair<SDValue, SDValue>
  5303. TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
  5304. bool RetSExt, bool RetZExt, bool isVarArg,
  5305. bool isInreg, unsigned NumFixedArgs,
  5306. CallingConv::ID CallConv, bool isTailCall,
  5307. bool isReturnValueUsed,
  5308. SDValue Callee,
  5309. ArgListTy &Args, SelectionDAG &DAG,
  5310. DebugLoc dl) const {
  5311. // Handle all of the outgoing arguments.
  5312. SmallVector<ISD::OutputArg, 32> Outs;
  5313. SmallVector<SDValue, 32> OutVals;
  5314. for (unsigned i = 0, e = Args.size(); i != e; ++i) {
  5315. SmallVector<EVT, 4> ValueVTs;
  5316. ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
  5317. for (unsigned Value = 0, NumValues = ValueVTs.size();
  5318. Value != NumValues; ++Value) {
  5319. EVT VT = ValueVTs[Value];
  5320. const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
  5321. SDValue Op = SDValue(Args[i].Node.getNode(),
  5322. Args[i].Node.getResNo() + Value);
  5323. ISD::ArgFlagsTy Flags;
  5324. unsigned OriginalAlignment =
  5325. getTargetData()->getABITypeAlignment(ArgTy);
  5326. if (Args[i].isZExt)
  5327. Flags.setZExt();
  5328. if (Args[i].isSExt)
  5329. Flags.setSExt();
  5330. if (Args[i].isInReg)
  5331. Flags.setInReg();
  5332. if (Args[i].isSRet)
  5333. Flags.setSRet();
  5334. if (Args[i].isByVal) {
  5335. Flags.setByVal();
  5336. const PointerType *Ty = cast<PointerType>(Args[i].Ty);
  5337. const Type *ElementTy = Ty->getElementType();
  5338. unsigned FrameAlign = getByValTypeAlignment(ElementTy);
  5339. unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
  5340. // For ByVal, alignment should come from FE. BE will guess if this
  5341. // info is not there but there are cases it cannot get right.
  5342. if (Args[i].Alignment)
  5343. FrameAlign = Args[i].Alignment;
  5344. Flags.setByValAlign(FrameAlign);
  5345. Flags.setByValSize(FrameSize);
  5346. }
  5347. if (Args[i].isNest)
  5348. Flags.setNest();
  5349. Flags.setOrigAlign(OriginalAlignment);
  5350. EVT PartVT = getRegisterType(RetTy->getContext(), VT);
  5351. unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
  5352. SmallVector<SDValue, 4> Parts(NumParts);
  5353. ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
  5354. if (Args[i].isSExt)
  5355. ExtendKind = ISD::SIGN_EXTEND;
  5356. else if (Args[i].isZExt)
  5357. ExtendKind = ISD::ZERO_EXTEND;
  5358. getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
  5359. PartVT, ExtendKind);
  5360. for (unsigned j = 0; j != NumParts; ++j) {
  5361. // if it isn't first piece, alignment must be 1
  5362. ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
  5363. i < NumFixedArgs);
  5364. if (NumParts > 1 && j == 0)
  5365. MyFlags.Flags.setSplit();
  5366. else if (j != 0)
  5367. MyFlags.Flags.setOrigAlign(1);
  5368. Outs.push_back(MyFlags);
  5369. OutVals.push_back(Parts[j]);
  5370. }
  5371. }
  5372. }
  5373. // Handle the incoming return values from the call.
  5374. SmallVector<ISD::InputArg, 32> Ins;
  5375. SmallVector<EVT, 4> RetTys;
  5376. ComputeValueVTs(*this, RetTy, RetTys);
  5377. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  5378. EVT VT = RetTys[I];
  5379. EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
  5380. unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
  5381. for (unsigned i = 0; i != NumRegs; ++i) {
  5382. ISD::InputArg MyFlags;
  5383. MyFlags.VT = RegisterVT.getSimpleVT();
  5384. MyFlags.Used = isReturnValueUsed;
  5385. if (RetSExt)
  5386. MyFlags.Flags.setSExt();
  5387. if (RetZExt)
  5388. MyFlags.Flags.setZExt();
  5389. if (isInreg)
  5390. MyFlags.Flags.setInReg();
  5391. Ins.push_back(MyFlags);
  5392. }
  5393. }
  5394. SmallVector<SDValue, 4> InVals;
  5395. Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
  5396. Outs, OutVals, Ins, dl, DAG, InVals);
  5397. // Verify that the target's LowerCall behaved as expected.
  5398. assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
  5399. "LowerCall didn't return a valid chain!");
  5400. assert((!isTailCall || InVals.empty()) &&
  5401. "LowerCall emitted a return value for a tail call!");
  5402. assert((isTailCall || InVals.size() == Ins.size()) &&
  5403. "LowerCall didn't emit the correct number of values!");
  5404. // For a tail call, the return value is merely live-out and there aren't
  5405. // any nodes in the DAG representing it. Return a special value to
  5406. // indicate that a tail call has been emitted and no more Instructions
  5407. // should be processed in the current block.
  5408. if (isTailCall) {
  5409. DAG.setRoot(Chain);
  5410. return std::make_pair(SDValue(), SDValue());
  5411. }
  5412. DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  5413. assert(InVals[i].getNode() &&
  5414. "LowerCall emitted a null value!");
  5415. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  5416. "LowerCall emitted a value with the wrong type!");
  5417. });
  5418. // Collect the legal value parts into potentially illegal values
  5419. // that correspond to the original function's return values.
  5420. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  5421. if (RetSExt)
  5422. AssertOp = ISD::AssertSext;
  5423. else if (RetZExt)
  5424. AssertOp = ISD::AssertZext;
  5425. SmallVector<SDValue, 4> ReturnValues;
  5426. unsigned CurReg = 0;
  5427. for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
  5428. EVT VT = RetTys[I];
  5429. EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
  5430. unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
  5431. ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
  5432. NumRegs, RegisterVT, VT,
  5433. AssertOp));
  5434. CurReg += NumRegs;
  5435. }
  5436. // For a function returning void, there is no return value. We can't create
  5437. // such a node, so we just return a null return value in that case. In
  5438. // that case, nothing will actually look at the value.
  5439. if (ReturnValues.empty())
  5440. return std::make_pair(SDValue(), Chain);
  5441. SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
  5442. DAG.getVTList(&RetTys[0], RetTys.size()),
  5443. &ReturnValues[0], ReturnValues.size());
  5444. return std::make_pair(Res, Chain);
  5445. }
  5446. void TargetLowering::LowerOperationWrapper(SDNode *N,
  5447. SmallVectorImpl<SDValue> &Results,
  5448. SelectionDAG &DAG) const {
  5449. SDValue Res = LowerOperation(SDValue(N, 0), DAG);
  5450. if (Res.getNode())
  5451. Results.push_back(Res);
  5452. }
  5453. SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
  5454. llvm_unreachable("LowerOperation not implemented for this target!");
  5455. return SDValue();
  5456. }
  5457. void
  5458. SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
  5459. SDValue Op = getNonRegisterValue(V);
  5460. assert((Op.getOpcode() != ISD::CopyFromReg ||
  5461. cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
  5462. "Copy from a reg to the same reg!");
  5463. assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
  5464. RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
  5465. SDValue Chain = DAG.getEntryNode();
  5466. RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
  5467. PendingExports.push_back(Chain);
  5468. }
  5469. #include "llvm/CodeGen/SelectionDAGISel.h"
  5470. void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
  5471. // If this is the entry block, emit arguments.
  5472. const Function &F = *LLVMBB->getParent();
  5473. SelectionDAG &DAG = SDB->DAG;
  5474. DebugLoc dl = SDB->getCurDebugLoc();
  5475. const TargetData *TD = TLI.getTargetData();
  5476. SmallVector<ISD::InputArg, 16> Ins;
  5477. // Check whether the function can return without sret-demotion.
  5478. SmallVector<ISD::OutputArg, 4> Outs;
  5479. GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
  5480. Outs, TLI);
  5481. if (!FuncInfo->CanLowerReturn) {
  5482. // Put in an sret pointer parameter before all the other parameters.
  5483. SmallVector<EVT, 1> ValueVTs;
  5484. ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
  5485. // NOTE: Assuming that a pointer will never break down to more than one VT
  5486. // or one register.
  5487. ISD::ArgFlagsTy Flags;
  5488. Flags.setSRet();
  5489. EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
  5490. ISD::InputArg RetArg(Flags, RegisterVT, true);
  5491. Ins.push_back(RetArg);
  5492. }
  5493. // Set up the incoming argument description vector.
  5494. unsigned Idx = 1;
  5495. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
  5496. I != E; ++I, ++Idx) {
  5497. SmallVector<EVT, 4> ValueVTs;
  5498. ComputeValueVTs(TLI, I->getType(), ValueVTs);
  5499. bool isArgValueUsed = !I->use_empty();
  5500. for (unsigned Value = 0, NumValues = ValueVTs.size();
  5501. Value != NumValues; ++Value) {
  5502. EVT VT = ValueVTs[Value];
  5503. const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  5504. ISD::ArgFlagsTy Flags;
  5505. unsigned OriginalAlignment =
  5506. TD->getABITypeAlignment(ArgTy);
  5507. if (F.paramHasAttr(Idx, Attribute::ZExt))
  5508. Flags.setZExt();
  5509. if (F.paramHasAttr(Idx, Attribute::SExt))
  5510. Flags.setSExt();
  5511. if (F.paramHasAttr(Idx, Attribute::InReg))
  5512. Flags.setInReg();
  5513. if (F.paramHasAttr(Idx, Attribute::StructRet))
  5514. Flags.setSRet();
  5515. if (F.paramHasAttr(Idx, Attribute::ByVal)) {
  5516. Flags.setByVal();
  5517. const PointerType *Ty = cast<PointerType>(I->getType());
  5518. const Type *ElementTy = Ty->getElementType();
  5519. unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
  5520. unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
  5521. // For ByVal, alignment should be passed from FE. BE will guess if
  5522. // this info is not there but there are cases it cannot get right.
  5523. if (F.getParamAlignment(Idx))
  5524. FrameAlign = F.getParamAlignment(Idx);
  5525. Flags.setByValAlign(FrameAlign);
  5526. Flags.setByValSize(FrameSize);
  5527. }
  5528. if (F.paramHasAttr(Idx, Attribute::Nest))
  5529. Flags.setNest();
  5530. Flags.setOrigAlign(OriginalAlignment);
  5531. EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
  5532. unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
  5533. for (unsigned i = 0; i != NumRegs; ++i) {
  5534. ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
  5535. if (NumRegs > 1 && i == 0)
  5536. MyFlags.Flags.setSplit();
  5537. // if it isn't first piece, alignment must be 1
  5538. else if (i > 0)
  5539. MyFlags.Flags.setOrigAlign(1);
  5540. Ins.push_back(MyFlags);
  5541. }
  5542. }
  5543. }
  5544. // Call the target to set up the argument values.
  5545. SmallVector<SDValue, 8> InVals;
  5546. SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
  5547. F.isVarArg(), Ins,
  5548. dl, DAG, InVals);
  5549. // Verify that the target's LowerFormalArguments behaved as expected.
  5550. assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
  5551. "LowerFormalArguments didn't return a valid chain!");
  5552. assert(InVals.size() == Ins.size() &&
  5553. "LowerFormalArguments didn't emit the correct number of values!");
  5554. DEBUG({
  5555. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  5556. assert(InVals[i].getNode() &&
  5557. "LowerFormalArguments emitted a null value!");
  5558. assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
  5559. "LowerFormalArguments emitted a value with the wrong type!");
  5560. }
  5561. });
  5562. // Update the DAG with the new chain value resulting from argument lowering.
  5563. DAG.setRoot(NewRoot);
  5564. // Set up the argument values.
  5565. unsigned i = 0;
  5566. Idx = 1;
  5567. if (!FuncInfo->CanLowerReturn) {
  5568. // Create a virtual register for the sret pointer, and put in a copy
  5569. // from the sret argument into it.
  5570. SmallVector<EVT, 1> ValueVTs;
  5571. ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
  5572. EVT VT = ValueVTs[0];
  5573. EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
  5574. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  5575. SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
  5576. RegVT, VT, AssertOp);
  5577. MachineFunction& MF = SDB->DAG.getMachineFunction();
  5578. MachineRegisterInfo& RegInfo = MF.getRegInfo();
  5579. unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
  5580. FuncInfo->DemoteRegister = SRetReg;
  5581. NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
  5582. SRetReg, ArgValue);
  5583. DAG.setRoot(NewRoot);
  5584. // i indexes lowered arguments. Bump it past the hidden sret argument.
  5585. // Idx indexes LLVM arguments. Don't touch it.
  5586. ++i;
  5587. }
  5588. for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
  5589. ++I, ++Idx) {
  5590. SmallVector<SDValue, 4> ArgValues;
  5591. SmallVector<EVT, 4> ValueVTs;
  5592. ComputeValueVTs(TLI, I->getType(), ValueVTs);
  5593. unsigned NumValues = ValueVTs.size();
  5594. // If this argument is unused then remember its value. It is used to generate
  5595. // debugging information.
  5596. if (I->use_empty() && NumValues)
  5597. SDB->setUnusedArgValue(I, InVals[i]);
  5598. for (unsigned Value = 0; Value != NumValues; ++Value) {
  5599. EVT VT = ValueVTs[Value];
  5600. EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
  5601. unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
  5602. if (!I->use_empty()) {
  5603. ISD::NodeType AssertOp = ISD::DELETED_NODE;
  5604. if (F.paramHasAttr(Idx, Attribute::SExt))
  5605. AssertOp = ISD::AssertSext;
  5606. else if (F.paramHasAttr(Idx, Attribute::ZExt))
  5607. AssertOp = ISD::AssertZext;
  5608. ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
  5609. NumParts, PartVT, VT,
  5610. AssertOp));
  5611. }
  5612. i += NumParts;
  5613. }
  5614. // Note down frame index for byval arguments.
  5615. if (I->hasByValAttr() && !ArgValues.empty())
  5616. if (FrameIndexSDNode *FI =
  5617. dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
  5618. FuncInfo->setByValArgumentFrameIndex(I, FI->getIndex());
  5619. if (!I->use_empty()) {
  5620. SDValue Res;
  5621. if (!ArgValues.empty())
  5622. Res = DAG.getMergeValues(&ArgValues[0], NumValues,
  5623. SDB->getCurDebugLoc());
  5624. SDB->setValue(I, Res);
  5625. // If this argument is live outside of the entry block, insert a copy from
  5626. // wherever we got it to the vreg that other BB's will reference it as.
  5627. SDB->CopyToExportRegsIfNeeded(I);
  5628. }
  5629. }
  5630. assert(i == InVals.size() && "Argument register count mismatch!");
  5631. // Finally, if the target has anything special to do, allow it to do so.
  5632. // FIXME: this should insert code into the DAG!
  5633. EmitFunctionEntryCode();
  5634. }
  5635. /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
  5636. /// ensure constants are generated when needed. Remember the virtual registers
  5637. /// that need to be added to the Machine PHI nodes as input. We cannot just
  5638. /// directly add them, because expansion might result in multiple MBB's for one
  5639. /// BB. As such, the start of the BB might correspond to a different MBB than
  5640. /// the end.
  5641. ///
  5642. void
  5643. SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
  5644. const TerminatorInst *TI = LLVMBB->getTerminator();
  5645. SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
  5646. // Check successor nodes' PHI nodes that expect a constant to be available
  5647. // from this block.
  5648. for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
  5649. const BasicBlock *SuccBB = TI->getSuccessor(succ);
  5650. if (!isa<PHINode>(SuccBB->begin())) continue;
  5651. MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
  5652. // If this terminator has multiple identical successors (common for
  5653. // switches), only handle each succ once.
  5654. if (!SuccsHandled.insert(SuccMBB)) continue;
  5655. MachineBasicBlock::iterator MBBI = SuccMBB->begin();
  5656. // At this point we know that there is a 1-1 correspondence between LLVM PHI
  5657. // nodes and Machine PHI nodes, but the incoming operands have not been
  5658. // emitted yet.
  5659. for (BasicBlock::const_iterator I = SuccBB->begin();
  5660. const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  5661. // Ignore dead phi's.
  5662. if (PN->use_empty()) continue;
  5663. unsigned Reg;
  5664. const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
  5665. if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
  5666. unsigned &RegOut = ConstantsOut[C];
  5667. if (RegOut == 0) {
  5668. RegOut = FuncInfo.CreateRegs(C->getType());
  5669. CopyValueToVirtualRegister(C, RegOut);
  5670. }
  5671. Reg = RegOut;
  5672. } else {
  5673. DenseMap<const Value *, unsigned>::iterator I =
  5674. FuncInfo.ValueMap.find(PHIOp);
  5675. if (I != FuncInfo.ValueMap.end())
  5676. Reg = I->second;
  5677. else {
  5678. assert(isa<AllocaInst>(PHIOp) &&
  5679. FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
  5680. "Didn't codegen value into a register!??");
  5681. Reg = FuncInfo.CreateRegs(PHIOp->getType());
  5682. CopyValueToVirtualRegister(PHIOp, Reg);
  5683. }
  5684. }
  5685. // Remember that this register needs to added to the machine PHI node as
  5686. // the input for this MBB.
  5687. SmallVector<EVT, 4> ValueVTs;
  5688. ComputeValueVTs(TLI, PN->getType(), ValueVTs);
  5689. for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
  5690. EVT VT = ValueVTs[vti];
  5691. unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
  5692. for (unsigned i = 0, e = NumRegisters; i != e; ++i)
  5693. FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
  5694. Reg += NumRegisters;
  5695. }
  5696. }
  5697. }
  5698. ConstantsOut.clear();
  5699. }