SelectionDAGBuild.cpp 233 KB

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