SelectionDAG.cpp 209 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802
  1. //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
  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 the SelectionDAG class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/SelectionDAG.h"
  14. #include "llvm/Constants.h"
  15. #include "llvm/Analysis/ValueTracking.h"
  16. #include "llvm/GlobalAlias.h"
  17. #include "llvm/GlobalVariable.h"
  18. #include "llvm/Intrinsics.h"
  19. #include "llvm/DerivedTypes.h"
  20. #include "llvm/Assembly/Writer.h"
  21. #include "llvm/CallingConv.h"
  22. #include "llvm/CodeGen/MachineBasicBlock.h"
  23. #include "llvm/CodeGen/MachineConstantPool.h"
  24. #include "llvm/CodeGen/MachineFrameInfo.h"
  25. #include "llvm/CodeGen/MachineModuleInfo.h"
  26. #include "llvm/CodeGen/PseudoSourceValue.h"
  27. #include "llvm/Target/TargetRegisterInfo.h"
  28. #include "llvm/Target/TargetData.h"
  29. #include "llvm/Target/TargetLowering.h"
  30. #include "llvm/Target/TargetOptions.h"
  31. #include "llvm/Target/TargetInstrInfo.h"
  32. #include "llvm/Target/TargetMachine.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/ManagedStatic.h"
  36. #include "llvm/Support/MathExtras.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/System/Mutex.h"
  39. #include "llvm/ADT/SetVector.h"
  40. #include "llvm/ADT/SmallPtrSet.h"
  41. #include "llvm/ADT/SmallSet.h"
  42. #include "llvm/ADT/SmallVector.h"
  43. #include "llvm/ADT/StringExtras.h"
  44. #include <algorithm>
  45. #include <cmath>
  46. using namespace llvm;
  47. /// makeVTList - Return an instance of the SDVTList struct initialized with the
  48. /// specified members.
  49. static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
  50. SDVTList Res = {VTs, NumVTs};
  51. return Res;
  52. }
  53. static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
  54. switch (VT.getSimpleVT()) {
  55. default: LLVM_UNREACHABLE("Unknown FP format");
  56. case MVT::f32: return &APFloat::IEEEsingle;
  57. case MVT::f64: return &APFloat::IEEEdouble;
  58. case MVT::f80: return &APFloat::x87DoubleExtended;
  59. case MVT::f128: return &APFloat::IEEEquad;
  60. case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
  61. }
  62. }
  63. SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
  64. //===----------------------------------------------------------------------===//
  65. // ConstantFPSDNode Class
  66. //===----------------------------------------------------------------------===//
  67. /// isExactlyValue - We don't rely on operator== working on double values, as
  68. /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
  69. /// As such, this method can be used to do an exact bit-for-bit comparison of
  70. /// two floating point values.
  71. bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
  72. return getValueAPF().bitwiseIsEqual(V);
  73. }
  74. bool ConstantFPSDNode::isValueValidForType(MVT VT,
  75. const APFloat& Val) {
  76. assert(VT.isFloatingPoint() && "Can only convert between FP types");
  77. // PPC long double cannot be converted to any other type.
  78. if (VT == MVT::ppcf128 ||
  79. &Val.getSemantics() == &APFloat::PPCDoubleDouble)
  80. return false;
  81. // convert modifies in place, so make a copy.
  82. APFloat Val2 = APFloat(Val);
  83. bool losesInfo;
  84. (void) Val2.convert(*MVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
  85. &losesInfo);
  86. return !losesInfo;
  87. }
  88. //===----------------------------------------------------------------------===//
  89. // ISD Namespace
  90. //===----------------------------------------------------------------------===//
  91. /// isBuildVectorAllOnes - Return true if the specified node is a
  92. /// BUILD_VECTOR where all of the elements are ~0 or undef.
  93. bool ISD::isBuildVectorAllOnes(const SDNode *N) {
  94. // Look through a bit convert.
  95. if (N->getOpcode() == ISD::BIT_CONVERT)
  96. N = N->getOperand(0).getNode();
  97. if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
  98. unsigned i = 0, e = N->getNumOperands();
  99. // Skip over all of the undef values.
  100. while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
  101. ++i;
  102. // Do not accept an all-undef vector.
  103. if (i == e) return false;
  104. // Do not accept build_vectors that aren't all constants or which have non-~0
  105. // elements.
  106. SDValue NotZero = N->getOperand(i);
  107. if (isa<ConstantSDNode>(NotZero)) {
  108. if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
  109. return false;
  110. } else if (isa<ConstantFPSDNode>(NotZero)) {
  111. if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
  112. bitcastToAPInt().isAllOnesValue())
  113. return false;
  114. } else
  115. return false;
  116. // Okay, we have at least one ~0 value, check to see if the rest match or are
  117. // undefs.
  118. for (++i; i != e; ++i)
  119. if (N->getOperand(i) != NotZero &&
  120. N->getOperand(i).getOpcode() != ISD::UNDEF)
  121. return false;
  122. return true;
  123. }
  124. /// isBuildVectorAllZeros - Return true if the specified node is a
  125. /// BUILD_VECTOR where all of the elements are 0 or undef.
  126. bool ISD::isBuildVectorAllZeros(const SDNode *N) {
  127. // Look through a bit convert.
  128. if (N->getOpcode() == ISD::BIT_CONVERT)
  129. N = N->getOperand(0).getNode();
  130. if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
  131. unsigned i = 0, e = N->getNumOperands();
  132. // Skip over all of the undef values.
  133. while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
  134. ++i;
  135. // Do not accept an all-undef vector.
  136. if (i == e) return false;
  137. // Do not accept build_vectors that aren't all constants or which have non-0
  138. // elements.
  139. SDValue Zero = N->getOperand(i);
  140. if (isa<ConstantSDNode>(Zero)) {
  141. if (!cast<ConstantSDNode>(Zero)->isNullValue())
  142. return false;
  143. } else if (isa<ConstantFPSDNode>(Zero)) {
  144. if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
  145. return false;
  146. } else
  147. return false;
  148. // Okay, we have at least one 0 value, check to see if the rest match or are
  149. // undefs.
  150. for (++i; i != e; ++i)
  151. if (N->getOperand(i) != Zero &&
  152. N->getOperand(i).getOpcode() != ISD::UNDEF)
  153. return false;
  154. return true;
  155. }
  156. /// isScalarToVector - Return true if the specified node is a
  157. /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
  158. /// element is not an undef.
  159. bool ISD::isScalarToVector(const SDNode *N) {
  160. if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
  161. return true;
  162. if (N->getOpcode() != ISD::BUILD_VECTOR)
  163. return false;
  164. if (N->getOperand(0).getOpcode() == ISD::UNDEF)
  165. return false;
  166. unsigned NumElems = N->getNumOperands();
  167. for (unsigned i = 1; i < NumElems; ++i) {
  168. SDValue V = N->getOperand(i);
  169. if (V.getOpcode() != ISD::UNDEF)
  170. return false;
  171. }
  172. return true;
  173. }
  174. /// isDebugLabel - Return true if the specified node represents a debug
  175. /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
  176. bool ISD::isDebugLabel(const SDNode *N) {
  177. SDValue Zero;
  178. if (N->getOpcode() == ISD::DBG_LABEL)
  179. return true;
  180. if (N->isMachineOpcode() &&
  181. N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
  182. return true;
  183. return false;
  184. }
  185. /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
  186. /// when given the operation for (X op Y).
  187. ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
  188. // To perform this operation, we just need to swap the L and G bits of the
  189. // operation.
  190. unsigned OldL = (Operation >> 2) & 1;
  191. unsigned OldG = (Operation >> 1) & 1;
  192. return ISD::CondCode((Operation & ~6) | // Keep the N, U, E bits
  193. (OldL << 1) | // New G bit
  194. (OldG << 2)); // New L bit.
  195. }
  196. /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
  197. /// 'op' is a valid SetCC operation.
  198. ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
  199. unsigned Operation = Op;
  200. if (isInteger)
  201. Operation ^= 7; // Flip L, G, E bits, but not U.
  202. else
  203. Operation ^= 15; // Flip all of the condition bits.
  204. if (Operation > ISD::SETTRUE2)
  205. Operation &= ~8; // Don't let N and U bits get set.
  206. return ISD::CondCode(Operation);
  207. }
  208. /// isSignedOp - For an integer comparison, return 1 if the comparison is a
  209. /// signed operation and 2 if the result is an unsigned comparison. Return zero
  210. /// if the operation does not depend on the sign of the input (setne and seteq).
  211. static int isSignedOp(ISD::CondCode Opcode) {
  212. switch (Opcode) {
  213. default: LLVM_UNREACHABLE("Illegal integer setcc operation!");
  214. case ISD::SETEQ:
  215. case ISD::SETNE: return 0;
  216. case ISD::SETLT:
  217. case ISD::SETLE:
  218. case ISD::SETGT:
  219. case ISD::SETGE: return 1;
  220. case ISD::SETULT:
  221. case ISD::SETULE:
  222. case ISD::SETUGT:
  223. case ISD::SETUGE: return 2;
  224. }
  225. }
  226. /// getSetCCOrOperation - Return the result of a logical OR between different
  227. /// comparisons of identical values: ((X op1 Y) | (X op2 Y)). This function
  228. /// returns SETCC_INVALID if it is not possible to represent the resultant
  229. /// comparison.
  230. ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
  231. bool isInteger) {
  232. if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
  233. // Cannot fold a signed integer setcc with an unsigned integer setcc.
  234. return ISD::SETCC_INVALID;
  235. unsigned Op = Op1 | Op2; // Combine all of the condition bits.
  236. // If the N and U bits get set then the resultant comparison DOES suddenly
  237. // care about orderedness, and is true when ordered.
  238. if (Op > ISD::SETTRUE2)
  239. Op &= ~16; // Clear the U bit if the N bit is set.
  240. // Canonicalize illegal integer setcc's.
  241. if (isInteger && Op == ISD::SETUNE) // e.g. SETUGT | SETULT
  242. Op = ISD::SETNE;
  243. return ISD::CondCode(Op);
  244. }
  245. /// getSetCCAndOperation - Return the result of a logical AND between different
  246. /// comparisons of identical values: ((X op1 Y) & (X op2 Y)). This
  247. /// function returns zero if it is not possible to represent the resultant
  248. /// comparison.
  249. ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
  250. bool isInteger) {
  251. if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
  252. // Cannot fold a signed setcc with an unsigned setcc.
  253. return ISD::SETCC_INVALID;
  254. // Combine all of the condition bits.
  255. ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
  256. // Canonicalize illegal integer setcc's.
  257. if (isInteger) {
  258. switch (Result) {
  259. default: break;
  260. case ISD::SETUO : Result = ISD::SETFALSE; break; // SETUGT & SETULT
  261. case ISD::SETOEQ: // SETEQ & SETU[LG]E
  262. case ISD::SETUEQ: Result = ISD::SETEQ ; break; // SETUGE & SETULE
  263. case ISD::SETOLT: Result = ISD::SETULT ; break; // SETULT & SETNE
  264. case ISD::SETOGT: Result = ISD::SETUGT ; break; // SETUGT & SETNE
  265. }
  266. }
  267. return Result;
  268. }
  269. const TargetMachine &SelectionDAG::getTarget() const {
  270. return MF->getTarget();
  271. }
  272. //===----------------------------------------------------------------------===//
  273. // SDNode Profile Support
  274. //===----------------------------------------------------------------------===//
  275. /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
  276. ///
  277. static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC) {
  278. ID.AddInteger(OpC);
  279. }
  280. /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
  281. /// solely with their pointer.
  282. static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
  283. ID.AddPointer(VTList.VTs);
  284. }
  285. /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
  286. ///
  287. static void AddNodeIDOperands(FoldingSetNodeID &ID,
  288. const SDValue *Ops, unsigned NumOps) {
  289. for (; NumOps; --NumOps, ++Ops) {
  290. ID.AddPointer(Ops->getNode());
  291. ID.AddInteger(Ops->getResNo());
  292. }
  293. }
  294. /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
  295. ///
  296. static void AddNodeIDOperands(FoldingSetNodeID &ID,
  297. const SDUse *Ops, unsigned NumOps) {
  298. for (; NumOps; --NumOps, ++Ops) {
  299. ID.AddPointer(Ops->getNode());
  300. ID.AddInteger(Ops->getResNo());
  301. }
  302. }
  303. static void AddNodeIDNode(FoldingSetNodeID &ID,
  304. unsigned short OpC, SDVTList VTList,
  305. const SDValue *OpList, unsigned N) {
  306. AddNodeIDOpcode(ID, OpC);
  307. AddNodeIDValueTypes(ID, VTList);
  308. AddNodeIDOperands(ID, OpList, N);
  309. }
  310. /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
  311. /// the NodeID data.
  312. static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
  313. switch (N->getOpcode()) {
  314. case ISD::TargetExternalSymbol:
  315. case ISD::ExternalSymbol:
  316. LLVM_UNREACHABLE("Should only be used on nodes with operands");
  317. default: break; // Normal nodes don't need extra info.
  318. case ISD::ARG_FLAGS:
  319. ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
  320. break;
  321. case ISD::TargetConstant:
  322. case ISD::Constant:
  323. ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
  324. break;
  325. case ISD::TargetConstantFP:
  326. case ISD::ConstantFP: {
  327. ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
  328. break;
  329. }
  330. case ISD::TargetGlobalAddress:
  331. case ISD::GlobalAddress:
  332. case ISD::TargetGlobalTLSAddress:
  333. case ISD::GlobalTLSAddress: {
  334. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
  335. ID.AddPointer(GA->getGlobal());
  336. ID.AddInteger(GA->getOffset());
  337. ID.AddInteger(GA->getTargetFlags());
  338. break;
  339. }
  340. case ISD::BasicBlock:
  341. ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
  342. break;
  343. case ISD::Register:
  344. ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
  345. break;
  346. case ISD::DBG_STOPPOINT: {
  347. const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
  348. ID.AddInteger(DSP->getLine());
  349. ID.AddInteger(DSP->getColumn());
  350. ID.AddPointer(DSP->getCompileUnit());
  351. break;
  352. }
  353. case ISD::SRCVALUE:
  354. ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
  355. break;
  356. case ISD::MEMOPERAND: {
  357. const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
  358. MO.Profile(ID);
  359. break;
  360. }
  361. case ISD::FrameIndex:
  362. case ISD::TargetFrameIndex:
  363. ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
  364. break;
  365. case ISD::JumpTable:
  366. case ISD::TargetJumpTable:
  367. ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
  368. ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
  369. break;
  370. case ISD::ConstantPool:
  371. case ISD::TargetConstantPool: {
  372. const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
  373. ID.AddInteger(CP->getAlignment());
  374. ID.AddInteger(CP->getOffset());
  375. if (CP->isMachineConstantPoolEntry())
  376. CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
  377. else
  378. ID.AddPointer(CP->getConstVal());
  379. ID.AddInteger(CP->getTargetFlags());
  380. break;
  381. }
  382. case ISD::CALL: {
  383. const CallSDNode *Call = cast<CallSDNode>(N);
  384. ID.AddInteger(Call->getCallingConv());
  385. ID.AddInteger(Call->isVarArg());
  386. break;
  387. }
  388. case ISD::LOAD: {
  389. const LoadSDNode *LD = cast<LoadSDNode>(N);
  390. ID.AddInteger(LD->getMemoryVT().getRawBits());
  391. ID.AddInteger(LD->getRawSubclassData());
  392. break;
  393. }
  394. case ISD::STORE: {
  395. const StoreSDNode *ST = cast<StoreSDNode>(N);
  396. ID.AddInteger(ST->getMemoryVT().getRawBits());
  397. ID.AddInteger(ST->getRawSubclassData());
  398. break;
  399. }
  400. case ISD::ATOMIC_CMP_SWAP:
  401. case ISD::ATOMIC_SWAP:
  402. case ISD::ATOMIC_LOAD_ADD:
  403. case ISD::ATOMIC_LOAD_SUB:
  404. case ISD::ATOMIC_LOAD_AND:
  405. case ISD::ATOMIC_LOAD_OR:
  406. case ISD::ATOMIC_LOAD_XOR:
  407. case ISD::ATOMIC_LOAD_NAND:
  408. case ISD::ATOMIC_LOAD_MIN:
  409. case ISD::ATOMIC_LOAD_MAX:
  410. case ISD::ATOMIC_LOAD_UMIN:
  411. case ISD::ATOMIC_LOAD_UMAX: {
  412. const AtomicSDNode *AT = cast<AtomicSDNode>(N);
  413. ID.AddInteger(AT->getMemoryVT().getRawBits());
  414. ID.AddInteger(AT->getRawSubclassData());
  415. break;
  416. }
  417. case ISD::VECTOR_SHUFFLE: {
  418. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  419. for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
  420. i != e; ++i)
  421. ID.AddInteger(SVN->getMaskElt(i));
  422. break;
  423. }
  424. } // end switch (N->getOpcode())
  425. }
  426. /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
  427. /// data.
  428. static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
  429. AddNodeIDOpcode(ID, N->getOpcode());
  430. // Add the return value info.
  431. AddNodeIDValueTypes(ID, N->getVTList());
  432. // Add the operand info.
  433. AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
  434. // Handle SDNode leafs with special info.
  435. AddNodeIDCustom(ID, N);
  436. }
  437. /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
  438. /// the CSE map that carries alignment, volatility, indexing mode, and
  439. /// extension/truncation information.
  440. ///
  441. static inline unsigned
  442. encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM,
  443. bool isVolatile, unsigned Alignment) {
  444. assert((ConvType & 3) == ConvType &&
  445. "ConvType may not require more than 2 bits!");
  446. assert((AM & 7) == AM &&
  447. "AM may not require more than 3 bits!");
  448. return ConvType |
  449. (AM << 2) |
  450. (isVolatile << 5) |
  451. ((Log2_32(Alignment) + 1) << 6);
  452. }
  453. //===----------------------------------------------------------------------===//
  454. // SelectionDAG Class
  455. //===----------------------------------------------------------------------===//
  456. /// doNotCSE - Return true if CSE should not be performed for this node.
  457. static bool doNotCSE(SDNode *N) {
  458. if (N->getValueType(0) == MVT::Flag)
  459. return true; // Never CSE anything that produces a flag.
  460. switch (N->getOpcode()) {
  461. default: break;
  462. case ISD::HANDLENODE:
  463. case ISD::DBG_LABEL:
  464. case ISD::DBG_STOPPOINT:
  465. case ISD::EH_LABEL:
  466. case ISD::DECLARE:
  467. return true; // Never CSE these nodes.
  468. }
  469. // Check that remaining values produced are not flags.
  470. for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
  471. if (N->getValueType(i) == MVT::Flag)
  472. return true; // Never CSE anything that produces a flag.
  473. return false;
  474. }
  475. /// RemoveDeadNodes - This method deletes all unreachable nodes in the
  476. /// SelectionDAG.
  477. void SelectionDAG::RemoveDeadNodes() {
  478. // Create a dummy node (which is not added to allnodes), that adds a reference
  479. // to the root node, preventing it from being deleted.
  480. HandleSDNode Dummy(getRoot());
  481. SmallVector<SDNode*, 128> DeadNodes;
  482. // Add all obviously-dead nodes to the DeadNodes worklist.
  483. for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
  484. if (I->use_empty())
  485. DeadNodes.push_back(I);
  486. RemoveDeadNodes(DeadNodes);
  487. // If the root changed (e.g. it was a dead load, update the root).
  488. setRoot(Dummy.getValue());
  489. }
  490. /// RemoveDeadNodes - This method deletes the unreachable nodes in the
  491. /// given list, and any nodes that become unreachable as a result.
  492. void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
  493. DAGUpdateListener *UpdateListener) {
  494. // Process the worklist, deleting the nodes and adding their uses to the
  495. // worklist.
  496. while (!DeadNodes.empty()) {
  497. SDNode *N = DeadNodes.pop_back_val();
  498. if (UpdateListener)
  499. UpdateListener->NodeDeleted(N, 0);
  500. // Take the node out of the appropriate CSE map.
  501. RemoveNodeFromCSEMaps(N);
  502. // Next, brutally remove the operand list. This is safe to do, as there are
  503. // no cycles in the graph.
  504. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  505. SDUse &Use = *I++;
  506. SDNode *Operand = Use.getNode();
  507. Use.set(SDValue());
  508. // Now that we removed this operand, see if there are no uses of it left.
  509. if (Operand->use_empty())
  510. DeadNodes.push_back(Operand);
  511. }
  512. DeallocateNode(N);
  513. }
  514. }
  515. void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
  516. SmallVector<SDNode*, 16> DeadNodes(1, N);
  517. RemoveDeadNodes(DeadNodes, UpdateListener);
  518. }
  519. void SelectionDAG::DeleteNode(SDNode *N) {
  520. // First take this out of the appropriate CSE map.
  521. RemoveNodeFromCSEMaps(N);
  522. // Finally, remove uses due to operands of this node, remove from the
  523. // AllNodes list, and delete the node.
  524. DeleteNodeNotInCSEMaps(N);
  525. }
  526. void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
  527. assert(N != AllNodes.begin() && "Cannot delete the entry node!");
  528. assert(N->use_empty() && "Cannot delete a node that is not dead!");
  529. // Drop all of the operands and decrement used node's use counts.
  530. N->DropOperands();
  531. DeallocateNode(N);
  532. }
  533. void SelectionDAG::DeallocateNode(SDNode *N) {
  534. if (N->OperandsNeedDelete)
  535. delete[] N->OperandList;
  536. // Set the opcode to DELETED_NODE to help catch bugs when node
  537. // memory is reallocated.
  538. N->NodeType = ISD::DELETED_NODE;
  539. NodeAllocator.Deallocate(AllNodes.remove(N));
  540. }
  541. /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
  542. /// correspond to it. This is useful when we're about to delete or repurpose
  543. /// the node. We don't want future request for structurally identical nodes
  544. /// to return N anymore.
  545. bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
  546. bool Erased = false;
  547. switch (N->getOpcode()) {
  548. case ISD::EntryToken:
  549. LLVM_UNREACHABLE("EntryToken should not be in CSEMaps!");
  550. return false;
  551. case ISD::HANDLENODE: return false; // noop.
  552. case ISD::CONDCODE:
  553. assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
  554. "Cond code doesn't exist!");
  555. Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
  556. CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
  557. break;
  558. case ISD::ExternalSymbol:
  559. Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
  560. break;
  561. case ISD::TargetExternalSymbol: {
  562. ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
  563. Erased = TargetExternalSymbols.erase(
  564. std::pair<std::string,unsigned char>(ESN->getSymbol(),
  565. ESN->getTargetFlags()));
  566. break;
  567. }
  568. case ISD::VALUETYPE: {
  569. MVT VT = cast<VTSDNode>(N)->getVT();
  570. if (VT.isExtended()) {
  571. Erased = ExtendedValueTypeNodes.erase(VT);
  572. } else {
  573. Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
  574. ValueTypeNodes[VT.getSimpleVT()] = 0;
  575. }
  576. break;
  577. }
  578. default:
  579. // Remove it from the CSE Map.
  580. Erased = CSEMap.RemoveNode(N);
  581. break;
  582. }
  583. #ifndef NDEBUG
  584. // Verify that the node was actually in one of the CSE maps, unless it has a
  585. // flag result (which cannot be CSE'd) or is one of the special cases that are
  586. // not subject to CSE.
  587. if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
  588. !N->isMachineOpcode() && !doNotCSE(N)) {
  589. N->dump(this);
  590. cerr << "\n";
  591. LLVM_UNREACHABLE("Node is not in map!");
  592. }
  593. #endif
  594. return Erased;
  595. }
  596. /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
  597. /// maps and modified in place. Add it back to the CSE maps, unless an identical
  598. /// node already exists, in which case transfer all its users to the existing
  599. /// node. This transfer can potentially trigger recursive merging.
  600. ///
  601. void
  602. SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
  603. DAGUpdateListener *UpdateListener) {
  604. // For node types that aren't CSE'd, just act as if no identical node
  605. // already exists.
  606. if (!doNotCSE(N)) {
  607. SDNode *Existing = CSEMap.GetOrInsertNode(N);
  608. if (Existing != N) {
  609. // If there was already an existing matching node, use ReplaceAllUsesWith
  610. // to replace the dead one with the existing one. This can cause
  611. // recursive merging of other unrelated nodes down the line.
  612. ReplaceAllUsesWith(N, Existing, UpdateListener);
  613. // N is now dead. Inform the listener if it exists and delete it.
  614. if (UpdateListener)
  615. UpdateListener->NodeDeleted(N, Existing);
  616. DeleteNodeNotInCSEMaps(N);
  617. return;
  618. }
  619. }
  620. // If the node doesn't already exist, we updated it. Inform a listener if
  621. // it exists.
  622. if (UpdateListener)
  623. UpdateListener->NodeUpdated(N);
  624. }
  625. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  626. /// were replaced with those specified. If this node is never memoized,
  627. /// return null, otherwise return a pointer to the slot it would take. If a
  628. /// node already exists with these operands, the slot will be non-null.
  629. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
  630. void *&InsertPos) {
  631. if (doNotCSE(N))
  632. return 0;
  633. SDValue Ops[] = { Op };
  634. FoldingSetNodeID ID;
  635. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
  636. AddNodeIDCustom(ID, N);
  637. return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  638. }
  639. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  640. /// were replaced with those specified. If this node is never memoized,
  641. /// return null, otherwise return a pointer to the slot it would take. If a
  642. /// node already exists with these operands, the slot will be non-null.
  643. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
  644. SDValue Op1, SDValue Op2,
  645. void *&InsertPos) {
  646. if (doNotCSE(N))
  647. return 0;
  648. SDValue Ops[] = { Op1, Op2 };
  649. FoldingSetNodeID ID;
  650. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
  651. AddNodeIDCustom(ID, N);
  652. return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  653. }
  654. /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
  655. /// were replaced with those specified. If this node is never memoized,
  656. /// return null, otherwise return a pointer to the slot it would take. If a
  657. /// node already exists with these operands, the slot will be non-null.
  658. SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
  659. const SDValue *Ops,unsigned NumOps,
  660. void *&InsertPos) {
  661. if (doNotCSE(N))
  662. return 0;
  663. FoldingSetNodeID ID;
  664. AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
  665. AddNodeIDCustom(ID, N);
  666. return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
  667. }
  668. /// VerifyNode - Sanity check the given node. Aborts if it is invalid.
  669. void SelectionDAG::VerifyNode(SDNode *N) {
  670. switch (N->getOpcode()) {
  671. default:
  672. break;
  673. case ISD::BUILD_PAIR: {
  674. MVT VT = N->getValueType(0);
  675. assert(N->getNumValues() == 1 && "Too many results!");
  676. assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
  677. "Wrong return type!");
  678. assert(N->getNumOperands() == 2 && "Wrong number of operands!");
  679. assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
  680. "Mismatched operand types!");
  681. assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
  682. "Wrong operand type!");
  683. assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
  684. "Wrong return type size");
  685. break;
  686. }
  687. case ISD::BUILD_VECTOR: {
  688. assert(N->getNumValues() == 1 && "Too many results!");
  689. assert(N->getValueType(0).isVector() && "Wrong return type!");
  690. assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
  691. "Wrong number of operands!");
  692. MVT EltVT = N->getValueType(0).getVectorElementType();
  693. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
  694. assert((I->getValueType() == EltVT ||
  695. (EltVT.isInteger() && I->getValueType().isInteger() &&
  696. EltVT.bitsLE(I->getValueType()))) &&
  697. "Wrong operand type!");
  698. break;
  699. }
  700. }
  701. }
  702. /// getMVTAlignment - Compute the default alignment value for the
  703. /// given type.
  704. ///
  705. unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
  706. const Type *Ty = VT == MVT::iPTR ?
  707. PointerType::get(Type::Int8Ty, 0) :
  708. VT.getTypeForMVT(*Context);
  709. return TLI.getTargetData()->getABITypeAlignment(Ty);
  710. }
  711. // EntryNode could meaningfully have debug info if we can find it...
  712. SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
  713. : TLI(tli), FLI(fli), DW(0),
  714. EntryNode(ISD::EntryToken, DebugLoc::getUnknownLoc(),
  715. getVTList(MVT::Other)), Root(getEntryNode()) {
  716. AllNodes.push_back(&EntryNode);
  717. }
  718. void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
  719. DwarfWriter *dw) {
  720. MF = &mf;
  721. MMI = mmi;
  722. DW = dw;
  723. Context = mf.getFunction()->getContext();
  724. }
  725. SelectionDAG::~SelectionDAG() {
  726. allnodes_clear();
  727. }
  728. void SelectionDAG::allnodes_clear() {
  729. assert(&*AllNodes.begin() == &EntryNode);
  730. AllNodes.remove(AllNodes.begin());
  731. while (!AllNodes.empty())
  732. DeallocateNode(AllNodes.begin());
  733. }
  734. void SelectionDAG::clear() {
  735. allnodes_clear();
  736. OperandAllocator.Reset();
  737. CSEMap.clear();
  738. ExtendedValueTypeNodes.clear();
  739. ExternalSymbols.clear();
  740. TargetExternalSymbols.clear();
  741. std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
  742. static_cast<CondCodeSDNode*>(0));
  743. std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
  744. static_cast<SDNode*>(0));
  745. EntryNode.UseList = 0;
  746. AllNodes.push_back(&EntryNode);
  747. Root = getEntryNode();
  748. }
  749. SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, MVT VT) {
  750. if (Op.getValueType() == VT) return Op;
  751. APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
  752. VT.getSizeInBits());
  753. return getNode(ISD::AND, DL, Op.getValueType(), Op,
  754. getConstant(Imm, Op.getValueType()));
  755. }
  756. /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
  757. ///
  758. SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, MVT VT) {
  759. MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
  760. SDValue NegOne =
  761. getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
  762. return getNode(ISD::XOR, DL, VT, Val, NegOne);
  763. }
  764. SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
  765. MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
  766. assert((EltVT.getSizeInBits() >= 64 ||
  767. (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
  768. "getConstant with a uint64_t value that doesn't fit in the type!");
  769. return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
  770. }
  771. SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
  772. return getConstant(*ConstantInt::get(Val), VT, isT);
  773. }
  774. SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
  775. assert(VT.isInteger() && "Cannot create FP integer constant!");
  776. MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
  777. assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
  778. "APInt size does not match type size!");
  779. unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
  780. FoldingSetNodeID ID;
  781. AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
  782. ID.AddPointer(&Val);
  783. void *IP = 0;
  784. SDNode *N = NULL;
  785. if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
  786. if (!VT.isVector())
  787. return SDValue(N, 0);
  788. if (!N) {
  789. N = NodeAllocator.Allocate<ConstantSDNode>();
  790. new (N) ConstantSDNode(isT, &Val, EltVT);
  791. CSEMap.InsertNode(N, IP);
  792. AllNodes.push_back(N);
  793. }
  794. SDValue Result(N, 0);
  795. if (VT.isVector()) {
  796. SmallVector<SDValue, 8> Ops;
  797. Ops.assign(VT.getVectorNumElements(), Result);
  798. Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
  799. VT, &Ops[0], Ops.size());
  800. }
  801. return Result;
  802. }
  803. SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
  804. return getConstant(Val, TLI.getPointerTy(), isTarget);
  805. }
  806. SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
  807. return getConstantFP(*ConstantFP::get(V), VT, isTarget);
  808. }
  809. SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
  810. assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
  811. MVT EltVT =
  812. VT.isVector() ? VT.getVectorElementType() : VT;
  813. // Do the map lookup using the actual bit pattern for the floating point
  814. // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
  815. // we don't have issues with SNANs.
  816. unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
  817. FoldingSetNodeID ID;
  818. AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
  819. ID.AddPointer(&V);
  820. void *IP = 0;
  821. SDNode *N = NULL;
  822. if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
  823. if (!VT.isVector())
  824. return SDValue(N, 0);
  825. if (!N) {
  826. N = NodeAllocator.Allocate<ConstantFPSDNode>();
  827. new (N) ConstantFPSDNode(isTarget, &V, EltVT);
  828. CSEMap.InsertNode(N, IP);
  829. AllNodes.push_back(N);
  830. }
  831. SDValue Result(N, 0);
  832. if (VT.isVector()) {
  833. SmallVector<SDValue, 8> Ops;
  834. Ops.assign(VT.getVectorNumElements(), Result);
  835. // FIXME DebugLoc info might be appropriate here
  836. Result = getNode(ISD::BUILD_VECTOR, DebugLoc::getUnknownLoc(),
  837. VT, &Ops[0], Ops.size());
  838. }
  839. return Result;
  840. }
  841. SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
  842. MVT EltVT =
  843. VT.isVector() ? VT.getVectorElementType() : VT;
  844. if (EltVT==MVT::f32)
  845. return getConstantFP(APFloat((float)Val), VT, isTarget);
  846. else
  847. return getConstantFP(APFloat(Val), VT, isTarget);
  848. }
  849. SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
  850. MVT VT, int64_t Offset,
  851. bool isTargetGA,
  852. unsigned char TargetFlags) {
  853. assert((TargetFlags == 0 || isTargetGA) &&
  854. "Cannot set target flags on target-independent globals");
  855. // Truncate (with sign-extension) the offset value to the pointer size.
  856. unsigned BitWidth = TLI.getPointerTy().getSizeInBits();
  857. if (BitWidth < 64)
  858. Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
  859. const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
  860. if (!GVar) {
  861. // If GV is an alias then use the aliasee for determining thread-localness.
  862. if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
  863. GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
  864. }
  865. unsigned Opc;
  866. if (GVar && GVar->isThreadLocal())
  867. Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
  868. else
  869. Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
  870. FoldingSetNodeID ID;
  871. AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
  872. ID.AddPointer(GV);
  873. ID.AddInteger(Offset);
  874. ID.AddInteger(TargetFlags);
  875. void *IP = 0;
  876. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  877. return SDValue(E, 0);
  878. SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
  879. new (N) GlobalAddressSDNode(Opc, GV, VT, Offset, TargetFlags);
  880. CSEMap.InsertNode(N, IP);
  881. AllNodes.push_back(N);
  882. return SDValue(N, 0);
  883. }
  884. SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
  885. unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
  886. FoldingSetNodeID ID;
  887. AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
  888. ID.AddInteger(FI);
  889. void *IP = 0;
  890. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  891. return SDValue(E, 0);
  892. SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
  893. new (N) FrameIndexSDNode(FI, VT, isTarget);
  894. CSEMap.InsertNode(N, IP);
  895. AllNodes.push_back(N);
  896. return SDValue(N, 0);
  897. }
  898. SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget,
  899. unsigned char TargetFlags) {
  900. assert((TargetFlags == 0 || isTarget) &&
  901. "Cannot set target flags on target-independent jump tables");
  902. unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
  903. FoldingSetNodeID ID;
  904. AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
  905. ID.AddInteger(JTI);
  906. ID.AddInteger(TargetFlags);
  907. void *IP = 0;
  908. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  909. return SDValue(E, 0);
  910. SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
  911. new (N) JumpTableSDNode(JTI, VT, isTarget, TargetFlags);
  912. CSEMap.InsertNode(N, IP);
  913. AllNodes.push_back(N);
  914. return SDValue(N, 0);
  915. }
  916. SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
  917. unsigned Alignment, int Offset,
  918. bool isTarget,
  919. unsigned char TargetFlags) {
  920. assert((TargetFlags == 0 || isTarget) &&
  921. "Cannot set target flags on target-independent globals");
  922. if (Alignment == 0)
  923. Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
  924. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  925. FoldingSetNodeID ID;
  926. AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
  927. ID.AddInteger(Alignment);
  928. ID.AddInteger(Offset);
  929. ID.AddPointer(C);
  930. ID.AddInteger(TargetFlags);
  931. void *IP = 0;
  932. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  933. return SDValue(E, 0);
  934. SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
  935. new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
  936. CSEMap.InsertNode(N, IP);
  937. AllNodes.push_back(N);
  938. return SDValue(N, 0);
  939. }
  940. SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
  941. unsigned Alignment, int Offset,
  942. bool isTarget,
  943. unsigned char TargetFlags) {
  944. assert((TargetFlags == 0 || isTarget) &&
  945. "Cannot set target flags on target-independent globals");
  946. if (Alignment == 0)
  947. Alignment = TLI.getTargetData()->getPrefTypeAlignment(C->getType());
  948. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  949. FoldingSetNodeID ID;
  950. AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
  951. ID.AddInteger(Alignment);
  952. ID.AddInteger(Offset);
  953. C->AddSelectionDAGCSEId(ID);
  954. ID.AddInteger(TargetFlags);
  955. void *IP = 0;
  956. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  957. return SDValue(E, 0);
  958. SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
  959. new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment, TargetFlags);
  960. CSEMap.InsertNode(N, IP);
  961. AllNodes.push_back(N);
  962. return SDValue(N, 0);
  963. }
  964. SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
  965. FoldingSetNodeID ID;
  966. AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
  967. ID.AddPointer(MBB);
  968. void *IP = 0;
  969. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  970. return SDValue(E, 0);
  971. SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
  972. new (N) BasicBlockSDNode(MBB);
  973. CSEMap.InsertNode(N, IP);
  974. AllNodes.push_back(N);
  975. return SDValue(N, 0);
  976. }
  977. SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
  978. FoldingSetNodeID ID;
  979. AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
  980. ID.AddInteger(Flags.getRawBits());
  981. void *IP = 0;
  982. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  983. return SDValue(E, 0);
  984. SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
  985. new (N) ARG_FLAGSSDNode(Flags);
  986. CSEMap.InsertNode(N, IP);
  987. AllNodes.push_back(N);
  988. return SDValue(N, 0);
  989. }
  990. SDValue SelectionDAG::getValueType(MVT VT) {
  991. if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
  992. ValueTypeNodes.resize(VT.getSimpleVT()+1);
  993. SDNode *&N = VT.isExtended() ?
  994. ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
  995. if (N) return SDValue(N, 0);
  996. N = NodeAllocator.Allocate<VTSDNode>();
  997. new (N) VTSDNode(VT);
  998. AllNodes.push_back(N);
  999. return SDValue(N, 0);
  1000. }
  1001. SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
  1002. SDNode *&N = ExternalSymbols[Sym];
  1003. if (N) return SDValue(N, 0);
  1004. N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
  1005. new (N) ExternalSymbolSDNode(false, Sym, 0, VT);
  1006. AllNodes.push_back(N);
  1007. return SDValue(N, 0);
  1008. }
  1009. SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT,
  1010. unsigned char TargetFlags) {
  1011. SDNode *&N =
  1012. TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
  1013. TargetFlags)];
  1014. if (N) return SDValue(N, 0);
  1015. N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
  1016. new (N) ExternalSymbolSDNode(true, Sym, TargetFlags, VT);
  1017. AllNodes.push_back(N);
  1018. return SDValue(N, 0);
  1019. }
  1020. SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
  1021. if ((unsigned)Cond >= CondCodeNodes.size())
  1022. CondCodeNodes.resize(Cond+1);
  1023. if (CondCodeNodes[Cond] == 0) {
  1024. CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
  1025. new (N) CondCodeSDNode(Cond);
  1026. CondCodeNodes[Cond] = N;
  1027. AllNodes.push_back(N);
  1028. }
  1029. return SDValue(CondCodeNodes[Cond], 0);
  1030. }
  1031. // commuteShuffle - swaps the values of N1 and N2, and swaps all indices in
  1032. // the shuffle mask M that point at N1 to point at N2, and indices that point
  1033. // N2 to point at N1.
  1034. static void commuteShuffle(SDValue &N1, SDValue &N2, SmallVectorImpl<int> &M) {
  1035. std::swap(N1, N2);
  1036. int NElts = M.size();
  1037. for (int i = 0; i != NElts; ++i) {
  1038. if (M[i] >= NElts)
  1039. M[i] -= NElts;
  1040. else if (M[i] >= 0)
  1041. M[i] += NElts;
  1042. }
  1043. }
  1044. SDValue SelectionDAG::getVectorShuffle(MVT VT, DebugLoc dl, SDValue N1,
  1045. SDValue N2, const int *Mask) {
  1046. assert(N1.getValueType() == N2.getValueType() && "Invalid VECTOR_SHUFFLE");
  1047. assert(VT.isVector() && N1.getValueType().isVector() &&
  1048. "Vector Shuffle VTs must be a vectors");
  1049. assert(VT.getVectorElementType() == N1.getValueType().getVectorElementType()
  1050. && "Vector Shuffle VTs must have same element type");
  1051. // Canonicalize shuffle undef, undef -> undef
  1052. if (N1.getOpcode() == ISD::UNDEF && N2.getOpcode() == ISD::UNDEF)
  1053. return getUNDEF(VT);
  1054. // Validate that all indices in Mask are within the range of the elements
  1055. // input to the shuffle.
  1056. unsigned NElts = VT.getVectorNumElements();
  1057. SmallVector<int, 8> MaskVec;
  1058. for (unsigned i = 0; i != NElts; ++i) {
  1059. assert(Mask[i] < (int)(NElts * 2) && "Index out of range");
  1060. MaskVec.push_back(Mask[i]);
  1061. }
  1062. // Canonicalize shuffle v, v -> v, undef
  1063. if (N1 == N2) {
  1064. N2 = getUNDEF(VT);
  1065. for (unsigned i = 0; i != NElts; ++i)
  1066. if (MaskVec[i] >= (int)NElts) MaskVec[i] -= NElts;
  1067. }
  1068. // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
  1069. if (N1.getOpcode() == ISD::UNDEF)
  1070. commuteShuffle(N1, N2, MaskVec);
  1071. // Canonicalize all index into lhs, -> shuffle lhs, undef
  1072. // Canonicalize all index into rhs, -> shuffle rhs, undef
  1073. bool AllLHS = true, AllRHS = true;
  1074. bool N2Undef = N2.getOpcode() == ISD::UNDEF;
  1075. for (unsigned i = 0; i != NElts; ++i) {
  1076. if (MaskVec[i] >= (int)NElts) {
  1077. if (N2Undef)
  1078. MaskVec[i] = -1;
  1079. else
  1080. AllLHS = false;
  1081. } else if (MaskVec[i] >= 0) {
  1082. AllRHS = false;
  1083. }
  1084. }
  1085. if (AllLHS && AllRHS)
  1086. return getUNDEF(VT);
  1087. if (AllLHS && !N2Undef)
  1088. N2 = getUNDEF(VT);
  1089. if (AllRHS) {
  1090. N1 = getUNDEF(VT);
  1091. commuteShuffle(N1, N2, MaskVec);
  1092. }
  1093. // If Identity shuffle, or all shuffle in to undef, return that node.
  1094. bool AllUndef = true;
  1095. bool Identity = true;
  1096. for (unsigned i = 0; i != NElts; ++i) {
  1097. if (MaskVec[i] >= 0 && MaskVec[i] != (int)i) Identity = false;
  1098. if (MaskVec[i] >= 0) AllUndef = false;
  1099. }
  1100. if (Identity && NElts == N1.getValueType().getVectorNumElements())
  1101. return N1;
  1102. if (AllUndef)
  1103. return getUNDEF(VT);
  1104. FoldingSetNodeID ID;
  1105. SDValue Ops[2] = { N1, N2 };
  1106. AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops, 2);
  1107. for (unsigned i = 0; i != NElts; ++i)
  1108. ID.AddInteger(MaskVec[i]);
  1109. void* IP = 0;
  1110. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  1111. return SDValue(E, 0);
  1112. // Allocate the mask array for the node out of the BumpPtrAllocator, since
  1113. // SDNode doesn't have access to it. This memory will be "leaked" when
  1114. // the node is deallocated, but recovered when the NodeAllocator is released.
  1115. int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
  1116. memcpy(MaskAlloc, &MaskVec[0], NElts * sizeof(int));
  1117. ShuffleVectorSDNode *N = NodeAllocator.Allocate<ShuffleVectorSDNode>();
  1118. new (N) ShuffleVectorSDNode(VT, dl, N1, N2, MaskAlloc);
  1119. CSEMap.InsertNode(N, IP);
  1120. AllNodes.push_back(N);
  1121. return SDValue(N, 0);
  1122. }
  1123. SDValue SelectionDAG::getConvertRndSat(MVT VT, DebugLoc dl,
  1124. SDValue Val, SDValue DTy,
  1125. SDValue STy, SDValue Rnd, SDValue Sat,
  1126. ISD::CvtCode Code) {
  1127. // If the src and dest types are the same and the conversion is between
  1128. // integer types of the same sign or two floats, no conversion is necessary.
  1129. if (DTy == STy &&
  1130. (Code == ISD::CVT_UU || Code == ISD::CVT_SS || Code == ISD::CVT_FF))
  1131. return Val;
  1132. FoldingSetNodeID ID;
  1133. void* IP = 0;
  1134. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  1135. return SDValue(E, 0);
  1136. CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
  1137. SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
  1138. new (N) CvtRndSatSDNode(VT, dl, Ops, 5, Code);
  1139. CSEMap.InsertNode(N, IP);
  1140. AllNodes.push_back(N);
  1141. return SDValue(N, 0);
  1142. }
  1143. SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
  1144. FoldingSetNodeID ID;
  1145. AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
  1146. ID.AddInteger(RegNo);
  1147. void *IP = 0;
  1148. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  1149. return SDValue(E, 0);
  1150. SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
  1151. new (N) RegisterSDNode(RegNo, VT);
  1152. CSEMap.InsertNode(N, IP);
  1153. AllNodes.push_back(N);
  1154. return SDValue(N, 0);
  1155. }
  1156. SDValue SelectionDAG::getDbgStopPoint(DebugLoc DL, SDValue Root,
  1157. unsigned Line, unsigned Col,
  1158. Value *CU) {
  1159. SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
  1160. new (N) DbgStopPointSDNode(Root, Line, Col, CU);
  1161. N->setDebugLoc(DL);
  1162. AllNodes.push_back(N);
  1163. return SDValue(N, 0);
  1164. }
  1165. SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
  1166. SDValue Root,
  1167. unsigned LabelID) {
  1168. FoldingSetNodeID ID;
  1169. SDValue Ops[] = { Root };
  1170. AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
  1171. ID.AddInteger(LabelID);
  1172. void *IP = 0;
  1173. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  1174. return SDValue(E, 0);
  1175. SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
  1176. new (N) LabelSDNode(Opcode, dl, Root, LabelID);
  1177. CSEMap.InsertNode(N, IP);
  1178. AllNodes.push_back(N);
  1179. return SDValue(N, 0);
  1180. }
  1181. SDValue SelectionDAG::getSrcValue(const Value *V) {
  1182. assert((!V || isa<PointerType>(V->getType())) &&
  1183. "SrcValue is not a pointer?");
  1184. FoldingSetNodeID ID;
  1185. AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
  1186. ID.AddPointer(V);
  1187. void *IP = 0;
  1188. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  1189. return SDValue(E, 0);
  1190. SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
  1191. new (N) SrcValueSDNode(V);
  1192. CSEMap.InsertNode(N, IP);
  1193. AllNodes.push_back(N);
  1194. return SDValue(N, 0);
  1195. }
  1196. SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
  1197. #ifndef NDEBUG
  1198. const Value *v = MO.getValue();
  1199. assert((!v || isa<PointerType>(v->getType())) &&
  1200. "SrcValue is not a pointer?");
  1201. #endif
  1202. FoldingSetNodeID ID;
  1203. AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
  1204. MO.Profile(ID);
  1205. void *IP = 0;
  1206. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  1207. return SDValue(E, 0);
  1208. SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
  1209. new (N) MemOperandSDNode(MO);
  1210. CSEMap.InsertNode(N, IP);
  1211. AllNodes.push_back(N);
  1212. return SDValue(N, 0);
  1213. }
  1214. /// getShiftAmountOperand - Return the specified value casted to
  1215. /// the target's desired shift amount type.
  1216. SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
  1217. MVT OpTy = Op.getValueType();
  1218. MVT ShTy = TLI.getShiftAmountTy();
  1219. if (OpTy == ShTy || OpTy.isVector()) return Op;
  1220. ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
  1221. return getNode(Opcode, Op.getDebugLoc(), ShTy, Op);
  1222. }
  1223. /// CreateStackTemporary - Create a stack temporary, suitable for holding the
  1224. /// specified value type.
  1225. SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
  1226. MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
  1227. unsigned ByteSize = VT.getStoreSizeInBits()/8;
  1228. const Type *Ty = VT.getTypeForMVT(*Context);
  1229. unsigned StackAlign =
  1230. std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
  1231. int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
  1232. return getFrameIndex(FrameIdx, TLI.getPointerTy());
  1233. }
  1234. /// CreateStackTemporary - Create a stack temporary suitable for holding
  1235. /// either of the specified value types.
  1236. SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) {
  1237. unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
  1238. VT2.getStoreSizeInBits())/8;
  1239. const Type *Ty1 = VT1.getTypeForMVT(*Context);
  1240. const Type *Ty2 = VT2.getTypeForMVT(*Context);
  1241. const TargetData *TD = TLI.getTargetData();
  1242. unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
  1243. TD->getPrefTypeAlignment(Ty2));
  1244. MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
  1245. int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
  1246. return getFrameIndex(FrameIdx, TLI.getPointerTy());
  1247. }
  1248. SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
  1249. SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
  1250. // These setcc operations always fold.
  1251. switch (Cond) {
  1252. default: break;
  1253. case ISD::SETFALSE:
  1254. case ISD::SETFALSE2: return getConstant(0, VT);
  1255. case ISD::SETTRUE:
  1256. case ISD::SETTRUE2: return getConstant(1, VT);
  1257. case ISD::SETOEQ:
  1258. case ISD::SETOGT:
  1259. case ISD::SETOGE:
  1260. case ISD::SETOLT:
  1261. case ISD::SETOLE:
  1262. case ISD::SETONE:
  1263. case ISD::SETO:
  1264. case ISD::SETUO:
  1265. case ISD::SETUEQ:
  1266. case ISD::SETUNE:
  1267. assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
  1268. break;
  1269. }
  1270. if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
  1271. const APInt &C2 = N2C->getAPIntValue();
  1272. if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
  1273. const APInt &C1 = N1C->getAPIntValue();
  1274. switch (Cond) {
  1275. default: LLVM_UNREACHABLE("Unknown integer setcc!");
  1276. case ISD::SETEQ: return getConstant(C1 == C2, VT);
  1277. case ISD::SETNE: return getConstant(C1 != C2, VT);
  1278. case ISD::SETULT: return getConstant(C1.ult(C2), VT);
  1279. case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
  1280. case ISD::SETULE: return getConstant(C1.ule(C2), VT);
  1281. case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
  1282. case ISD::SETLT: return getConstant(C1.slt(C2), VT);
  1283. case ISD::SETGT: return getConstant(C1.sgt(C2), VT);
  1284. case ISD::SETLE: return getConstant(C1.sle(C2), VT);
  1285. case ISD::SETGE: return getConstant(C1.sge(C2), VT);
  1286. }
  1287. }
  1288. }
  1289. if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
  1290. if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
  1291. // No compile time operations on this type yet.
  1292. if (N1C->getValueType(0) == MVT::ppcf128)
  1293. return SDValue();
  1294. APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
  1295. switch (Cond) {
  1296. default: break;
  1297. case ISD::SETEQ: if (R==APFloat::cmpUnordered)
  1298. return getUNDEF(VT);
  1299. // fall through
  1300. case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
  1301. case ISD::SETNE: if (R==APFloat::cmpUnordered)
  1302. return getUNDEF(VT);
  1303. // fall through
  1304. case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
  1305. R==APFloat::cmpLessThan, VT);
  1306. case ISD::SETLT: if (R==APFloat::cmpUnordered)
  1307. return getUNDEF(VT);
  1308. // fall through
  1309. case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
  1310. case ISD::SETGT: if (R==APFloat::cmpUnordered)
  1311. return getUNDEF(VT);
  1312. // fall through
  1313. case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
  1314. case ISD::SETLE: if (R==APFloat::cmpUnordered)
  1315. return getUNDEF(VT);
  1316. // fall through
  1317. case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
  1318. R==APFloat::cmpEqual, VT);
  1319. case ISD::SETGE: if (R==APFloat::cmpUnordered)
  1320. return getUNDEF(VT);
  1321. // fall through
  1322. case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
  1323. R==APFloat::cmpEqual, VT);
  1324. case ISD::SETO: return getConstant(R!=APFloat::cmpUnordered, VT);
  1325. case ISD::SETUO: return getConstant(R==APFloat::cmpUnordered, VT);
  1326. case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
  1327. R==APFloat::cmpEqual, VT);
  1328. case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
  1329. case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
  1330. R==APFloat::cmpLessThan, VT);
  1331. case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
  1332. R==APFloat::cmpUnordered, VT);
  1333. case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
  1334. case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
  1335. }
  1336. } else {
  1337. // Ensure that the constant occurs on the RHS.
  1338. return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
  1339. }
  1340. }
  1341. // Could not fold it.
  1342. return SDValue();
  1343. }
  1344. /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
  1345. /// use this predicate to simplify operations downstream.
  1346. bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
  1347. // This predicate is not safe for vector operations.
  1348. if (Op.getValueType().isVector())
  1349. return false;
  1350. unsigned BitWidth = Op.getValueSizeInBits();
  1351. return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
  1352. }
  1353. /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
  1354. /// this predicate to simplify operations downstream. Mask is known to be zero
  1355. /// for bits that V cannot have.
  1356. bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
  1357. unsigned Depth) const {
  1358. APInt KnownZero, KnownOne;
  1359. ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
  1360. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1361. return (KnownZero & Mask) == Mask;
  1362. }
  1363. /// ComputeMaskedBits - Determine which of the bits specified in Mask are
  1364. /// known to be either zero or one and return them in the KnownZero/KnownOne
  1365. /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
  1366. /// processing.
  1367. void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask,
  1368. APInt &KnownZero, APInt &KnownOne,
  1369. unsigned Depth) const {
  1370. unsigned BitWidth = Mask.getBitWidth();
  1371. assert(BitWidth == Op.getValueType().getSizeInBits() &&
  1372. "Mask size mismatches value type size!");
  1373. KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
  1374. if (Depth == 6 || Mask == 0)
  1375. return; // Limit search depth.
  1376. APInt KnownZero2, KnownOne2;
  1377. switch (Op.getOpcode()) {
  1378. case ISD::Constant:
  1379. // We know all of the bits for a constant!
  1380. KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
  1381. KnownZero = ~KnownOne & Mask;
  1382. return;
  1383. case ISD::AND:
  1384. // If either the LHS or the RHS are Zero, the result is zero.
  1385. ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
  1386. ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
  1387. KnownZero2, KnownOne2, Depth+1);
  1388. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1389. assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
  1390. // Output known-1 bits are only known if set in both the LHS & RHS.
  1391. KnownOne &= KnownOne2;
  1392. // Output known-0 are known to be clear if zero in either the LHS | RHS.
  1393. KnownZero |= KnownZero2;
  1394. return;
  1395. case ISD::OR:
  1396. ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
  1397. ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
  1398. KnownZero2, KnownOne2, Depth+1);
  1399. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1400. assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
  1401. // Output known-0 bits are only known if clear in both the LHS & RHS.
  1402. KnownZero &= KnownZero2;
  1403. // Output known-1 are known to be set if set in either the LHS | RHS.
  1404. KnownOne |= KnownOne2;
  1405. return;
  1406. case ISD::XOR: {
  1407. ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
  1408. ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
  1409. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1410. assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
  1411. // Output known-0 bits are known if clear or set in both the LHS & RHS.
  1412. APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
  1413. // Output known-1 are known to be set if set in only one of the LHS, RHS.
  1414. KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
  1415. KnownZero = KnownZeroOut;
  1416. return;
  1417. }
  1418. case ISD::MUL: {
  1419. APInt Mask2 = APInt::getAllOnesValue(BitWidth);
  1420. ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
  1421. ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
  1422. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1423. assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
  1424. // If low bits are zero in either operand, output low known-0 bits.
  1425. // Also compute a conserative estimate for high known-0 bits.
  1426. // More trickiness is possible, but this is sufficient for the
  1427. // interesting case of alignment computation.
  1428. KnownOne.clear();
  1429. unsigned TrailZ = KnownZero.countTrailingOnes() +
  1430. KnownZero2.countTrailingOnes();
  1431. unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
  1432. KnownZero2.countLeadingOnes(),
  1433. BitWidth) - BitWidth;
  1434. TrailZ = std::min(TrailZ, BitWidth);
  1435. LeadZ = std::min(LeadZ, BitWidth);
  1436. KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
  1437. APInt::getHighBitsSet(BitWidth, LeadZ);
  1438. KnownZero &= Mask;
  1439. return;
  1440. }
  1441. case ISD::UDIV: {
  1442. // For the purposes of computing leading zeros we can conservatively
  1443. // treat a udiv as a logical right shift by the power of 2 known to
  1444. // be less than the denominator.
  1445. APInt AllOnes = APInt::getAllOnesValue(BitWidth);
  1446. ComputeMaskedBits(Op.getOperand(0),
  1447. AllOnes, KnownZero2, KnownOne2, Depth+1);
  1448. unsigned LeadZ = KnownZero2.countLeadingOnes();
  1449. KnownOne2.clear();
  1450. KnownZero2.clear();
  1451. ComputeMaskedBits(Op.getOperand(1),
  1452. AllOnes, KnownZero2, KnownOne2, Depth+1);
  1453. unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
  1454. if (RHSUnknownLeadingOnes != BitWidth)
  1455. LeadZ = std::min(BitWidth,
  1456. LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
  1457. KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
  1458. return;
  1459. }
  1460. case ISD::SELECT:
  1461. ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
  1462. ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
  1463. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1464. assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
  1465. // Only known if known in both the LHS and RHS.
  1466. KnownOne &= KnownOne2;
  1467. KnownZero &= KnownZero2;
  1468. return;
  1469. case ISD::SELECT_CC:
  1470. ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
  1471. ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
  1472. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1473. assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
  1474. // Only known if known in both the LHS and RHS.
  1475. KnownOne &= KnownOne2;
  1476. KnownZero &= KnownZero2;
  1477. return;
  1478. case ISD::SADDO:
  1479. case ISD::UADDO:
  1480. case ISD::SSUBO:
  1481. case ISD::USUBO:
  1482. case ISD::SMULO:
  1483. case ISD::UMULO:
  1484. if (Op.getResNo() != 1)
  1485. return;
  1486. // The boolean result conforms to getBooleanContents. Fall through.
  1487. case ISD::SETCC:
  1488. // If we know the result of a setcc has the top bits zero, use this info.
  1489. if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
  1490. BitWidth > 1)
  1491. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
  1492. return;
  1493. case ISD::SHL:
  1494. // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
  1495. if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  1496. unsigned ShAmt = SA->getZExtValue();
  1497. // If the shift count is an invalid immediate, don't do anything.
  1498. if (ShAmt >= BitWidth)
  1499. return;
  1500. ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
  1501. KnownZero, KnownOne, Depth+1);
  1502. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1503. KnownZero <<= ShAmt;
  1504. KnownOne <<= ShAmt;
  1505. // low bits known zero.
  1506. KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
  1507. }
  1508. return;
  1509. case ISD::SRL:
  1510. // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
  1511. if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  1512. unsigned ShAmt = SA->getZExtValue();
  1513. // If the shift count is an invalid immediate, don't do anything.
  1514. if (ShAmt >= BitWidth)
  1515. return;
  1516. ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
  1517. KnownZero, KnownOne, Depth+1);
  1518. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1519. KnownZero = KnownZero.lshr(ShAmt);
  1520. KnownOne = KnownOne.lshr(ShAmt);
  1521. APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
  1522. KnownZero |= HighBits; // High bits known zero.
  1523. }
  1524. return;
  1525. case ISD::SRA:
  1526. if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  1527. unsigned ShAmt = SA->getZExtValue();
  1528. // If the shift count is an invalid immediate, don't do anything.
  1529. if (ShAmt >= BitWidth)
  1530. return;
  1531. APInt InDemandedMask = (Mask << ShAmt);
  1532. // If any of the demanded bits are produced by the sign extension, we also
  1533. // demand the input sign bit.
  1534. APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
  1535. if (HighBits.getBoolValue())
  1536. InDemandedMask |= APInt::getSignBit(BitWidth);
  1537. ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
  1538. Depth+1);
  1539. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1540. KnownZero = KnownZero.lshr(ShAmt);
  1541. KnownOne = KnownOne.lshr(ShAmt);
  1542. // Handle the sign bits.
  1543. APInt SignBit = APInt::getSignBit(BitWidth);
  1544. SignBit = SignBit.lshr(ShAmt); // Adjust to where it is now in the mask.
  1545. if (KnownZero.intersects(SignBit)) {
  1546. KnownZero |= HighBits; // New bits are known zero.
  1547. } else if (KnownOne.intersects(SignBit)) {
  1548. KnownOne |= HighBits; // New bits are known one.
  1549. }
  1550. }
  1551. return;
  1552. case ISD::SIGN_EXTEND_INREG: {
  1553. MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  1554. unsigned EBits = EVT.getSizeInBits();
  1555. // Sign extension. Compute the demanded bits in the result that are not
  1556. // present in the input.
  1557. APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
  1558. APInt InSignBit = APInt::getSignBit(EBits);
  1559. APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
  1560. // If the sign extended bits are demanded, we know that the sign
  1561. // bit is demanded.
  1562. InSignBit.zext(BitWidth);
  1563. if (NewBits.getBoolValue())
  1564. InputDemandedBits |= InSignBit;
  1565. ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
  1566. KnownZero, KnownOne, Depth+1);
  1567. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1568. // If the sign bit of the input is known set or clear, then we know the
  1569. // top bits of the result.
  1570. if (KnownZero.intersects(InSignBit)) { // Input sign bit known clear
  1571. KnownZero |= NewBits;
  1572. KnownOne &= ~NewBits;
  1573. } else if (KnownOne.intersects(InSignBit)) { // Input sign bit known set
  1574. KnownOne |= NewBits;
  1575. KnownZero &= ~NewBits;
  1576. } else { // Input sign bit unknown
  1577. KnownZero &= ~NewBits;
  1578. KnownOne &= ~NewBits;
  1579. }
  1580. return;
  1581. }
  1582. case ISD::CTTZ:
  1583. case ISD::CTLZ:
  1584. case ISD::CTPOP: {
  1585. unsigned LowBits = Log2_32(BitWidth)+1;
  1586. KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
  1587. KnownOne.clear();
  1588. return;
  1589. }
  1590. case ISD::LOAD: {
  1591. if (ISD::isZEXTLoad(Op.getNode())) {
  1592. LoadSDNode *LD = cast<LoadSDNode>(Op);
  1593. MVT VT = LD->getMemoryVT();
  1594. unsigned MemBits = VT.getSizeInBits();
  1595. KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
  1596. }
  1597. return;
  1598. }
  1599. case ISD::ZERO_EXTEND: {
  1600. MVT InVT = Op.getOperand(0).getValueType();
  1601. unsigned InBits = InVT.getSizeInBits();
  1602. APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
  1603. APInt InMask = Mask;
  1604. InMask.trunc(InBits);
  1605. KnownZero.trunc(InBits);
  1606. KnownOne.trunc(InBits);
  1607. ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
  1608. KnownZero.zext(BitWidth);
  1609. KnownOne.zext(BitWidth);
  1610. KnownZero |= NewBits;
  1611. return;
  1612. }
  1613. case ISD::SIGN_EXTEND: {
  1614. MVT InVT = Op.getOperand(0).getValueType();
  1615. unsigned InBits = InVT.getSizeInBits();
  1616. APInt InSignBit = APInt::getSignBit(InBits);
  1617. APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
  1618. APInt InMask = Mask;
  1619. InMask.trunc(InBits);
  1620. // If any of the sign extended bits are demanded, we know that the sign
  1621. // bit is demanded. Temporarily set this bit in the mask for our callee.
  1622. if (NewBits.getBoolValue())
  1623. InMask |= InSignBit;
  1624. KnownZero.trunc(InBits);
  1625. KnownOne.trunc(InBits);
  1626. ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
  1627. // Note if the sign bit is known to be zero or one.
  1628. bool SignBitKnownZero = KnownZero.isNegative();
  1629. bool SignBitKnownOne = KnownOne.isNegative();
  1630. assert(!(SignBitKnownZero && SignBitKnownOne) &&
  1631. "Sign bit can't be known to be both zero and one!");
  1632. // If the sign bit wasn't actually demanded by our caller, we don't
  1633. // want it set in the KnownZero and KnownOne result values. Reset the
  1634. // mask and reapply it to the result values.
  1635. InMask = Mask;
  1636. InMask.trunc(InBits);
  1637. KnownZero &= InMask;
  1638. KnownOne &= InMask;
  1639. KnownZero.zext(BitWidth);
  1640. KnownOne.zext(BitWidth);
  1641. // If the sign bit is known zero or one, the top bits match.
  1642. if (SignBitKnownZero)
  1643. KnownZero |= NewBits;
  1644. else if (SignBitKnownOne)
  1645. KnownOne |= NewBits;
  1646. return;
  1647. }
  1648. case ISD::ANY_EXTEND: {
  1649. MVT InVT = Op.getOperand(0).getValueType();
  1650. unsigned InBits = InVT.getSizeInBits();
  1651. APInt InMask = Mask;
  1652. InMask.trunc(InBits);
  1653. KnownZero.trunc(InBits);
  1654. KnownOne.trunc(InBits);
  1655. ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
  1656. KnownZero.zext(BitWidth);
  1657. KnownOne.zext(BitWidth);
  1658. return;
  1659. }
  1660. case ISD::TRUNCATE: {
  1661. MVT InVT = Op.getOperand(0).getValueType();
  1662. unsigned InBits = InVT.getSizeInBits();
  1663. APInt InMask = Mask;
  1664. InMask.zext(InBits);
  1665. KnownZero.zext(InBits);
  1666. KnownOne.zext(InBits);
  1667. ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
  1668. assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
  1669. KnownZero.trunc(BitWidth);
  1670. KnownOne.trunc(BitWidth);
  1671. break;
  1672. }
  1673. case ISD::AssertZext: {
  1674. MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  1675. APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
  1676. ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero,
  1677. KnownOne, Depth+1);
  1678. KnownZero |= (~InMask) & Mask;
  1679. return;
  1680. }
  1681. case ISD::FGETSIGN:
  1682. // All bits are zero except the low bit.
  1683. KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
  1684. return;
  1685. case ISD::SUB: {
  1686. if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
  1687. // We know that the top bits of C-X are clear if X contains less bits
  1688. // than C (i.e. no wrap-around can happen). For example, 20-X is
  1689. // positive if we can prove that X is >= 0 and < 16.
  1690. if (CLHS->getAPIntValue().isNonNegative()) {
  1691. unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
  1692. // NLZ can't be BitWidth with no sign bit
  1693. APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
  1694. ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
  1695. Depth+1);
  1696. // If all of the MaskV bits are known to be zero, then we know the
  1697. // output top bits are zero, because we now know that the output is
  1698. // from [0-C].
  1699. if ((KnownZero2 & MaskV) == MaskV) {
  1700. unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
  1701. // Top bits known zero.
  1702. KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
  1703. }
  1704. }
  1705. }
  1706. }
  1707. // fall through
  1708. case ISD::ADD: {
  1709. // Output known-0 bits are known if clear or set in both the low clear bits
  1710. // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
  1711. // low 3 bits clear.
  1712. APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
  1713. ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
  1714. assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
  1715. unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
  1716. ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
  1717. assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
  1718. KnownZeroOut = std::min(KnownZeroOut,
  1719. KnownZero2.countTrailingOnes());
  1720. KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
  1721. return;
  1722. }
  1723. case ISD::SREM:
  1724. if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  1725. const APInt &RA = Rem->getAPIntValue();
  1726. if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
  1727. APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
  1728. APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
  1729. ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
  1730. // If the sign bit of the first operand is zero, the sign bit of
  1731. // the result is zero. If the first operand has no one bits below
  1732. // the second operand's single 1 bit, its sign will be zero.
  1733. if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
  1734. KnownZero2 |= ~LowBits;
  1735. KnownZero |= KnownZero2 & Mask;
  1736. assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
  1737. }
  1738. }
  1739. return;
  1740. case ISD::UREM: {
  1741. if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  1742. const APInt &RA = Rem->getAPIntValue();
  1743. if (RA.isPowerOf2()) {
  1744. APInt LowBits = (RA - 1);
  1745. APInt Mask2 = LowBits & Mask;
  1746. KnownZero |= ~LowBits & Mask;
  1747. ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
  1748. assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
  1749. break;
  1750. }
  1751. }
  1752. // Since the result is less than or equal to either operand, any leading
  1753. // zero bits in either operand must also exist in the result.
  1754. APInt AllOnes = APInt::getAllOnesValue(BitWidth);
  1755. ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
  1756. Depth+1);
  1757. ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
  1758. Depth+1);
  1759. uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
  1760. KnownZero2.countLeadingOnes());
  1761. KnownOne.clear();
  1762. KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
  1763. return;
  1764. }
  1765. default:
  1766. // Allow the target to implement this method for its nodes.
  1767. if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
  1768. case ISD::INTRINSIC_WO_CHAIN:
  1769. case ISD::INTRINSIC_W_CHAIN:
  1770. case ISD::INTRINSIC_VOID:
  1771. TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
  1772. }
  1773. return;
  1774. }
  1775. }
  1776. /// ComputeNumSignBits - Return the number of times the sign bit of the
  1777. /// register is replicated into the other bits. We know that at least 1 bit
  1778. /// is always equal to the sign bit (itself), but other cases can give us
  1779. /// information. For example, immediately after an "SRA X, 2", we know that
  1780. /// the top 3 bits are all equal to each other, so we return 3.
  1781. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
  1782. MVT VT = Op.getValueType();
  1783. assert(VT.isInteger() && "Invalid VT!");
  1784. unsigned VTBits = VT.getSizeInBits();
  1785. unsigned Tmp, Tmp2;
  1786. unsigned FirstAnswer = 1;
  1787. if (Depth == 6)
  1788. return 1; // Limit search depth.
  1789. switch (Op.getOpcode()) {
  1790. default: break;
  1791. case ISD::AssertSext:
  1792. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  1793. return VTBits-Tmp+1;
  1794. case ISD::AssertZext:
  1795. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  1796. return VTBits-Tmp;
  1797. case ISD::Constant: {
  1798. const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
  1799. // If negative, return # leading ones.
  1800. if (Val.isNegative())
  1801. return Val.countLeadingOnes();
  1802. // Return # leading zeros.
  1803. return Val.countLeadingZeros();
  1804. }
  1805. case ISD::SIGN_EXTEND:
  1806. Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
  1807. return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
  1808. case ISD::SIGN_EXTEND_INREG:
  1809. // Max of the input and what this extends.
  1810. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  1811. Tmp = VTBits-Tmp+1;
  1812. Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  1813. return std::max(Tmp, Tmp2);
  1814. case ISD::SRA:
  1815. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  1816. // SRA X, C -> adds C sign bits.
  1817. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  1818. Tmp += C->getZExtValue();
  1819. if (Tmp > VTBits) Tmp = VTBits;
  1820. }
  1821. return Tmp;
  1822. case ISD::SHL:
  1823. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  1824. // shl destroys sign bits.
  1825. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  1826. if (C->getZExtValue() >= VTBits || // Bad shift.
  1827. C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
  1828. return Tmp - C->getZExtValue();
  1829. }
  1830. break;
  1831. case ISD::AND:
  1832. case ISD::OR:
  1833. case ISD::XOR: // NOT is handled here.
  1834. // Logical binary ops preserve the number of sign bits at the worst.
  1835. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  1836. if (Tmp != 1) {
  1837. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
  1838. FirstAnswer = std::min(Tmp, Tmp2);
  1839. // We computed what we know about the sign bits as our first
  1840. // answer. Now proceed to the generic code that uses
  1841. // ComputeMaskedBits, and pick whichever answer is better.
  1842. }
  1843. break;
  1844. case ISD::SELECT:
  1845. Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
  1846. if (Tmp == 1) return 1; // Early out.
  1847. Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
  1848. return std::min(Tmp, Tmp2);
  1849. case ISD::SADDO:
  1850. case ISD::UADDO:
  1851. case ISD::SSUBO:
  1852. case ISD::USUBO:
  1853. case ISD::SMULO:
  1854. case ISD::UMULO:
  1855. if (Op.getResNo() != 1)
  1856. break;
  1857. // The boolean result conforms to getBooleanContents. Fall through.
  1858. case ISD::SETCC:
  1859. // If setcc returns 0/-1, all bits are sign bits.
  1860. if (TLI.getBooleanContents() ==
  1861. TargetLowering::ZeroOrNegativeOneBooleanContent)
  1862. return VTBits;
  1863. break;
  1864. case ISD::ROTL:
  1865. case ISD::ROTR:
  1866. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  1867. unsigned RotAmt = C->getZExtValue() & (VTBits-1);
  1868. // Handle rotate right by N like a rotate left by 32-N.
  1869. if (Op.getOpcode() == ISD::ROTR)
  1870. RotAmt = (VTBits-RotAmt) & (VTBits-1);
  1871. // If we aren't rotating out all of the known-in sign bits, return the
  1872. // number that are left. This handles rotl(sext(x), 1) for example.
  1873. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  1874. if (Tmp > RotAmt+1) return Tmp-RotAmt;
  1875. }
  1876. break;
  1877. case ISD::ADD:
  1878. // Add can have at most one carry bit. Thus we know that the output
  1879. // is, at worst, one more bit than the inputs.
  1880. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  1881. if (Tmp == 1) return 1; // Early out.
  1882. // Special case decrementing a value (ADD X, -1):
  1883. if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
  1884. if (CRHS->isAllOnesValue()) {
  1885. APInt KnownZero, KnownOne;
  1886. APInt Mask = APInt::getAllOnesValue(VTBits);
  1887. ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
  1888. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  1889. // sign bits set.
  1890. if ((KnownZero | APInt(VTBits, 1)) == Mask)
  1891. return VTBits;
  1892. // If we are subtracting one from a positive number, there is no carry
  1893. // out of the result.
  1894. if (KnownZero.isNegative())
  1895. return Tmp;
  1896. }
  1897. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
  1898. if (Tmp2 == 1) return 1;
  1899. return std::min(Tmp, Tmp2)-1;
  1900. break;
  1901. case ISD::SUB:
  1902. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
  1903. if (Tmp2 == 1) return 1;
  1904. // Handle NEG.
  1905. if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
  1906. if (CLHS->isNullValue()) {
  1907. APInt KnownZero, KnownOne;
  1908. APInt Mask = APInt::getAllOnesValue(VTBits);
  1909. ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
  1910. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  1911. // sign bits set.
  1912. if ((KnownZero | APInt(VTBits, 1)) == Mask)
  1913. return VTBits;
  1914. // If the input is known to be positive (the sign bit is known clear),
  1915. // the output of the NEG has the same number of sign bits as the input.
  1916. if (KnownZero.isNegative())
  1917. return Tmp2;
  1918. // Otherwise, we treat this like a SUB.
  1919. }
  1920. // Sub can have at most one carry bit. Thus we know that the output
  1921. // is, at worst, one more bit than the inputs.
  1922. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  1923. if (Tmp == 1) return 1; // Early out.
  1924. return std::min(Tmp, Tmp2)-1;
  1925. break;
  1926. case ISD::TRUNCATE:
  1927. // FIXME: it's tricky to do anything useful for this, but it is an important
  1928. // case for targets like X86.
  1929. break;
  1930. }
  1931. // Handle LOADX separately here. EXTLOAD case will fallthrough.
  1932. if (Op.getOpcode() == ISD::LOAD) {
  1933. LoadSDNode *LD = cast<LoadSDNode>(Op);
  1934. unsigned ExtType = LD->getExtensionType();
  1935. switch (ExtType) {
  1936. default: break;
  1937. case ISD::SEXTLOAD: // '17' bits known
  1938. Tmp = LD->getMemoryVT().getSizeInBits();
  1939. return VTBits-Tmp+1;
  1940. case ISD::ZEXTLOAD: // '16' bits known
  1941. Tmp = LD->getMemoryVT().getSizeInBits();
  1942. return VTBits-Tmp;
  1943. }
  1944. }
  1945. // Allow the target to implement this method for its nodes.
  1946. if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
  1947. Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
  1948. Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
  1949. Op.getOpcode() == ISD::INTRINSIC_VOID) {
  1950. unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
  1951. if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
  1952. }
  1953. // Finally, if we can prove that the top bits of the result are 0's or 1's,
  1954. // use this information.
  1955. APInt KnownZero, KnownOne;
  1956. APInt Mask = APInt::getAllOnesValue(VTBits);
  1957. ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
  1958. if (KnownZero.isNegative()) { // sign bit is 0
  1959. Mask = KnownZero;
  1960. } else if (KnownOne.isNegative()) { // sign bit is 1;
  1961. Mask = KnownOne;
  1962. } else {
  1963. // Nothing known.
  1964. return FirstAnswer;
  1965. }
  1966. // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
  1967. // the number of identical bits in the top of the input value.
  1968. Mask = ~Mask;
  1969. Mask <<= Mask.getBitWidth()-VTBits;
  1970. // Return # leading zeros. We use 'min' here in case Val was zero before
  1971. // shifting. We don't want to return '64' as for an i32 "0".
  1972. return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
  1973. }
  1974. bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
  1975. GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
  1976. if (!GA) return false;
  1977. if (GA->getOffset() != 0) return false;
  1978. GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
  1979. if (!GV) return false;
  1980. MachineModuleInfo *MMI = getMachineModuleInfo();
  1981. return MMI && MMI->hasDebugInfo();
  1982. }
  1983. /// getShuffleScalarElt - Returns the scalar element that will make up the ith
  1984. /// element of the result of the vector shuffle.
  1985. SDValue SelectionDAG::getShuffleScalarElt(const ShuffleVectorSDNode *N,
  1986. unsigned i) {
  1987. MVT VT = N->getValueType(0);
  1988. DebugLoc dl = N->getDebugLoc();
  1989. if (N->getMaskElt(i) < 0)
  1990. return getUNDEF(VT.getVectorElementType());
  1991. unsigned Index = N->getMaskElt(i);
  1992. unsigned NumElems = VT.getVectorNumElements();
  1993. SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
  1994. Index %= NumElems;
  1995. if (V.getOpcode() == ISD::BIT_CONVERT) {
  1996. V = V.getOperand(0);
  1997. MVT VVT = V.getValueType();
  1998. if (!VVT.isVector() || VVT.getVectorNumElements() != (unsigned)NumElems)
  1999. return SDValue();
  2000. }
  2001. if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
  2002. return (Index == 0) ? V.getOperand(0)
  2003. : getUNDEF(VT.getVectorElementType());
  2004. if (V.getOpcode() == ISD::BUILD_VECTOR)
  2005. return V.getOperand(Index);
  2006. if (const ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(V))
  2007. return getShuffleScalarElt(SVN, Index);
  2008. return SDValue();
  2009. }
  2010. /// getNode - Gets or creates the specified node.
  2011. ///
  2012. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT) {
  2013. FoldingSetNodeID ID;
  2014. AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
  2015. void *IP = 0;
  2016. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  2017. return SDValue(E, 0);
  2018. SDNode *N = NodeAllocator.Allocate<SDNode>();
  2019. new (N) SDNode(Opcode, DL, getVTList(VT));
  2020. CSEMap.InsertNode(N, IP);
  2021. AllNodes.push_back(N);
  2022. #ifndef NDEBUG
  2023. VerifyNode(N);
  2024. #endif
  2025. return SDValue(N, 0);
  2026. }
  2027. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
  2028. MVT VT, SDValue Operand) {
  2029. // Constant fold unary operations with an integer constant operand.
  2030. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
  2031. const APInt &Val = C->getAPIntValue();
  2032. unsigned BitWidth = VT.getSizeInBits();
  2033. switch (Opcode) {
  2034. default: break;
  2035. case ISD::SIGN_EXTEND:
  2036. return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
  2037. case ISD::ANY_EXTEND:
  2038. case ISD::ZERO_EXTEND:
  2039. case ISD::TRUNCATE:
  2040. return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
  2041. case ISD::UINT_TO_FP:
  2042. case ISD::SINT_TO_FP: {
  2043. const uint64_t zero[] = {0, 0};
  2044. // No compile time operations on this type.
  2045. if (VT==MVT::ppcf128)
  2046. break;
  2047. APFloat apf = APFloat(APInt(BitWidth, 2, zero));
  2048. (void)apf.convertFromAPInt(Val,
  2049. Opcode==ISD::SINT_TO_FP,
  2050. APFloat::rmNearestTiesToEven);
  2051. return getConstantFP(apf, VT);
  2052. }
  2053. case ISD::BIT_CONVERT:
  2054. if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
  2055. return getConstantFP(Val.bitsToFloat(), VT);
  2056. else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
  2057. return getConstantFP(Val.bitsToDouble(), VT);
  2058. break;
  2059. case ISD::BSWAP:
  2060. return getConstant(Val.byteSwap(), VT);
  2061. case ISD::CTPOP:
  2062. return getConstant(Val.countPopulation(), VT);
  2063. case ISD::CTLZ:
  2064. return getConstant(Val.countLeadingZeros(), VT);
  2065. case ISD::CTTZ:
  2066. return getConstant(Val.countTrailingZeros(), VT);
  2067. }
  2068. }
  2069. // Constant fold unary operations with a floating point constant operand.
  2070. if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
  2071. APFloat V = C->getValueAPF(); // make copy
  2072. if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
  2073. switch (Opcode) {
  2074. case ISD::FNEG:
  2075. V.changeSign();
  2076. return getConstantFP(V, VT);
  2077. case ISD::FABS:
  2078. V.clearSign();
  2079. return getConstantFP(V, VT);
  2080. case ISD::FP_ROUND:
  2081. case ISD::FP_EXTEND: {
  2082. bool ignored;
  2083. // This can return overflow, underflow, or inexact; we don't care.
  2084. // FIXME need to be more flexible about rounding mode.
  2085. (void)V.convert(*MVTToAPFloatSemantics(VT),
  2086. APFloat::rmNearestTiesToEven, &ignored);
  2087. return getConstantFP(V, VT);
  2088. }
  2089. case ISD::FP_TO_SINT:
  2090. case ISD::FP_TO_UINT: {
  2091. integerPart x[2];
  2092. bool ignored;
  2093. assert(integerPartWidth >= 64);
  2094. // FIXME need to be more flexible about rounding mode.
  2095. APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
  2096. Opcode==ISD::FP_TO_SINT,
  2097. APFloat::rmTowardZero, &ignored);
  2098. if (s==APFloat::opInvalidOp) // inexact is OK, in fact usual
  2099. break;
  2100. APInt api(VT.getSizeInBits(), 2, x);
  2101. return getConstant(api, VT);
  2102. }
  2103. case ISD::BIT_CONVERT:
  2104. if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
  2105. return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
  2106. else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
  2107. return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
  2108. break;
  2109. }
  2110. }
  2111. }
  2112. unsigned OpOpcode = Operand.getNode()->getOpcode();
  2113. switch (Opcode) {
  2114. case ISD::TokenFactor:
  2115. case ISD::MERGE_VALUES:
  2116. case ISD::CONCAT_VECTORS:
  2117. return Operand; // Factor, merge or concat of one node? No need.
  2118. case ISD::FP_ROUND: LLVM_UNREACHABLE("Invalid method to make FP_ROUND node");
  2119. case ISD::FP_EXTEND:
  2120. assert(VT.isFloatingPoint() &&
  2121. Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
  2122. if (Operand.getValueType() == VT) return Operand; // noop conversion.
  2123. if (Operand.getOpcode() == ISD::UNDEF)
  2124. return getUNDEF(VT);
  2125. break;
  2126. case ISD::SIGN_EXTEND:
  2127. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  2128. "Invalid SIGN_EXTEND!");
  2129. if (Operand.getValueType() == VT) return Operand; // noop extension
  2130. assert(Operand.getValueType().bitsLT(VT)
  2131. && "Invalid sext node, dst < src!");
  2132. if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
  2133. return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
  2134. break;
  2135. case ISD::ZERO_EXTEND:
  2136. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  2137. "Invalid ZERO_EXTEND!");
  2138. if (Operand.getValueType() == VT) return Operand; // noop extension
  2139. assert(Operand.getValueType().bitsLT(VT)
  2140. && "Invalid zext node, dst < src!");
  2141. if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
  2142. return getNode(ISD::ZERO_EXTEND, DL, VT,
  2143. Operand.getNode()->getOperand(0));
  2144. break;
  2145. case ISD::ANY_EXTEND:
  2146. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  2147. "Invalid ANY_EXTEND!");
  2148. if (Operand.getValueType() == VT) return Operand; // noop extension
  2149. assert(Operand.getValueType().bitsLT(VT)
  2150. && "Invalid anyext node, dst < src!");
  2151. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
  2152. // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
  2153. return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
  2154. break;
  2155. case ISD::TRUNCATE:
  2156. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  2157. "Invalid TRUNCATE!");
  2158. if (Operand.getValueType() == VT) return Operand; // noop truncate
  2159. assert(Operand.getValueType().bitsGT(VT)
  2160. && "Invalid truncate node, src < dst!");
  2161. if (OpOpcode == ISD::TRUNCATE)
  2162. return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
  2163. else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  2164. OpOpcode == ISD::ANY_EXTEND) {
  2165. // If the source is smaller than the dest, we still need an extend.
  2166. if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
  2167. return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
  2168. else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
  2169. return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
  2170. else
  2171. return Operand.getNode()->getOperand(0);
  2172. }
  2173. break;
  2174. case ISD::BIT_CONVERT:
  2175. // Basic sanity checking.
  2176. assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
  2177. && "Cannot BIT_CONVERT between types of different sizes!");
  2178. if (VT == Operand.getValueType()) return Operand; // noop conversion.
  2179. if (OpOpcode == ISD::BIT_CONVERT) // bitconv(bitconv(x)) -> bitconv(x)
  2180. return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
  2181. if (OpOpcode == ISD::UNDEF)
  2182. return getUNDEF(VT);
  2183. break;
  2184. case ISD::SCALAR_TO_VECTOR:
  2185. assert(VT.isVector() && !Operand.getValueType().isVector() &&
  2186. (VT.getVectorElementType() == Operand.getValueType() ||
  2187. (VT.getVectorElementType().isInteger() &&
  2188. Operand.getValueType().isInteger() &&
  2189. VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
  2190. "Illegal SCALAR_TO_VECTOR node!");
  2191. if (OpOpcode == ISD::UNDEF)
  2192. return getUNDEF(VT);
  2193. // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
  2194. if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
  2195. isa<ConstantSDNode>(Operand.getOperand(1)) &&
  2196. Operand.getConstantOperandVal(1) == 0 &&
  2197. Operand.getOperand(0).getValueType() == VT)
  2198. return Operand.getOperand(0);
  2199. break;
  2200. case ISD::FNEG:
  2201. // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
  2202. if (UnsafeFPMath && OpOpcode == ISD::FSUB)
  2203. return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
  2204. Operand.getNode()->getOperand(0));
  2205. if (OpOpcode == ISD::FNEG) // --X -> X
  2206. return Operand.getNode()->getOperand(0);
  2207. break;
  2208. case ISD::FABS:
  2209. if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
  2210. return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
  2211. break;
  2212. }
  2213. SDNode *N;
  2214. SDVTList VTs = getVTList(VT);
  2215. if (VT != MVT::Flag) { // Don't CSE flag producing nodes
  2216. FoldingSetNodeID ID;
  2217. SDValue Ops[1] = { Operand };
  2218. AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
  2219. void *IP = 0;
  2220. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  2221. return SDValue(E, 0);
  2222. N = NodeAllocator.Allocate<UnarySDNode>();
  2223. new (N) UnarySDNode(Opcode, DL, VTs, Operand);
  2224. CSEMap.InsertNode(N, IP);
  2225. } else {
  2226. N = NodeAllocator.Allocate<UnarySDNode>();
  2227. new (N) UnarySDNode(Opcode, DL, VTs, Operand);
  2228. }
  2229. AllNodes.push_back(N);
  2230. #ifndef NDEBUG
  2231. VerifyNode(N);
  2232. #endif
  2233. return SDValue(N, 0);
  2234. }
  2235. SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
  2236. MVT VT,
  2237. ConstantSDNode *Cst1,
  2238. ConstantSDNode *Cst2) {
  2239. const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
  2240. switch (Opcode) {
  2241. case ISD::ADD: return getConstant(C1 + C2, VT);
  2242. case ISD::SUB: return getConstant(C1 - C2, VT);
  2243. case ISD::MUL: return getConstant(C1 * C2, VT);
  2244. case ISD::UDIV:
  2245. if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
  2246. break;
  2247. case ISD::UREM:
  2248. if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
  2249. break;
  2250. case ISD::SDIV:
  2251. if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
  2252. break;
  2253. case ISD::SREM:
  2254. if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
  2255. break;
  2256. case ISD::AND: return getConstant(C1 & C2, VT);
  2257. case ISD::OR: return getConstant(C1 | C2, VT);
  2258. case ISD::XOR: return getConstant(C1 ^ C2, VT);
  2259. case ISD::SHL: return getConstant(C1 << C2, VT);
  2260. case ISD::SRL: return getConstant(C1.lshr(C2), VT);
  2261. case ISD::SRA: return getConstant(C1.ashr(C2), VT);
  2262. case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
  2263. case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
  2264. default: break;
  2265. }
  2266. return SDValue();
  2267. }
  2268. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
  2269. SDValue N1, SDValue N2) {
  2270. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
  2271. ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
  2272. switch (Opcode) {
  2273. default: break;
  2274. case ISD::TokenFactor:
  2275. assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
  2276. N2.getValueType() == MVT::Other && "Invalid token factor!");
  2277. // Fold trivial token factors.
  2278. if (N1.getOpcode() == ISD::EntryToken) return N2;
  2279. if (N2.getOpcode() == ISD::EntryToken) return N1;
  2280. if (N1 == N2) return N1;
  2281. break;
  2282. case ISD::CONCAT_VECTORS:
  2283. // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
  2284. // one big BUILD_VECTOR.
  2285. if (N1.getOpcode() == ISD::BUILD_VECTOR &&
  2286. N2.getOpcode() == ISD::BUILD_VECTOR) {
  2287. SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
  2288. Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
  2289. return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
  2290. }
  2291. break;
  2292. case ISD::AND:
  2293. assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
  2294. N1.getValueType() == VT && "Binary operator types must match!");
  2295. // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
  2296. // worth handling here.
  2297. if (N2C && N2C->isNullValue())
  2298. return N2;
  2299. if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
  2300. return N1;
  2301. break;
  2302. case ISD::OR:
  2303. case ISD::XOR:
  2304. case ISD::ADD:
  2305. case ISD::SUB:
  2306. assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
  2307. N1.getValueType() == VT && "Binary operator types must match!");
  2308. // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
  2309. // it's worth handling here.
  2310. if (N2C && N2C->isNullValue())
  2311. return N1;
  2312. break;
  2313. case ISD::UDIV:
  2314. case ISD::UREM:
  2315. case ISD::MULHU:
  2316. case ISD::MULHS:
  2317. case ISD::MUL:
  2318. case ISD::SDIV:
  2319. case ISD::SREM:
  2320. assert(VT.isInteger() && "This operator does not apply to FP types!");
  2321. // fall through
  2322. case ISD::FADD:
  2323. case ISD::FSUB:
  2324. case ISD::FMUL:
  2325. case ISD::FDIV:
  2326. case ISD::FREM:
  2327. if (UnsafeFPMath) {
  2328. if (Opcode == ISD::FADD) {
  2329. // 0+x --> x
  2330. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
  2331. if (CFP->getValueAPF().isZero())
  2332. return N2;
  2333. // x+0 --> x
  2334. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
  2335. if (CFP->getValueAPF().isZero())
  2336. return N1;
  2337. } else if (Opcode == ISD::FSUB) {
  2338. // x-0 --> x
  2339. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
  2340. if (CFP->getValueAPF().isZero())
  2341. return N1;
  2342. }
  2343. }
  2344. assert(N1.getValueType() == N2.getValueType() &&
  2345. N1.getValueType() == VT && "Binary operator types must match!");
  2346. break;
  2347. case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
  2348. assert(N1.getValueType() == VT &&
  2349. N1.getValueType().isFloatingPoint() &&
  2350. N2.getValueType().isFloatingPoint() &&
  2351. "Invalid FCOPYSIGN!");
  2352. break;
  2353. case ISD::SHL:
  2354. case ISD::SRA:
  2355. case ISD::SRL:
  2356. case ISD::ROTL:
  2357. case ISD::ROTR:
  2358. assert(VT == N1.getValueType() &&
  2359. "Shift operators return type must be the same as their first arg");
  2360. assert(VT.isInteger() && N2.getValueType().isInteger() &&
  2361. "Shifts only work on integers");
  2362. // Always fold shifts of i1 values so the code generator doesn't need to
  2363. // handle them. Since we know the size of the shift has to be less than the
  2364. // size of the value, the shift/rotate count is guaranteed to be zero.
  2365. if (VT == MVT::i1)
  2366. return N1;
  2367. break;
  2368. case ISD::FP_ROUND_INREG: {
  2369. MVT EVT = cast<VTSDNode>(N2)->getVT();
  2370. assert(VT == N1.getValueType() && "Not an inreg round!");
  2371. assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
  2372. "Cannot FP_ROUND_INREG integer types");
  2373. assert(EVT.bitsLE(VT) && "Not rounding down!");
  2374. if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
  2375. break;
  2376. }
  2377. case ISD::FP_ROUND:
  2378. assert(VT.isFloatingPoint() &&
  2379. N1.getValueType().isFloatingPoint() &&
  2380. VT.bitsLE(N1.getValueType()) &&
  2381. isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
  2382. if (N1.getValueType() == VT) return N1; // noop conversion.
  2383. break;
  2384. case ISD::AssertSext:
  2385. case ISD::AssertZext: {
  2386. MVT EVT = cast<VTSDNode>(N2)->getVT();
  2387. assert(VT == N1.getValueType() && "Not an inreg extend!");
  2388. assert(VT.isInteger() && EVT.isInteger() &&
  2389. "Cannot *_EXTEND_INREG FP types");
  2390. assert(EVT.bitsLE(VT) && "Not extending!");
  2391. if (VT == EVT) return N1; // noop assertion.
  2392. break;
  2393. }
  2394. case ISD::SIGN_EXTEND_INREG: {
  2395. MVT EVT = cast<VTSDNode>(N2)->getVT();
  2396. assert(VT == N1.getValueType() && "Not an inreg extend!");
  2397. assert(VT.isInteger() && EVT.isInteger() &&
  2398. "Cannot *_EXTEND_INREG FP types");
  2399. assert(EVT.bitsLE(VT) && "Not extending!");
  2400. if (EVT == VT) return N1; // Not actually extending
  2401. if (N1C) {
  2402. APInt Val = N1C->getAPIntValue();
  2403. unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
  2404. Val <<= Val.getBitWidth()-FromBits;
  2405. Val = Val.ashr(Val.getBitWidth()-FromBits);
  2406. return getConstant(Val, VT);
  2407. }
  2408. break;
  2409. }
  2410. case ISD::EXTRACT_VECTOR_ELT:
  2411. // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
  2412. if (N1.getOpcode() == ISD::UNDEF)
  2413. return getUNDEF(VT);
  2414. // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
  2415. // expanding copies of large vectors from registers.
  2416. if (N2C &&
  2417. N1.getOpcode() == ISD::CONCAT_VECTORS &&
  2418. N1.getNumOperands() > 0) {
  2419. unsigned Factor =
  2420. N1.getOperand(0).getValueType().getVectorNumElements();
  2421. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
  2422. N1.getOperand(N2C->getZExtValue() / Factor),
  2423. getConstant(N2C->getZExtValue() % Factor,
  2424. N2.getValueType()));
  2425. }
  2426. // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
  2427. // expanding large vector constants.
  2428. if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
  2429. SDValue Elt = N1.getOperand(N2C->getZExtValue());
  2430. MVT VEltTy = N1.getValueType().getVectorElementType();
  2431. if (Elt.getValueType() != VEltTy) {
  2432. // If the vector element type is not legal, the BUILD_VECTOR operands
  2433. // are promoted and implicitly truncated. Make that explicit here.
  2434. Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
  2435. }
  2436. if (VT != VEltTy) {
  2437. // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
  2438. // result is implicitly extended.
  2439. Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
  2440. }
  2441. return Elt;
  2442. }
  2443. // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
  2444. // operations are lowered to scalars.
  2445. if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
  2446. // If the indices are the same, return the inserted element.
  2447. if (N1.getOperand(2) == N2)
  2448. return N1.getOperand(1);
  2449. // If the indices are known different, extract the element from
  2450. // the original vector.
  2451. else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
  2452. isa<ConstantSDNode>(N2))
  2453. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
  2454. }
  2455. break;
  2456. case ISD::EXTRACT_ELEMENT:
  2457. assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
  2458. assert(!N1.getValueType().isVector() && !VT.isVector() &&
  2459. (N1.getValueType().isInteger() == VT.isInteger()) &&
  2460. "Wrong types for EXTRACT_ELEMENT!");
  2461. // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
  2462. // 64-bit integers into 32-bit parts. Instead of building the extract of
  2463. // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
  2464. if (N1.getOpcode() == ISD::BUILD_PAIR)
  2465. return N1.getOperand(N2C->getZExtValue());
  2466. // EXTRACT_ELEMENT of a constant int is also very common.
  2467. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
  2468. unsigned ElementSize = VT.getSizeInBits();
  2469. unsigned Shift = ElementSize * N2C->getZExtValue();
  2470. APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
  2471. return getConstant(ShiftedVal.trunc(ElementSize), VT);
  2472. }
  2473. break;
  2474. case ISD::EXTRACT_SUBVECTOR:
  2475. if (N1.getValueType() == VT) // Trivial extraction.
  2476. return N1;
  2477. break;
  2478. }
  2479. if (N1C) {
  2480. if (N2C) {
  2481. SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
  2482. if (SV.getNode()) return SV;
  2483. } else { // Cannonicalize constant to RHS if commutative
  2484. if (isCommutativeBinOp(Opcode)) {
  2485. std::swap(N1C, N2C);
  2486. std::swap(N1, N2);
  2487. }
  2488. }
  2489. }
  2490. // Constant fold FP operations.
  2491. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
  2492. ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
  2493. if (N1CFP) {
  2494. if (!N2CFP && isCommutativeBinOp(Opcode)) {
  2495. // Cannonicalize constant to RHS if commutative
  2496. std::swap(N1CFP, N2CFP);
  2497. std::swap(N1, N2);
  2498. } else if (N2CFP && VT != MVT::ppcf128) {
  2499. APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
  2500. APFloat::opStatus s;
  2501. switch (Opcode) {
  2502. case ISD::FADD:
  2503. s = V1.add(V2, APFloat::rmNearestTiesToEven);
  2504. if (s != APFloat::opInvalidOp)
  2505. return getConstantFP(V1, VT);
  2506. break;
  2507. case ISD::FSUB:
  2508. s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
  2509. if (s!=APFloat::opInvalidOp)
  2510. return getConstantFP(V1, VT);
  2511. break;
  2512. case ISD::FMUL:
  2513. s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
  2514. if (s!=APFloat::opInvalidOp)
  2515. return getConstantFP(V1, VT);
  2516. break;
  2517. case ISD::FDIV:
  2518. s = V1.divide(V2, APFloat::rmNearestTiesToEven);
  2519. if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
  2520. return getConstantFP(V1, VT);
  2521. break;
  2522. case ISD::FREM :
  2523. s = V1.mod(V2, APFloat::rmNearestTiesToEven);
  2524. if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
  2525. return getConstantFP(V1, VT);
  2526. break;
  2527. case ISD::FCOPYSIGN:
  2528. V1.copySign(V2);
  2529. return getConstantFP(V1, VT);
  2530. default: break;
  2531. }
  2532. }
  2533. }
  2534. // Canonicalize an UNDEF to the RHS, even over a constant.
  2535. if (N1.getOpcode() == ISD::UNDEF) {
  2536. if (isCommutativeBinOp(Opcode)) {
  2537. std::swap(N1, N2);
  2538. } else {
  2539. switch (Opcode) {
  2540. case ISD::FP_ROUND_INREG:
  2541. case ISD::SIGN_EXTEND_INREG:
  2542. case ISD::SUB:
  2543. case ISD::FSUB:
  2544. case ISD::FDIV:
  2545. case ISD::FREM:
  2546. case ISD::SRA:
  2547. return N1; // fold op(undef, arg2) -> undef
  2548. case ISD::UDIV:
  2549. case ISD::SDIV:
  2550. case ISD::UREM:
  2551. case ISD::SREM:
  2552. case ISD::SRL:
  2553. case ISD::SHL:
  2554. if (!VT.isVector())
  2555. return getConstant(0, VT); // fold op(undef, arg2) -> 0
  2556. // For vectors, we can't easily build an all zero vector, just return
  2557. // the LHS.
  2558. return N2;
  2559. }
  2560. }
  2561. }
  2562. // Fold a bunch of operators when the RHS is undef.
  2563. if (N2.getOpcode() == ISD::UNDEF) {
  2564. switch (Opcode) {
  2565. case ISD::XOR:
  2566. if (N1.getOpcode() == ISD::UNDEF)
  2567. // Handle undef ^ undef -> 0 special case. This is a common
  2568. // idiom (misuse).
  2569. return getConstant(0, VT);
  2570. // fallthrough
  2571. case ISD::ADD:
  2572. case ISD::ADDC:
  2573. case ISD::ADDE:
  2574. case ISD::SUB:
  2575. case ISD::UDIV:
  2576. case ISD::SDIV:
  2577. case ISD::UREM:
  2578. case ISD::SREM:
  2579. return N2; // fold op(arg1, undef) -> undef
  2580. case ISD::FADD:
  2581. case ISD::FSUB:
  2582. case ISD::FMUL:
  2583. case ISD::FDIV:
  2584. case ISD::FREM:
  2585. if (UnsafeFPMath)
  2586. return N2;
  2587. break;
  2588. case ISD::MUL:
  2589. case ISD::AND:
  2590. case ISD::SRL:
  2591. case ISD::SHL:
  2592. if (!VT.isVector())
  2593. return getConstant(0, VT); // fold op(arg1, undef) -> 0
  2594. // For vectors, we can't easily build an all zero vector, just return
  2595. // the LHS.
  2596. return N1;
  2597. case ISD::OR:
  2598. if (!VT.isVector())
  2599. return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
  2600. // For vectors, we can't easily build an all one vector, just return
  2601. // the LHS.
  2602. return N1;
  2603. case ISD::SRA:
  2604. return N1;
  2605. }
  2606. }
  2607. // Memoize this node if possible.
  2608. SDNode *N;
  2609. SDVTList VTs = getVTList(VT);
  2610. if (VT != MVT::Flag) {
  2611. SDValue Ops[] = { N1, N2 };
  2612. FoldingSetNodeID ID;
  2613. AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
  2614. void *IP = 0;
  2615. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  2616. return SDValue(E, 0);
  2617. N = NodeAllocator.Allocate<BinarySDNode>();
  2618. new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
  2619. CSEMap.InsertNode(N, IP);
  2620. } else {
  2621. N = NodeAllocator.Allocate<BinarySDNode>();
  2622. new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
  2623. }
  2624. AllNodes.push_back(N);
  2625. #ifndef NDEBUG
  2626. VerifyNode(N);
  2627. #endif
  2628. return SDValue(N, 0);
  2629. }
  2630. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
  2631. SDValue N1, SDValue N2, SDValue N3) {
  2632. // Perform various simplifications.
  2633. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
  2634. ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
  2635. switch (Opcode) {
  2636. case ISD::CONCAT_VECTORS:
  2637. // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
  2638. // one big BUILD_VECTOR.
  2639. if (N1.getOpcode() == ISD::BUILD_VECTOR &&
  2640. N2.getOpcode() == ISD::BUILD_VECTOR &&
  2641. N3.getOpcode() == ISD::BUILD_VECTOR) {
  2642. SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
  2643. Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
  2644. Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
  2645. return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
  2646. }
  2647. break;
  2648. case ISD::SETCC: {
  2649. // Use FoldSetCC to simplify SETCC's.
  2650. SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
  2651. if (Simp.getNode()) return Simp;
  2652. break;
  2653. }
  2654. case ISD::SELECT:
  2655. if (N1C) {
  2656. if (N1C->getZExtValue())
  2657. return N2; // select true, X, Y -> X
  2658. else
  2659. return N3; // select false, X, Y -> Y
  2660. }
  2661. if (N2 == N3) return N2; // select C, X, X -> X
  2662. break;
  2663. case ISD::BRCOND:
  2664. if (N2C) {
  2665. if (N2C->getZExtValue()) // Unconditional branch
  2666. return getNode(ISD::BR, DL, MVT::Other, N1, N3);
  2667. else
  2668. return N1; // Never-taken branch
  2669. }
  2670. break;
  2671. case ISD::VECTOR_SHUFFLE:
  2672. LLVM_UNREACHABLE("should use getVectorShuffle constructor!");
  2673. break;
  2674. case ISD::BIT_CONVERT:
  2675. // Fold bit_convert nodes from a type to themselves.
  2676. if (N1.getValueType() == VT)
  2677. return N1;
  2678. break;
  2679. }
  2680. // Memoize node if it doesn't produce a flag.
  2681. SDNode *N;
  2682. SDVTList VTs = getVTList(VT);
  2683. if (VT != MVT::Flag) {
  2684. SDValue Ops[] = { N1, N2, N3 };
  2685. FoldingSetNodeID ID;
  2686. AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
  2687. void *IP = 0;
  2688. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  2689. return SDValue(E, 0);
  2690. N = NodeAllocator.Allocate<TernarySDNode>();
  2691. new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
  2692. CSEMap.InsertNode(N, IP);
  2693. } else {
  2694. N = NodeAllocator.Allocate<TernarySDNode>();
  2695. new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
  2696. }
  2697. AllNodes.push_back(N);
  2698. #ifndef NDEBUG
  2699. VerifyNode(N);
  2700. #endif
  2701. return SDValue(N, 0);
  2702. }
  2703. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
  2704. SDValue N1, SDValue N2, SDValue N3,
  2705. SDValue N4) {
  2706. SDValue Ops[] = { N1, N2, N3, N4 };
  2707. return getNode(Opcode, DL, VT, Ops, 4);
  2708. }
  2709. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
  2710. SDValue N1, SDValue N2, SDValue N3,
  2711. SDValue N4, SDValue N5) {
  2712. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  2713. return getNode(Opcode, DL, VT, Ops, 5);
  2714. }
  2715. /// getMemsetValue - Vectorized representation of the memset value
  2716. /// operand.
  2717. static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG,
  2718. DebugLoc dl) {
  2719. unsigned NumBits = VT.isVector() ?
  2720. VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
  2721. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
  2722. APInt Val = APInt(NumBits, C->getZExtValue() & 255);
  2723. unsigned Shift = 8;
  2724. for (unsigned i = NumBits; i > 8; i >>= 1) {
  2725. Val = (Val << Shift) | Val;
  2726. Shift <<= 1;
  2727. }
  2728. if (VT.isInteger())
  2729. return DAG.getConstant(Val, VT);
  2730. return DAG.getConstantFP(APFloat(Val), VT);
  2731. }
  2732. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2733. Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
  2734. unsigned Shift = 8;
  2735. for (unsigned i = NumBits; i > 8; i >>= 1) {
  2736. Value = DAG.getNode(ISD::OR, dl, VT,
  2737. DAG.getNode(ISD::SHL, dl, VT, Value,
  2738. DAG.getConstant(Shift,
  2739. TLI.getShiftAmountTy())),
  2740. Value);
  2741. Shift <<= 1;
  2742. }
  2743. return Value;
  2744. }
  2745. /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
  2746. /// used when a memcpy is turned into a memset when the source is a constant
  2747. /// string ptr.
  2748. static SDValue getMemsetStringVal(MVT VT, DebugLoc dl, SelectionDAG &DAG,
  2749. const TargetLowering &TLI,
  2750. std::string &Str, unsigned Offset) {
  2751. // Handle vector with all elements zero.
  2752. if (Str.empty()) {
  2753. if (VT.isInteger())
  2754. return DAG.getConstant(0, VT);
  2755. unsigned NumElts = VT.getVectorNumElements();
  2756. MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
  2757. return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
  2758. DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
  2759. }
  2760. assert(!VT.isVector() && "Can't handle vector type here!");
  2761. unsigned NumBits = VT.getSizeInBits();
  2762. unsigned MSB = NumBits / 8;
  2763. uint64_t Val = 0;
  2764. if (TLI.isLittleEndian())
  2765. Offset = Offset + MSB - 1;
  2766. for (unsigned i = 0; i != MSB; ++i) {
  2767. Val = (Val << 8) | (unsigned char)Str[Offset];
  2768. Offset += TLI.isLittleEndian() ? -1 : 1;
  2769. }
  2770. return DAG.getConstant(Val, VT);
  2771. }
  2772. /// getMemBasePlusOffset - Returns base and offset node for the
  2773. ///
  2774. static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
  2775. SelectionDAG &DAG) {
  2776. MVT VT = Base.getValueType();
  2777. return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
  2778. VT, Base, DAG.getConstant(Offset, VT));
  2779. }
  2780. /// isMemSrcFromString - Returns true if memcpy source is a string constant.
  2781. ///
  2782. static bool isMemSrcFromString(SDValue Src, std::string &Str) {
  2783. unsigned SrcDelta = 0;
  2784. GlobalAddressSDNode *G = NULL;
  2785. if (Src.getOpcode() == ISD::GlobalAddress)
  2786. G = cast<GlobalAddressSDNode>(Src);
  2787. else if (Src.getOpcode() == ISD::ADD &&
  2788. Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
  2789. Src.getOperand(1).getOpcode() == ISD::Constant) {
  2790. G = cast<GlobalAddressSDNode>(Src.getOperand(0));
  2791. SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
  2792. }
  2793. if (!G)
  2794. return false;
  2795. GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
  2796. if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
  2797. return true;
  2798. return false;
  2799. }
  2800. /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
  2801. /// to replace the memset / memcpy is below the threshold. It also returns the
  2802. /// types of the sequence of memory ops to perform memset / memcpy.
  2803. static
  2804. bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
  2805. SDValue Dst, SDValue Src,
  2806. unsigned Limit, uint64_t Size, unsigned &Align,
  2807. std::string &Str, bool &isSrcStr,
  2808. SelectionDAG &DAG,
  2809. const TargetLowering &TLI) {
  2810. isSrcStr = isMemSrcFromString(Src, Str);
  2811. bool isSrcConst = isa<ConstantSDNode>(Src);
  2812. bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
  2813. MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr, DAG);
  2814. if (VT != MVT::iAny) {
  2815. unsigned NewAlign = (unsigned)
  2816. TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT(
  2817. *DAG.getContext()));
  2818. // If source is a string constant, this will require an unaligned load.
  2819. if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
  2820. if (Dst.getOpcode() != ISD::FrameIndex) {
  2821. // Can't change destination alignment. It requires a unaligned store.
  2822. if (AllowUnalign)
  2823. VT = MVT::iAny;
  2824. } else {
  2825. int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
  2826. MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
  2827. if (MFI->isFixedObjectIndex(FI)) {
  2828. // Can't change destination alignment. It requires a unaligned store.
  2829. if (AllowUnalign)
  2830. VT = MVT::iAny;
  2831. } else {
  2832. // Give the stack frame object a larger alignment if needed.
  2833. if (MFI->getObjectAlignment(FI) < NewAlign)
  2834. MFI->setObjectAlignment(FI, NewAlign);
  2835. Align = NewAlign;
  2836. }
  2837. }
  2838. }
  2839. }
  2840. if (VT == MVT::iAny) {
  2841. if (AllowUnalign) {
  2842. VT = MVT::i64;
  2843. } else {
  2844. switch (Align & 7) {
  2845. case 0: VT = MVT::i64; break;
  2846. case 4: VT = MVT::i32; break;
  2847. case 2: VT = MVT::i16; break;
  2848. default: VT = MVT::i8; break;
  2849. }
  2850. }
  2851. MVT LVT = MVT::i64;
  2852. while (!TLI.isTypeLegal(LVT))
  2853. LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
  2854. assert(LVT.isInteger());
  2855. if (VT.bitsGT(LVT))
  2856. VT = LVT;
  2857. }
  2858. unsigned NumMemOps = 0;
  2859. while (Size != 0) {
  2860. unsigned VTSize = VT.getSizeInBits() / 8;
  2861. while (VTSize > Size) {
  2862. // For now, only use non-vector load / store's for the left-over pieces.
  2863. if (VT.isVector()) {
  2864. VT = MVT::i64;
  2865. while (!TLI.isTypeLegal(VT))
  2866. VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
  2867. VTSize = VT.getSizeInBits() / 8;
  2868. } else {
  2869. // This can result in a type that is not legal on the target, e.g.
  2870. // 1 or 2 bytes on PPC.
  2871. VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
  2872. VTSize >>= 1;
  2873. }
  2874. }
  2875. if (++NumMemOps > Limit)
  2876. return false;
  2877. MemOps.push_back(VT);
  2878. Size -= VTSize;
  2879. }
  2880. return true;
  2881. }
  2882. static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
  2883. SDValue Chain, SDValue Dst,
  2884. SDValue Src, uint64_t Size,
  2885. unsigned Align, bool AlwaysInline,
  2886. const Value *DstSV, uint64_t DstSVOff,
  2887. const Value *SrcSV, uint64_t SrcSVOff){
  2888. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2889. // Expand memcpy to a series of load and store ops if the size operand falls
  2890. // below a certain threshold.
  2891. std::vector<MVT> MemOps;
  2892. uint64_t Limit = -1ULL;
  2893. if (!AlwaysInline)
  2894. Limit = TLI.getMaxStoresPerMemcpy();
  2895. unsigned DstAlign = Align; // Destination alignment can change.
  2896. std::string Str;
  2897. bool CopyFromStr;
  2898. if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
  2899. Str, CopyFromStr, DAG, TLI))
  2900. return SDValue();
  2901. bool isZeroStr = CopyFromStr && Str.empty();
  2902. SmallVector<SDValue, 8> OutChains;
  2903. unsigned NumMemOps = MemOps.size();
  2904. uint64_t SrcOff = 0, DstOff = 0;
  2905. for (unsigned i = 0; i < NumMemOps; i++) {
  2906. MVT VT = MemOps[i];
  2907. unsigned VTSize = VT.getSizeInBits() / 8;
  2908. SDValue Value, Store;
  2909. if (CopyFromStr && (isZeroStr || !VT.isVector())) {
  2910. // It's unlikely a store of a vector immediate can be done in a single
  2911. // instruction. It would require a load from a constantpool first.
  2912. // We also handle store a vector with all zero's.
  2913. // FIXME: Handle other cases where store of vector immediate is done in
  2914. // a single instruction.
  2915. Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
  2916. Store = DAG.getStore(Chain, dl, Value,
  2917. getMemBasePlusOffset(Dst, DstOff, DAG),
  2918. DstSV, DstSVOff + DstOff, false, DstAlign);
  2919. } else {
  2920. // The type might not be legal for the target. This should only happen
  2921. // if the type is smaller than a legal type, as on PPC, so the right
  2922. // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
  2923. // to Load/Store if NVT==VT.
  2924. // FIXME does the case above also need this?
  2925. MVT NVT = TLI.getTypeToTransformTo(VT);
  2926. assert(NVT.bitsGE(VT));
  2927. Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
  2928. getMemBasePlusOffset(Src, SrcOff, DAG),
  2929. SrcSV, SrcSVOff + SrcOff, VT, false, Align);
  2930. Store = DAG.getTruncStore(Chain, dl, Value,
  2931. getMemBasePlusOffset(Dst, DstOff, DAG),
  2932. DstSV, DstSVOff + DstOff, VT, false, DstAlign);
  2933. }
  2934. OutChains.push_back(Store);
  2935. SrcOff += VTSize;
  2936. DstOff += VTSize;
  2937. }
  2938. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  2939. &OutChains[0], OutChains.size());
  2940. }
  2941. static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
  2942. SDValue Chain, SDValue Dst,
  2943. SDValue Src, uint64_t Size,
  2944. unsigned Align, bool AlwaysInline,
  2945. const Value *DstSV, uint64_t DstSVOff,
  2946. const Value *SrcSV, uint64_t SrcSVOff){
  2947. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2948. // Expand memmove to a series of load and store ops if the size operand falls
  2949. // below a certain threshold.
  2950. std::vector<MVT> MemOps;
  2951. uint64_t Limit = -1ULL;
  2952. if (!AlwaysInline)
  2953. Limit = TLI.getMaxStoresPerMemmove();
  2954. unsigned DstAlign = Align; // Destination alignment can change.
  2955. std::string Str;
  2956. bool CopyFromStr;
  2957. if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
  2958. Str, CopyFromStr, DAG, TLI))
  2959. return SDValue();
  2960. uint64_t SrcOff = 0, DstOff = 0;
  2961. SmallVector<SDValue, 8> LoadValues;
  2962. SmallVector<SDValue, 8> LoadChains;
  2963. SmallVector<SDValue, 8> OutChains;
  2964. unsigned NumMemOps = MemOps.size();
  2965. for (unsigned i = 0; i < NumMemOps; i++) {
  2966. MVT VT = MemOps[i];
  2967. unsigned VTSize = VT.getSizeInBits() / 8;
  2968. SDValue Value, Store;
  2969. Value = DAG.getLoad(VT, dl, Chain,
  2970. getMemBasePlusOffset(Src, SrcOff, DAG),
  2971. SrcSV, SrcSVOff + SrcOff, false, Align);
  2972. LoadValues.push_back(Value);
  2973. LoadChains.push_back(Value.getValue(1));
  2974. SrcOff += VTSize;
  2975. }
  2976. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  2977. &LoadChains[0], LoadChains.size());
  2978. OutChains.clear();
  2979. for (unsigned i = 0; i < NumMemOps; i++) {
  2980. MVT VT = MemOps[i];
  2981. unsigned VTSize = VT.getSizeInBits() / 8;
  2982. SDValue Value, Store;
  2983. Store = DAG.getStore(Chain, dl, LoadValues[i],
  2984. getMemBasePlusOffset(Dst, DstOff, DAG),
  2985. DstSV, DstSVOff + DstOff, false, DstAlign);
  2986. OutChains.push_back(Store);
  2987. DstOff += VTSize;
  2988. }
  2989. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  2990. &OutChains[0], OutChains.size());
  2991. }
  2992. static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
  2993. SDValue Chain, SDValue Dst,
  2994. SDValue Src, uint64_t Size,
  2995. unsigned Align,
  2996. const Value *DstSV, uint64_t DstSVOff) {
  2997. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  2998. // Expand memset to a series of load/store ops if the size operand
  2999. // falls below a certain threshold.
  3000. std::vector<MVT> MemOps;
  3001. std::string Str;
  3002. bool CopyFromStr;
  3003. if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
  3004. Size, Align, Str, CopyFromStr, DAG, TLI))
  3005. return SDValue();
  3006. SmallVector<SDValue, 8> OutChains;
  3007. uint64_t DstOff = 0;
  3008. unsigned NumMemOps = MemOps.size();
  3009. for (unsigned i = 0; i < NumMemOps; i++) {
  3010. MVT VT = MemOps[i];
  3011. unsigned VTSize = VT.getSizeInBits() / 8;
  3012. SDValue Value = getMemsetValue(Src, VT, DAG, dl);
  3013. SDValue Store = DAG.getStore(Chain, dl, Value,
  3014. getMemBasePlusOffset(Dst, DstOff, DAG),
  3015. DstSV, DstSVOff + DstOff);
  3016. OutChains.push_back(Store);
  3017. DstOff += VTSize;
  3018. }
  3019. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  3020. &OutChains[0], OutChains.size());
  3021. }
  3022. SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
  3023. SDValue Src, SDValue Size,
  3024. unsigned Align, bool AlwaysInline,
  3025. const Value *DstSV, uint64_t DstSVOff,
  3026. const Value *SrcSV, uint64_t SrcSVOff) {
  3027. // Check to see if we should lower the memcpy to loads and stores first.
  3028. // For cases within the target-specified limits, this is the best choice.
  3029. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  3030. if (ConstantSize) {
  3031. // Memcpy with size zero? Just return the original chain.
  3032. if (ConstantSize->isNullValue())
  3033. return Chain;
  3034. SDValue Result =
  3035. getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
  3036. ConstantSize->getZExtValue(),
  3037. Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
  3038. if (Result.getNode())
  3039. return Result;
  3040. }
  3041. // Then check to see if we should lower the memcpy with target-specific
  3042. // code. If the target chooses to do this, this is the next best.
  3043. SDValue Result =
  3044. TLI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
  3045. AlwaysInline,
  3046. DstSV, DstSVOff, SrcSV, SrcSVOff);
  3047. if (Result.getNode())
  3048. return Result;
  3049. // If we really need inline code and the target declined to provide it,
  3050. // use a (potentially long) sequence of loads and stores.
  3051. if (AlwaysInline) {
  3052. assert(ConstantSize && "AlwaysInline requires a constant size!");
  3053. return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
  3054. ConstantSize->getZExtValue(), Align, true,
  3055. DstSV, DstSVOff, SrcSV, SrcSVOff);
  3056. }
  3057. // Emit a library call.
  3058. TargetLowering::ArgListTy Args;
  3059. TargetLowering::ArgListEntry Entry;
  3060. Entry.Ty = TLI.getTargetData()->getIntPtrType();
  3061. Entry.Node = Dst; Args.push_back(Entry);
  3062. Entry.Node = Src; Args.push_back(Entry);
  3063. Entry.Node = Size; Args.push_back(Entry);
  3064. // FIXME: pass in DebugLoc
  3065. std::pair<SDValue,SDValue> CallResult =
  3066. TLI.LowerCallTo(Chain, Type::VoidTy,
  3067. false, false, false, false, 0, CallingConv::C, false,
  3068. getExternalSymbol("memcpy", TLI.getPointerTy()),
  3069. Args, *this, dl);
  3070. return CallResult.second;
  3071. }
  3072. SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
  3073. SDValue Src, SDValue Size,
  3074. unsigned Align,
  3075. const Value *DstSV, uint64_t DstSVOff,
  3076. const Value *SrcSV, uint64_t SrcSVOff) {
  3077. // Check to see if we should lower the memmove to loads and stores first.
  3078. // For cases within the target-specified limits, this is the best choice.
  3079. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  3080. if (ConstantSize) {
  3081. // Memmove with size zero? Just return the original chain.
  3082. if (ConstantSize->isNullValue())
  3083. return Chain;
  3084. SDValue Result =
  3085. getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
  3086. ConstantSize->getZExtValue(),
  3087. Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
  3088. if (Result.getNode())
  3089. return Result;
  3090. }
  3091. // Then check to see if we should lower the memmove with target-specific
  3092. // code. If the target chooses to do this, this is the next best.
  3093. SDValue Result =
  3094. TLI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align,
  3095. DstSV, DstSVOff, SrcSV, SrcSVOff);
  3096. if (Result.getNode())
  3097. return Result;
  3098. // Emit a library call.
  3099. TargetLowering::ArgListTy Args;
  3100. TargetLowering::ArgListEntry Entry;
  3101. Entry.Ty = TLI.getTargetData()->getIntPtrType();
  3102. Entry.Node = Dst; Args.push_back(Entry);
  3103. Entry.Node = Src; Args.push_back(Entry);
  3104. Entry.Node = Size; Args.push_back(Entry);
  3105. // FIXME: pass in DebugLoc
  3106. std::pair<SDValue,SDValue> CallResult =
  3107. TLI.LowerCallTo(Chain, Type::VoidTy,
  3108. false, false, false, false, 0, CallingConv::C, false,
  3109. getExternalSymbol("memmove", TLI.getPointerTy()),
  3110. Args, *this, dl);
  3111. return CallResult.second;
  3112. }
  3113. SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
  3114. SDValue Src, SDValue Size,
  3115. unsigned Align,
  3116. const Value *DstSV, uint64_t DstSVOff) {
  3117. // Check to see if we should lower the memset to stores first.
  3118. // For cases within the target-specified limits, this is the best choice.
  3119. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  3120. if (ConstantSize) {
  3121. // Memset with size zero? Just return the original chain.
  3122. if (ConstantSize->isNullValue())
  3123. return Chain;
  3124. SDValue Result =
  3125. getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
  3126. Align, DstSV, DstSVOff);
  3127. if (Result.getNode())
  3128. return Result;
  3129. }
  3130. // Then check to see if we should lower the memset with target-specific
  3131. // code. If the target chooses to do this, this is the next best.
  3132. SDValue Result =
  3133. TLI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align,
  3134. DstSV, DstSVOff);
  3135. if (Result.getNode())
  3136. return Result;
  3137. // Emit a library call.
  3138. const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
  3139. TargetLowering::ArgListTy Args;
  3140. TargetLowering::ArgListEntry Entry;
  3141. Entry.Node = Dst; Entry.Ty = IntPtrTy;
  3142. Args.push_back(Entry);
  3143. // Extend or truncate the argument to be an i32 value for the call.
  3144. if (Src.getValueType().bitsGT(MVT::i32))
  3145. Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
  3146. else
  3147. Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
  3148. Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
  3149. Args.push_back(Entry);
  3150. Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
  3151. Args.push_back(Entry);
  3152. // FIXME: pass in DebugLoc
  3153. std::pair<SDValue,SDValue> CallResult =
  3154. TLI.LowerCallTo(Chain, Type::VoidTy,
  3155. false, false, false, false, 0, CallingConv::C, false,
  3156. getExternalSymbol("memset", TLI.getPointerTy()),
  3157. Args, *this, dl);
  3158. return CallResult.second;
  3159. }
  3160. SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
  3161. SDValue Chain,
  3162. SDValue Ptr, SDValue Cmp,
  3163. SDValue Swp, const Value* PtrVal,
  3164. unsigned Alignment) {
  3165. assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
  3166. assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
  3167. MVT VT = Cmp.getValueType();
  3168. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  3169. Alignment = getMVTAlignment(MemVT);
  3170. SDVTList VTs = getVTList(VT, MVT::Other);
  3171. FoldingSetNodeID ID;
  3172. ID.AddInteger(MemVT.getRawBits());
  3173. SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
  3174. AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
  3175. void* IP = 0;
  3176. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3177. return SDValue(E, 0);
  3178. SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
  3179. new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
  3180. Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
  3181. CSEMap.InsertNode(N, IP);
  3182. AllNodes.push_back(N);
  3183. return SDValue(N, 0);
  3184. }
  3185. SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
  3186. SDValue Chain,
  3187. SDValue Ptr, SDValue Val,
  3188. const Value* PtrVal,
  3189. unsigned Alignment) {
  3190. assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
  3191. Opcode == ISD::ATOMIC_LOAD_SUB ||
  3192. Opcode == ISD::ATOMIC_LOAD_AND ||
  3193. Opcode == ISD::ATOMIC_LOAD_OR ||
  3194. Opcode == ISD::ATOMIC_LOAD_XOR ||
  3195. Opcode == ISD::ATOMIC_LOAD_NAND ||
  3196. Opcode == ISD::ATOMIC_LOAD_MIN ||
  3197. Opcode == ISD::ATOMIC_LOAD_MAX ||
  3198. Opcode == ISD::ATOMIC_LOAD_UMIN ||
  3199. Opcode == ISD::ATOMIC_LOAD_UMAX ||
  3200. Opcode == ISD::ATOMIC_SWAP) &&
  3201. "Invalid Atomic Op");
  3202. MVT VT = Val.getValueType();
  3203. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  3204. Alignment = getMVTAlignment(MemVT);
  3205. SDVTList VTs = getVTList(VT, MVT::Other);
  3206. FoldingSetNodeID ID;
  3207. ID.AddInteger(MemVT.getRawBits());
  3208. SDValue Ops[] = {Chain, Ptr, Val};
  3209. AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
  3210. void* IP = 0;
  3211. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3212. return SDValue(E, 0);
  3213. SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
  3214. new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
  3215. Chain, Ptr, Val, PtrVal, Alignment);
  3216. CSEMap.InsertNode(N, IP);
  3217. AllNodes.push_back(N);
  3218. return SDValue(N, 0);
  3219. }
  3220. /// getMergeValues - Create a MERGE_VALUES node from the given operands.
  3221. /// Allowed to return something different (and simpler) if Simplify is true.
  3222. SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
  3223. DebugLoc dl) {
  3224. if (NumOps == 1)
  3225. return Ops[0];
  3226. SmallVector<MVT, 4> VTs;
  3227. VTs.reserve(NumOps);
  3228. for (unsigned i = 0; i < NumOps; ++i)
  3229. VTs.push_back(Ops[i].getValueType());
  3230. return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
  3231. Ops, NumOps);
  3232. }
  3233. SDValue
  3234. SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
  3235. const MVT *VTs, unsigned NumVTs,
  3236. const SDValue *Ops, unsigned NumOps,
  3237. MVT MemVT, const Value *srcValue, int SVOff,
  3238. unsigned Align, bool Vol,
  3239. bool ReadMem, bool WriteMem) {
  3240. return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
  3241. MemVT, srcValue, SVOff, Align, Vol,
  3242. ReadMem, WriteMem);
  3243. }
  3244. SDValue
  3245. SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
  3246. const SDValue *Ops, unsigned NumOps,
  3247. MVT MemVT, const Value *srcValue, int SVOff,
  3248. unsigned Align, bool Vol,
  3249. bool ReadMem, bool WriteMem) {
  3250. // Memoize the node unless it returns a flag.
  3251. MemIntrinsicSDNode *N;
  3252. if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
  3253. FoldingSetNodeID ID;
  3254. AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
  3255. void *IP = 0;
  3256. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3257. return SDValue(E, 0);
  3258. N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
  3259. new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
  3260. srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
  3261. CSEMap.InsertNode(N, IP);
  3262. } else {
  3263. N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
  3264. new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
  3265. srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
  3266. }
  3267. AllNodes.push_back(N);
  3268. return SDValue(N, 0);
  3269. }
  3270. SDValue
  3271. SelectionDAG::getCall(unsigned CallingConv, DebugLoc dl, bool IsVarArgs,
  3272. bool IsTailCall, bool IsInreg, SDVTList VTs,
  3273. const SDValue *Operands, unsigned NumOperands,
  3274. unsigned NumFixedArgs) {
  3275. // Do not include isTailCall in the folding set profile.
  3276. FoldingSetNodeID ID;
  3277. AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
  3278. ID.AddInteger(CallingConv);
  3279. ID.AddInteger(IsVarArgs);
  3280. void *IP = 0;
  3281. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
  3282. // Instead of including isTailCall in the folding set, we just
  3283. // set the flag of the existing node.
  3284. if (!IsTailCall)
  3285. cast<CallSDNode>(E)->setNotTailCall();
  3286. return SDValue(E, 0);
  3287. }
  3288. SDNode *N = NodeAllocator.Allocate<CallSDNode>();
  3289. new (N) CallSDNode(CallingConv, dl, IsVarArgs, IsTailCall, IsInreg,
  3290. VTs, Operands, NumOperands, NumFixedArgs);
  3291. CSEMap.InsertNode(N, IP);
  3292. AllNodes.push_back(N);
  3293. return SDValue(N, 0);
  3294. }
  3295. SDValue
  3296. SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl,
  3297. ISD::LoadExtType ExtType, MVT VT, SDValue Chain,
  3298. SDValue Ptr, SDValue Offset,
  3299. const Value *SV, int SVOffset, MVT EVT,
  3300. bool isVolatile, unsigned Alignment) {
  3301. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  3302. Alignment = getMVTAlignment(VT);
  3303. if (VT == EVT) {
  3304. ExtType = ISD::NON_EXTLOAD;
  3305. } else if (ExtType == ISD::NON_EXTLOAD) {
  3306. assert(VT == EVT && "Non-extending load from different memory type!");
  3307. } else {
  3308. // Extending load.
  3309. if (VT.isVector())
  3310. assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
  3311. "Invalid vector extload!");
  3312. else
  3313. assert(EVT.bitsLT(VT) &&
  3314. "Should only be an extending load, not truncating!");
  3315. assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
  3316. "Cannot sign/zero extend a FP/Vector load!");
  3317. assert(VT.isInteger() == EVT.isInteger() &&
  3318. "Cannot convert from FP to Int or Int -> FP!");
  3319. }
  3320. bool Indexed = AM != ISD::UNINDEXED;
  3321. assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
  3322. "Unindexed load with an offset!");
  3323. SDVTList VTs = Indexed ?
  3324. getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
  3325. SDValue Ops[] = { Chain, Ptr, Offset };
  3326. FoldingSetNodeID ID;
  3327. AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
  3328. ID.AddInteger(EVT.getRawBits());
  3329. ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
  3330. void *IP = 0;
  3331. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3332. return SDValue(E, 0);
  3333. SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
  3334. new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset,
  3335. Alignment, isVolatile);
  3336. CSEMap.InsertNode(N, IP);
  3337. AllNodes.push_back(N);
  3338. return SDValue(N, 0);
  3339. }
  3340. SDValue SelectionDAG::getLoad(MVT VT, DebugLoc dl,
  3341. SDValue Chain, SDValue Ptr,
  3342. const Value *SV, int SVOffset,
  3343. bool isVolatile, unsigned Alignment) {
  3344. SDValue Undef = getUNDEF(Ptr.getValueType());
  3345. return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
  3346. SV, SVOffset, VT, isVolatile, Alignment);
  3347. }
  3348. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, MVT VT,
  3349. SDValue Chain, SDValue Ptr,
  3350. const Value *SV,
  3351. int SVOffset, MVT EVT,
  3352. bool isVolatile, unsigned Alignment) {
  3353. SDValue Undef = getUNDEF(Ptr.getValueType());
  3354. return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
  3355. SV, SVOffset, EVT, isVolatile, Alignment);
  3356. }
  3357. SDValue
  3358. SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
  3359. SDValue Offset, ISD::MemIndexedMode AM) {
  3360. LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
  3361. assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
  3362. "Load is already a indexed load!");
  3363. return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
  3364. LD->getChain(), Base, Offset, LD->getSrcValue(),
  3365. LD->getSrcValueOffset(), LD->getMemoryVT(),
  3366. LD->isVolatile(), LD->getAlignment());
  3367. }
  3368. SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
  3369. SDValue Ptr, const Value *SV, int SVOffset,
  3370. bool isVolatile, unsigned Alignment) {
  3371. MVT VT = Val.getValueType();
  3372. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  3373. Alignment = getMVTAlignment(VT);
  3374. SDVTList VTs = getVTList(MVT::Other);
  3375. SDValue Undef = getUNDEF(Ptr.getValueType());
  3376. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  3377. FoldingSetNodeID ID;
  3378. AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
  3379. ID.AddInteger(VT.getRawBits());
  3380. ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
  3381. isVolatile, Alignment));
  3382. void *IP = 0;
  3383. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3384. return SDValue(E, 0);
  3385. SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
  3386. new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false,
  3387. VT, SV, SVOffset, Alignment, isVolatile);
  3388. CSEMap.InsertNode(N, IP);
  3389. AllNodes.push_back(N);
  3390. return SDValue(N, 0);
  3391. }
  3392. SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
  3393. SDValue Ptr, const Value *SV,
  3394. int SVOffset, MVT SVT,
  3395. bool isVolatile, unsigned Alignment) {
  3396. MVT VT = Val.getValueType();
  3397. if (VT == SVT)
  3398. return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
  3399. assert(VT.bitsGT(SVT) && "Not a truncation?");
  3400. assert(VT.isInteger() == SVT.isInteger() &&
  3401. "Can't do FP-INT conversion!");
  3402. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  3403. Alignment = getMVTAlignment(VT);
  3404. SDVTList VTs = getVTList(MVT::Other);
  3405. SDValue Undef = getUNDEF(Ptr.getValueType());
  3406. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  3407. FoldingSetNodeID ID;
  3408. AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
  3409. ID.AddInteger(SVT.getRawBits());
  3410. ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED,
  3411. isVolatile, Alignment));
  3412. void *IP = 0;
  3413. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3414. return SDValue(E, 0);
  3415. SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
  3416. new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true,
  3417. SVT, SV, SVOffset, Alignment, isVolatile);
  3418. CSEMap.InsertNode(N, IP);
  3419. AllNodes.push_back(N);
  3420. return SDValue(N, 0);
  3421. }
  3422. SDValue
  3423. SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
  3424. SDValue Offset, ISD::MemIndexedMode AM) {
  3425. StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
  3426. assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
  3427. "Store is already a indexed store!");
  3428. SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
  3429. SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
  3430. FoldingSetNodeID ID;
  3431. AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
  3432. ID.AddInteger(ST->getMemoryVT().getRawBits());
  3433. ID.AddInteger(ST->getRawSubclassData());
  3434. void *IP = 0;
  3435. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3436. return SDValue(E, 0);
  3437. SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
  3438. new (N) StoreSDNode(Ops, dl, VTs, AM,
  3439. ST->isTruncatingStore(), ST->getMemoryVT(),
  3440. ST->getSrcValue(), ST->getSrcValueOffset(),
  3441. ST->getAlignment(), ST->isVolatile());
  3442. CSEMap.InsertNode(N, IP);
  3443. AllNodes.push_back(N);
  3444. return SDValue(N, 0);
  3445. }
  3446. SDValue SelectionDAG::getVAArg(MVT VT, DebugLoc dl,
  3447. SDValue Chain, SDValue Ptr,
  3448. SDValue SV) {
  3449. SDValue Ops[] = { Chain, Ptr, SV };
  3450. return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 3);
  3451. }
  3452. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
  3453. const SDUse *Ops, unsigned NumOps) {
  3454. switch (NumOps) {
  3455. case 0: return getNode(Opcode, DL, VT);
  3456. case 1: return getNode(Opcode, DL, VT, Ops[0]);
  3457. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
  3458. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
  3459. default: break;
  3460. }
  3461. // Copy from an SDUse array into an SDValue array for use with
  3462. // the regular getNode logic.
  3463. SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
  3464. return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
  3465. }
  3466. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
  3467. const SDValue *Ops, unsigned NumOps) {
  3468. switch (NumOps) {
  3469. case 0: return getNode(Opcode, DL, VT);
  3470. case 1: return getNode(Opcode, DL, VT, Ops[0]);
  3471. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
  3472. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
  3473. default: break;
  3474. }
  3475. switch (Opcode) {
  3476. default: break;
  3477. case ISD::SELECT_CC: {
  3478. assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
  3479. assert(Ops[0].getValueType() == Ops[1].getValueType() &&
  3480. "LHS and RHS of condition must have same type!");
  3481. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  3482. "True and False arms of SelectCC must have same type!");
  3483. assert(Ops[2].getValueType() == VT &&
  3484. "select_cc node must be of same type as true and false value!");
  3485. break;
  3486. }
  3487. case ISD::BR_CC: {
  3488. assert(NumOps == 5 && "BR_CC takes 5 operands!");
  3489. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  3490. "LHS/RHS of comparison should match types!");
  3491. break;
  3492. }
  3493. }
  3494. // Memoize nodes.
  3495. SDNode *N;
  3496. SDVTList VTs = getVTList(VT);
  3497. if (VT != MVT::Flag) {
  3498. FoldingSetNodeID ID;
  3499. AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
  3500. void *IP = 0;
  3501. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3502. return SDValue(E, 0);
  3503. N = NodeAllocator.Allocate<SDNode>();
  3504. new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
  3505. CSEMap.InsertNode(N, IP);
  3506. } else {
  3507. N = NodeAllocator.Allocate<SDNode>();
  3508. new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
  3509. }
  3510. AllNodes.push_back(N);
  3511. #ifndef NDEBUG
  3512. VerifyNode(N);
  3513. #endif
  3514. return SDValue(N, 0);
  3515. }
  3516. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
  3517. const std::vector<MVT> &ResultTys,
  3518. const SDValue *Ops, unsigned NumOps) {
  3519. return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
  3520. Ops, NumOps);
  3521. }
  3522. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
  3523. const MVT *VTs, unsigned NumVTs,
  3524. const SDValue *Ops, unsigned NumOps) {
  3525. if (NumVTs == 1)
  3526. return getNode(Opcode, DL, VTs[0], Ops, NumOps);
  3527. return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
  3528. }
  3529. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
  3530. const SDValue *Ops, unsigned NumOps) {
  3531. if (VTList.NumVTs == 1)
  3532. return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
  3533. switch (Opcode) {
  3534. // FIXME: figure out how to safely handle things like
  3535. // int foo(int x) { return 1 << (x & 255); }
  3536. // int bar() { return foo(256); }
  3537. #if 0
  3538. case ISD::SRA_PARTS:
  3539. case ISD::SRL_PARTS:
  3540. case ISD::SHL_PARTS:
  3541. if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  3542. cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
  3543. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  3544. else if (N3.getOpcode() == ISD::AND)
  3545. if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
  3546. // If the and is only masking out bits that cannot effect the shift,
  3547. // eliminate the and.
  3548. unsigned NumBits = VT.getSizeInBits()*2;
  3549. if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
  3550. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  3551. }
  3552. break;
  3553. #endif
  3554. }
  3555. // Memoize the node unless it returns a flag.
  3556. SDNode *N;
  3557. if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
  3558. FoldingSetNodeID ID;
  3559. AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
  3560. void *IP = 0;
  3561. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  3562. return SDValue(E, 0);
  3563. if (NumOps == 1) {
  3564. N = NodeAllocator.Allocate<UnarySDNode>();
  3565. new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
  3566. } else if (NumOps == 2) {
  3567. N = NodeAllocator.Allocate<BinarySDNode>();
  3568. new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
  3569. } else if (NumOps == 3) {
  3570. N = NodeAllocator.Allocate<TernarySDNode>();
  3571. new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
  3572. } else {
  3573. N = NodeAllocator.Allocate<SDNode>();
  3574. new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
  3575. }
  3576. CSEMap.InsertNode(N, IP);
  3577. } else {
  3578. if (NumOps == 1) {
  3579. N = NodeAllocator.Allocate<UnarySDNode>();
  3580. new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
  3581. } else if (NumOps == 2) {
  3582. N = NodeAllocator.Allocate<BinarySDNode>();
  3583. new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
  3584. } else if (NumOps == 3) {
  3585. N = NodeAllocator.Allocate<TernarySDNode>();
  3586. new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
  3587. } else {
  3588. N = NodeAllocator.Allocate<SDNode>();
  3589. new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
  3590. }
  3591. }
  3592. AllNodes.push_back(N);
  3593. #ifndef NDEBUG
  3594. VerifyNode(N);
  3595. #endif
  3596. return SDValue(N, 0);
  3597. }
  3598. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
  3599. return getNode(Opcode, DL, VTList, 0, 0);
  3600. }
  3601. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
  3602. SDValue N1) {
  3603. SDValue Ops[] = { N1 };
  3604. return getNode(Opcode, DL, VTList, Ops, 1);
  3605. }
  3606. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
  3607. SDValue N1, SDValue N2) {
  3608. SDValue Ops[] = { N1, N2 };
  3609. return getNode(Opcode, DL, VTList, Ops, 2);
  3610. }
  3611. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
  3612. SDValue N1, SDValue N2, SDValue N3) {
  3613. SDValue Ops[] = { N1, N2, N3 };
  3614. return getNode(Opcode, DL, VTList, Ops, 3);
  3615. }
  3616. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
  3617. SDValue N1, SDValue N2, SDValue N3,
  3618. SDValue N4) {
  3619. SDValue Ops[] = { N1, N2, N3, N4 };
  3620. return getNode(Opcode, DL, VTList, Ops, 4);
  3621. }
  3622. SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
  3623. SDValue N1, SDValue N2, SDValue N3,
  3624. SDValue N4, SDValue N5) {
  3625. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  3626. return getNode(Opcode, DL, VTList, Ops, 5);
  3627. }
  3628. SDVTList SelectionDAG::getVTList(MVT VT) {
  3629. return makeVTList(SDNode::getValueTypeList(VT), 1);
  3630. }
  3631. SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
  3632. for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
  3633. E = VTList.rend(); I != E; ++I)
  3634. if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
  3635. return *I;
  3636. MVT *Array = Allocator.Allocate<MVT>(2);
  3637. Array[0] = VT1;
  3638. Array[1] = VT2;
  3639. SDVTList Result = makeVTList(Array, 2);
  3640. VTList.push_back(Result);
  3641. return Result;
  3642. }
  3643. SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
  3644. for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
  3645. E = VTList.rend(); I != E; ++I)
  3646. if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
  3647. I->VTs[2] == VT3)
  3648. return *I;
  3649. MVT *Array = Allocator.Allocate<MVT>(3);
  3650. Array[0] = VT1;
  3651. Array[1] = VT2;
  3652. Array[2] = VT3;
  3653. SDVTList Result = makeVTList(Array, 3);
  3654. VTList.push_back(Result);
  3655. return Result;
  3656. }
  3657. SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) {
  3658. for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
  3659. E = VTList.rend(); I != E; ++I)
  3660. if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
  3661. I->VTs[2] == VT3 && I->VTs[3] == VT4)
  3662. return *I;
  3663. MVT *Array = Allocator.Allocate<MVT>(3);
  3664. Array[0] = VT1;
  3665. Array[1] = VT2;
  3666. Array[2] = VT3;
  3667. Array[3] = VT4;
  3668. SDVTList Result = makeVTList(Array, 4);
  3669. VTList.push_back(Result);
  3670. return Result;
  3671. }
  3672. SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
  3673. switch (NumVTs) {
  3674. case 0: LLVM_UNREACHABLE("Cannot have nodes without results!");
  3675. case 1: return getVTList(VTs[0]);
  3676. case 2: return getVTList(VTs[0], VTs[1]);
  3677. case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
  3678. default: break;
  3679. }
  3680. for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
  3681. E = VTList.rend(); I != E; ++I) {
  3682. if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
  3683. continue;
  3684. bool NoMatch = false;
  3685. for (unsigned i = 2; i != NumVTs; ++i)
  3686. if (VTs[i] != I->VTs[i]) {
  3687. NoMatch = true;
  3688. break;
  3689. }
  3690. if (!NoMatch)
  3691. return *I;
  3692. }
  3693. MVT *Array = Allocator.Allocate<MVT>(NumVTs);
  3694. std::copy(VTs, VTs+NumVTs, Array);
  3695. SDVTList Result = makeVTList(Array, NumVTs);
  3696. VTList.push_back(Result);
  3697. return Result;
  3698. }
  3699. /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
  3700. /// specified operands. If the resultant node already exists in the DAG,
  3701. /// this does not modify the specified node, instead it returns the node that
  3702. /// already exists. If the resultant node does not exist in the DAG, the
  3703. /// input node is returned. As a degenerate case, if you specify the same
  3704. /// input operands as the node already has, the input node is returned.
  3705. SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
  3706. SDNode *N = InN.getNode();
  3707. assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
  3708. // Check to see if there is no change.
  3709. if (Op == N->getOperand(0)) return InN;
  3710. // See if the modified node already exists.
  3711. void *InsertPos = 0;
  3712. if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
  3713. return SDValue(Existing, InN.getResNo());
  3714. // Nope it doesn't. Remove the node from its current place in the maps.
  3715. if (InsertPos)
  3716. if (!RemoveNodeFromCSEMaps(N))
  3717. InsertPos = 0;
  3718. // Now we update the operands.
  3719. N->OperandList[0].set(Op);
  3720. // If this gets put into a CSE map, add it.
  3721. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  3722. return InN;
  3723. }
  3724. SDValue SelectionDAG::
  3725. UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
  3726. SDNode *N = InN.getNode();
  3727. assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
  3728. // Check to see if there is no change.
  3729. if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
  3730. return InN; // No operands changed, just return the input node.
  3731. // See if the modified node already exists.
  3732. void *InsertPos = 0;
  3733. if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
  3734. return SDValue(Existing, InN.getResNo());
  3735. // Nope it doesn't. Remove the node from its current place in the maps.
  3736. if (InsertPos)
  3737. if (!RemoveNodeFromCSEMaps(N))
  3738. InsertPos = 0;
  3739. // Now we update the operands.
  3740. if (N->OperandList[0] != Op1)
  3741. N->OperandList[0].set(Op1);
  3742. if (N->OperandList[1] != Op2)
  3743. N->OperandList[1].set(Op2);
  3744. // If this gets put into a CSE map, add it.
  3745. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  3746. return InN;
  3747. }
  3748. SDValue SelectionDAG::
  3749. UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
  3750. SDValue Ops[] = { Op1, Op2, Op3 };
  3751. return UpdateNodeOperands(N, Ops, 3);
  3752. }
  3753. SDValue SelectionDAG::
  3754. UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
  3755. SDValue Op3, SDValue Op4) {
  3756. SDValue Ops[] = { Op1, Op2, Op3, Op4 };
  3757. return UpdateNodeOperands(N, Ops, 4);
  3758. }
  3759. SDValue SelectionDAG::
  3760. UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
  3761. SDValue Op3, SDValue Op4, SDValue Op5) {
  3762. SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
  3763. return UpdateNodeOperands(N, Ops, 5);
  3764. }
  3765. SDValue SelectionDAG::
  3766. UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
  3767. SDNode *N = InN.getNode();
  3768. assert(N->getNumOperands() == NumOps &&
  3769. "Update with wrong number of operands");
  3770. // Check to see if there is no change.
  3771. bool AnyChange = false;
  3772. for (unsigned i = 0; i != NumOps; ++i) {
  3773. if (Ops[i] != N->getOperand(i)) {
  3774. AnyChange = true;
  3775. break;
  3776. }
  3777. }
  3778. // No operands changed, just return the input node.
  3779. if (!AnyChange) return InN;
  3780. // See if the modified node already exists.
  3781. void *InsertPos = 0;
  3782. if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
  3783. return SDValue(Existing, InN.getResNo());
  3784. // Nope it doesn't. Remove the node from its current place in the maps.
  3785. if (InsertPos)
  3786. if (!RemoveNodeFromCSEMaps(N))
  3787. InsertPos = 0;
  3788. // Now we update the operands.
  3789. for (unsigned i = 0; i != NumOps; ++i)
  3790. if (N->OperandList[i] != Ops[i])
  3791. N->OperandList[i].set(Ops[i]);
  3792. // If this gets put into a CSE map, add it.
  3793. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  3794. return InN;
  3795. }
  3796. /// DropOperands - Release the operands and set this node to have
  3797. /// zero operands.
  3798. void SDNode::DropOperands() {
  3799. // Unlike the code in MorphNodeTo that does this, we don't need to
  3800. // watch for dead nodes here.
  3801. for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
  3802. SDUse &Use = *I++;
  3803. Use.set(SDValue());
  3804. }
  3805. }
  3806. /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
  3807. /// machine opcode.
  3808. ///
  3809. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3810. MVT VT) {
  3811. SDVTList VTs = getVTList(VT);
  3812. return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
  3813. }
  3814. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3815. MVT VT, SDValue Op1) {
  3816. SDVTList VTs = getVTList(VT);
  3817. SDValue Ops[] = { Op1 };
  3818. return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
  3819. }
  3820. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3821. MVT VT, SDValue Op1,
  3822. SDValue Op2) {
  3823. SDVTList VTs = getVTList(VT);
  3824. SDValue Ops[] = { Op1, Op2 };
  3825. return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
  3826. }
  3827. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3828. MVT VT, SDValue Op1,
  3829. SDValue Op2, SDValue Op3) {
  3830. SDVTList VTs = getVTList(VT);
  3831. SDValue Ops[] = { Op1, Op2, Op3 };
  3832. return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
  3833. }
  3834. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3835. MVT VT, const SDValue *Ops,
  3836. unsigned NumOps) {
  3837. SDVTList VTs = getVTList(VT);
  3838. return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
  3839. }
  3840. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3841. MVT VT1, MVT VT2, const SDValue *Ops,
  3842. unsigned NumOps) {
  3843. SDVTList VTs = getVTList(VT1, VT2);
  3844. return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
  3845. }
  3846. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3847. MVT VT1, MVT VT2) {
  3848. SDVTList VTs = getVTList(VT1, VT2);
  3849. return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
  3850. }
  3851. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3852. MVT VT1, MVT VT2, MVT VT3,
  3853. const SDValue *Ops, unsigned NumOps) {
  3854. SDVTList VTs = getVTList(VT1, VT2, VT3);
  3855. return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
  3856. }
  3857. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3858. MVT VT1, MVT VT2, MVT VT3, MVT VT4,
  3859. const SDValue *Ops, unsigned NumOps) {
  3860. SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
  3861. return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
  3862. }
  3863. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3864. MVT VT1, MVT VT2,
  3865. SDValue Op1) {
  3866. SDVTList VTs = getVTList(VT1, VT2);
  3867. SDValue Ops[] = { Op1 };
  3868. return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
  3869. }
  3870. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3871. MVT VT1, MVT VT2,
  3872. SDValue Op1, SDValue Op2) {
  3873. SDVTList VTs = getVTList(VT1, VT2);
  3874. SDValue Ops[] = { Op1, Op2 };
  3875. return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
  3876. }
  3877. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3878. MVT VT1, MVT VT2,
  3879. SDValue Op1, SDValue Op2,
  3880. SDValue Op3) {
  3881. SDVTList VTs = getVTList(VT1, VT2);
  3882. SDValue Ops[] = { Op1, Op2, Op3 };
  3883. return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
  3884. }
  3885. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3886. MVT VT1, MVT VT2, MVT VT3,
  3887. SDValue Op1, SDValue Op2,
  3888. SDValue Op3) {
  3889. SDVTList VTs = getVTList(VT1, VT2, VT3);
  3890. SDValue Ops[] = { Op1, Op2, Op3 };
  3891. return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
  3892. }
  3893. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  3894. SDVTList VTs, const SDValue *Ops,
  3895. unsigned NumOps) {
  3896. return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
  3897. }
  3898. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3899. MVT VT) {
  3900. SDVTList VTs = getVTList(VT);
  3901. return MorphNodeTo(N, Opc, VTs, 0, 0);
  3902. }
  3903. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3904. MVT VT, SDValue Op1) {
  3905. SDVTList VTs = getVTList(VT);
  3906. SDValue Ops[] = { Op1 };
  3907. return MorphNodeTo(N, Opc, VTs, Ops, 1);
  3908. }
  3909. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3910. MVT VT, SDValue Op1,
  3911. SDValue Op2) {
  3912. SDVTList VTs = getVTList(VT);
  3913. SDValue Ops[] = { Op1, Op2 };
  3914. return MorphNodeTo(N, Opc, VTs, Ops, 2);
  3915. }
  3916. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3917. MVT VT, SDValue Op1,
  3918. SDValue Op2, SDValue Op3) {
  3919. SDVTList VTs = getVTList(VT);
  3920. SDValue Ops[] = { Op1, Op2, Op3 };
  3921. return MorphNodeTo(N, Opc, VTs, Ops, 3);
  3922. }
  3923. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3924. MVT VT, const SDValue *Ops,
  3925. unsigned NumOps) {
  3926. SDVTList VTs = getVTList(VT);
  3927. return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
  3928. }
  3929. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3930. MVT VT1, MVT VT2, const SDValue *Ops,
  3931. unsigned NumOps) {
  3932. SDVTList VTs = getVTList(VT1, VT2);
  3933. return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
  3934. }
  3935. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3936. MVT VT1, MVT VT2) {
  3937. SDVTList VTs = getVTList(VT1, VT2);
  3938. return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
  3939. }
  3940. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3941. MVT VT1, MVT VT2, MVT VT3,
  3942. const SDValue *Ops, unsigned NumOps) {
  3943. SDVTList VTs = getVTList(VT1, VT2, VT3);
  3944. return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
  3945. }
  3946. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3947. MVT VT1, MVT VT2,
  3948. SDValue Op1) {
  3949. SDVTList VTs = getVTList(VT1, VT2);
  3950. SDValue Ops[] = { Op1 };
  3951. return MorphNodeTo(N, Opc, VTs, Ops, 1);
  3952. }
  3953. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3954. MVT VT1, MVT VT2,
  3955. SDValue Op1, SDValue Op2) {
  3956. SDVTList VTs = getVTList(VT1, VT2);
  3957. SDValue Ops[] = { Op1, Op2 };
  3958. return MorphNodeTo(N, Opc, VTs, Ops, 2);
  3959. }
  3960. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3961. MVT VT1, MVT VT2,
  3962. SDValue Op1, SDValue Op2,
  3963. SDValue Op3) {
  3964. SDVTList VTs = getVTList(VT1, VT2);
  3965. SDValue Ops[] = { Op1, Op2, Op3 };
  3966. return MorphNodeTo(N, Opc, VTs, Ops, 3);
  3967. }
  3968. /// MorphNodeTo - These *mutate* the specified node to have the specified
  3969. /// return type, opcode, and operands.
  3970. ///
  3971. /// Note that MorphNodeTo returns the resultant node. If there is already a
  3972. /// node of the specified opcode and operands, it returns that node instead of
  3973. /// the current one. Note that the DebugLoc need not be the same.
  3974. ///
  3975. /// Using MorphNodeTo is faster than creating a new node and swapping it in
  3976. /// with ReplaceAllUsesWith both because it often avoids allocating a new
  3977. /// node, and because it doesn't require CSE recalculation for any of
  3978. /// the node's users.
  3979. ///
  3980. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  3981. SDVTList VTs, const SDValue *Ops,
  3982. unsigned NumOps) {
  3983. // If an identical node already exists, use it.
  3984. void *IP = 0;
  3985. if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
  3986. FoldingSetNodeID ID;
  3987. AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
  3988. if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
  3989. return ON;
  3990. }
  3991. if (!RemoveNodeFromCSEMaps(N))
  3992. IP = 0;
  3993. // Start the morphing.
  3994. N->NodeType = Opc;
  3995. N->ValueList = VTs.VTs;
  3996. N->NumValues = VTs.NumVTs;
  3997. // Clear the operands list, updating used nodes to remove this from their
  3998. // use list. Keep track of any operands that become dead as a result.
  3999. SmallPtrSet<SDNode*, 16> DeadNodeSet;
  4000. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  4001. SDUse &Use = *I++;
  4002. SDNode *Used = Use.getNode();
  4003. Use.set(SDValue());
  4004. if (Used->use_empty())
  4005. DeadNodeSet.insert(Used);
  4006. }
  4007. // If NumOps is larger than the # of operands we currently have, reallocate
  4008. // the operand list.
  4009. if (NumOps > N->NumOperands) {
  4010. if (N->OperandsNeedDelete)
  4011. delete[] N->OperandList;
  4012. if (N->isMachineOpcode()) {
  4013. // We're creating a final node that will live unmorphed for the
  4014. // remainder of the current SelectionDAG iteration, so we can allocate
  4015. // the operands directly out of a pool with no recycling metadata.
  4016. N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
  4017. N->OperandsNeedDelete = false;
  4018. } else {
  4019. N->OperandList = new SDUse[NumOps];
  4020. N->OperandsNeedDelete = true;
  4021. }
  4022. }
  4023. // Assign the new operands.
  4024. N->NumOperands = NumOps;
  4025. for (unsigned i = 0, e = NumOps; i != e; ++i) {
  4026. N->OperandList[i].setUser(N);
  4027. N->OperandList[i].setInitial(Ops[i]);
  4028. }
  4029. // Delete any nodes that are still dead after adding the uses for the
  4030. // new operands.
  4031. SmallVector<SDNode *, 16> DeadNodes;
  4032. for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
  4033. E = DeadNodeSet.end(); I != E; ++I)
  4034. if ((*I)->use_empty())
  4035. DeadNodes.push_back(*I);
  4036. RemoveDeadNodes(DeadNodes);
  4037. if (IP)
  4038. CSEMap.InsertNode(N, IP); // Memoize the new node.
  4039. return N;
  4040. }
  4041. /// getTargetNode - These are used for target selectors to create a new node
  4042. /// with specified return type(s), target opcode, and operands.
  4043. ///
  4044. /// Note that getTargetNode returns the resultant node. If there is already a
  4045. /// node of the specified opcode and operands, it returns that node instead of
  4046. /// the current one.
  4047. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT) {
  4048. return getNode(~Opcode, dl, VT).getNode();
  4049. }
  4050. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
  4051. SDValue Op1) {
  4052. return getNode(~Opcode, dl, VT, Op1).getNode();
  4053. }
  4054. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
  4055. SDValue Op1, SDValue Op2) {
  4056. return getNode(~Opcode, dl, VT, Op1, Op2).getNode();
  4057. }
  4058. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
  4059. SDValue Op1, SDValue Op2,
  4060. SDValue Op3) {
  4061. return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode();
  4062. }
  4063. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
  4064. const SDValue *Ops, unsigned NumOps) {
  4065. return getNode(~Opcode, dl, VT, Ops, NumOps).getNode();
  4066. }
  4067. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
  4068. MVT VT1, MVT VT2) {
  4069. SDVTList VTs = getVTList(VT1, VT2);
  4070. SDValue Op;
  4071. return getNode(~Opcode, dl, VTs, &Op, 0).getNode();
  4072. }
  4073. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
  4074. MVT VT2, SDValue Op1) {
  4075. SDVTList VTs = getVTList(VT1, VT2);
  4076. return getNode(~Opcode, dl, VTs, &Op1, 1).getNode();
  4077. }
  4078. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
  4079. MVT VT2, SDValue Op1,
  4080. SDValue Op2) {
  4081. SDVTList VTs = getVTList(VT1, VT2);
  4082. SDValue Ops[] = { Op1, Op2 };
  4083. return getNode(~Opcode, dl, VTs, Ops, 2).getNode();
  4084. }
  4085. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
  4086. MVT VT2, SDValue Op1,
  4087. SDValue Op2, SDValue Op3) {
  4088. SDVTList VTs = getVTList(VT1, VT2);
  4089. SDValue Ops[] = { Op1, Op2, Op3 };
  4090. return getNode(~Opcode, dl, VTs, Ops, 3).getNode();
  4091. }
  4092. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
  4093. MVT VT1, MVT VT2,
  4094. const SDValue *Ops, unsigned NumOps) {
  4095. SDVTList VTs = getVTList(VT1, VT2);
  4096. return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
  4097. }
  4098. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
  4099. MVT VT1, MVT VT2, MVT VT3,
  4100. SDValue Op1, SDValue Op2) {
  4101. SDVTList VTs = getVTList(VT1, VT2, VT3);
  4102. SDValue Ops[] = { Op1, Op2 };
  4103. return getNode(~Opcode, dl, VTs, Ops, 2).getNode();
  4104. }
  4105. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
  4106. MVT VT1, MVT VT2, MVT VT3,
  4107. SDValue Op1, SDValue Op2,
  4108. SDValue Op3) {
  4109. SDVTList VTs = getVTList(VT1, VT2, VT3);
  4110. SDValue Ops[] = { Op1, Op2, Op3 };
  4111. return getNode(~Opcode, dl, VTs, Ops, 3).getNode();
  4112. }
  4113. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
  4114. MVT VT1, MVT VT2, MVT VT3,
  4115. const SDValue *Ops, unsigned NumOps) {
  4116. SDVTList VTs = getVTList(VT1, VT2, VT3);
  4117. return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
  4118. }
  4119. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
  4120. MVT VT2, MVT VT3, MVT VT4,
  4121. const SDValue *Ops, unsigned NumOps) {
  4122. SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
  4123. return getNode(~Opcode, dl, VTs, Ops, NumOps).getNode();
  4124. }
  4125. SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
  4126. const std::vector<MVT> &ResultTys,
  4127. const SDValue *Ops, unsigned NumOps) {
  4128. return getNode(~Opcode, dl, ResultTys, Ops, NumOps).getNode();
  4129. }
  4130. /// getNodeIfExists - Get the specified node if it's already available, or
  4131. /// else return NULL.
  4132. SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
  4133. const SDValue *Ops, unsigned NumOps) {
  4134. if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
  4135. FoldingSetNodeID ID;
  4136. AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
  4137. void *IP = 0;
  4138. if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
  4139. return E;
  4140. }
  4141. return NULL;
  4142. }
  4143. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  4144. /// This can cause recursive merging of nodes in the DAG.
  4145. ///
  4146. /// This version assumes From has a single result value.
  4147. ///
  4148. void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
  4149. DAGUpdateListener *UpdateListener) {
  4150. SDNode *From = FromN.getNode();
  4151. assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
  4152. "Cannot replace with this method!");
  4153. assert(From != To.getNode() && "Cannot replace uses of with self");
  4154. // Iterate over all the existing uses of From. New uses will be added
  4155. // to the beginning of the use list, which we avoid visiting.
  4156. // This specifically avoids visiting uses of From that arise while the
  4157. // replacement is happening, because any such uses would be the result
  4158. // of CSE: If an existing node looks like From after one of its operands
  4159. // is replaced by To, we don't want to replace of all its users with To
  4160. // too. See PR3018 for more info.
  4161. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  4162. while (UI != UE) {
  4163. SDNode *User = *UI;
  4164. // This node is about to morph, remove its old self from the CSE maps.
  4165. RemoveNodeFromCSEMaps(User);
  4166. // A user can appear in a use list multiple times, and when this
  4167. // happens the uses are usually next to each other in the list.
  4168. // To help reduce the number of CSE recomputations, process all
  4169. // the uses of this user that we can find this way.
  4170. do {
  4171. SDUse &Use = UI.getUse();
  4172. ++UI;
  4173. Use.set(To);
  4174. } while (UI != UE && *UI == User);
  4175. // Now that we have modified User, add it back to the CSE maps. If it
  4176. // already exists there, recursively merge the results together.
  4177. AddModifiedNodeToCSEMaps(User, UpdateListener);
  4178. }
  4179. }
  4180. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  4181. /// This can cause recursive merging of nodes in the DAG.
  4182. ///
  4183. /// This version assumes that for each value of From, there is a
  4184. /// corresponding value in To in the same position with the same type.
  4185. ///
  4186. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
  4187. DAGUpdateListener *UpdateListener) {
  4188. #ifndef NDEBUG
  4189. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  4190. assert((!From->hasAnyUseOfValue(i) ||
  4191. From->getValueType(i) == To->getValueType(i)) &&
  4192. "Cannot use this version of ReplaceAllUsesWith!");
  4193. #endif
  4194. // Handle the trivial case.
  4195. if (From == To)
  4196. return;
  4197. // Iterate over just the existing users of From. See the comments in
  4198. // the ReplaceAllUsesWith above.
  4199. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  4200. while (UI != UE) {
  4201. SDNode *User = *UI;
  4202. // This node is about to morph, remove its old self from the CSE maps.
  4203. RemoveNodeFromCSEMaps(User);
  4204. // A user can appear in a use list multiple times, and when this
  4205. // happens the uses are usually next to each other in the list.
  4206. // To help reduce the number of CSE recomputations, process all
  4207. // the uses of this user that we can find this way.
  4208. do {
  4209. SDUse &Use = UI.getUse();
  4210. ++UI;
  4211. Use.setNode(To);
  4212. } while (UI != UE && *UI == User);
  4213. // Now that we have modified User, add it back to the CSE maps. If it
  4214. // already exists there, recursively merge the results together.
  4215. AddModifiedNodeToCSEMaps(User, UpdateListener);
  4216. }
  4217. }
  4218. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  4219. /// This can cause recursive merging of nodes in the DAG.
  4220. ///
  4221. /// This version can replace From with any result values. To must match the
  4222. /// number and types of values returned by From.
  4223. void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
  4224. const SDValue *To,
  4225. DAGUpdateListener *UpdateListener) {
  4226. if (From->getNumValues() == 1) // Handle the simple case efficiently.
  4227. return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
  4228. // Iterate over just the existing users of From. See the comments in
  4229. // the ReplaceAllUsesWith above.
  4230. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  4231. while (UI != UE) {
  4232. SDNode *User = *UI;
  4233. // This node is about to morph, remove its old self from the CSE maps.
  4234. RemoveNodeFromCSEMaps(User);
  4235. // A user can appear in a use list multiple times, and when this
  4236. // happens the uses are usually next to each other in the list.
  4237. // To help reduce the number of CSE recomputations, process all
  4238. // the uses of this user that we can find this way.
  4239. do {
  4240. SDUse &Use = UI.getUse();
  4241. const SDValue &ToOp = To[Use.getResNo()];
  4242. ++UI;
  4243. Use.set(ToOp);
  4244. } while (UI != UE && *UI == User);
  4245. // Now that we have modified User, add it back to the CSE maps. If it
  4246. // already exists there, recursively merge the results together.
  4247. AddModifiedNodeToCSEMaps(User, UpdateListener);
  4248. }
  4249. }
  4250. /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
  4251. /// uses of other values produced by From.getNode() alone. The Deleted
  4252. /// vector is handled the same way as for ReplaceAllUsesWith.
  4253. void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
  4254. DAGUpdateListener *UpdateListener){
  4255. // Handle the really simple, really trivial case efficiently.
  4256. if (From == To) return;
  4257. // Handle the simple, trivial, case efficiently.
  4258. if (From.getNode()->getNumValues() == 1) {
  4259. ReplaceAllUsesWith(From, To, UpdateListener);
  4260. return;
  4261. }
  4262. // Iterate over just the existing users of From. See the comments in
  4263. // the ReplaceAllUsesWith above.
  4264. SDNode::use_iterator UI = From.getNode()->use_begin(),
  4265. UE = From.getNode()->use_end();
  4266. while (UI != UE) {
  4267. SDNode *User = *UI;
  4268. bool UserRemovedFromCSEMaps = false;
  4269. // A user can appear in a use list multiple times, and when this
  4270. // happens the uses are usually next to each other in the list.
  4271. // To help reduce the number of CSE recomputations, process all
  4272. // the uses of this user that we can find this way.
  4273. do {
  4274. SDUse &Use = UI.getUse();
  4275. // Skip uses of different values from the same node.
  4276. if (Use.getResNo() != From.getResNo()) {
  4277. ++UI;
  4278. continue;
  4279. }
  4280. // If this node hasn't been modified yet, it's still in the CSE maps,
  4281. // so remove its old self from the CSE maps.
  4282. if (!UserRemovedFromCSEMaps) {
  4283. RemoveNodeFromCSEMaps(User);
  4284. UserRemovedFromCSEMaps = true;
  4285. }
  4286. ++UI;
  4287. Use.set(To);
  4288. } while (UI != UE && *UI == User);
  4289. // We are iterating over all uses of the From node, so if a use
  4290. // doesn't use the specific value, no changes are made.
  4291. if (!UserRemovedFromCSEMaps)
  4292. continue;
  4293. // Now that we have modified User, add it back to the CSE maps. If it
  4294. // already exists there, recursively merge the results together.
  4295. AddModifiedNodeToCSEMaps(User, UpdateListener);
  4296. }
  4297. }
  4298. namespace {
  4299. /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
  4300. /// to record information about a use.
  4301. struct UseMemo {
  4302. SDNode *User;
  4303. unsigned Index;
  4304. SDUse *Use;
  4305. };
  4306. /// operator< - Sort Memos by User.
  4307. bool operator<(const UseMemo &L, const UseMemo &R) {
  4308. return (intptr_t)L.User < (intptr_t)R.User;
  4309. }
  4310. }
  4311. /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
  4312. /// uses of other values produced by From.getNode() alone. The same value
  4313. /// may appear in both the From and To list. The Deleted vector is
  4314. /// handled the same way as for ReplaceAllUsesWith.
  4315. void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
  4316. const SDValue *To,
  4317. unsigned Num,
  4318. DAGUpdateListener *UpdateListener){
  4319. // Handle the simple, trivial case efficiently.
  4320. if (Num == 1)
  4321. return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
  4322. // Read up all the uses and make records of them. This helps
  4323. // processing new uses that are introduced during the
  4324. // replacement process.
  4325. SmallVector<UseMemo, 4> Uses;
  4326. for (unsigned i = 0; i != Num; ++i) {
  4327. unsigned FromResNo = From[i].getResNo();
  4328. SDNode *FromNode = From[i].getNode();
  4329. for (SDNode::use_iterator UI = FromNode->use_begin(),
  4330. E = FromNode->use_end(); UI != E; ++UI) {
  4331. SDUse &Use = UI.getUse();
  4332. if (Use.getResNo() == FromResNo) {
  4333. UseMemo Memo = { *UI, i, &Use };
  4334. Uses.push_back(Memo);
  4335. }
  4336. }
  4337. }
  4338. // Sort the uses, so that all the uses from a given User are together.
  4339. std::sort(Uses.begin(), Uses.end());
  4340. for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
  4341. UseIndex != UseIndexEnd; ) {
  4342. // We know that this user uses some value of From. If it is the right
  4343. // value, update it.
  4344. SDNode *User = Uses[UseIndex].User;
  4345. // This node is about to morph, remove its old self from the CSE maps.
  4346. RemoveNodeFromCSEMaps(User);
  4347. // The Uses array is sorted, so all the uses for a given User
  4348. // are next to each other in the list.
  4349. // To help reduce the number of CSE recomputations, process all
  4350. // the uses of this user that we can find this way.
  4351. do {
  4352. unsigned i = Uses[UseIndex].Index;
  4353. SDUse &Use = *Uses[UseIndex].Use;
  4354. ++UseIndex;
  4355. Use.set(To[i]);
  4356. } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
  4357. // Now that we have modified User, add it back to the CSE maps. If it
  4358. // already exists there, recursively merge the results together.
  4359. AddModifiedNodeToCSEMaps(User, UpdateListener);
  4360. }
  4361. }
  4362. /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
  4363. /// based on their topological order. It returns the maximum id and a vector
  4364. /// of the SDNodes* in assigned order by reference.
  4365. unsigned SelectionDAG::AssignTopologicalOrder() {
  4366. unsigned DAGSize = 0;
  4367. // SortedPos tracks the progress of the algorithm. Nodes before it are
  4368. // sorted, nodes after it are unsorted. When the algorithm completes
  4369. // it is at the end of the list.
  4370. allnodes_iterator SortedPos = allnodes_begin();
  4371. // Visit all the nodes. Move nodes with no operands to the front of
  4372. // the list immediately. Annotate nodes that do have operands with their
  4373. // operand count. Before we do this, the Node Id fields of the nodes
  4374. // may contain arbitrary values. After, the Node Id fields for nodes
  4375. // before SortedPos will contain the topological sort index, and the
  4376. // Node Id fields for nodes At SortedPos and after will contain the
  4377. // count of outstanding operands.
  4378. for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
  4379. SDNode *N = I++;
  4380. unsigned Degree = N->getNumOperands();
  4381. if (Degree == 0) {
  4382. // A node with no uses, add it to the result array immediately.
  4383. N->setNodeId(DAGSize++);
  4384. allnodes_iterator Q = N;
  4385. if (Q != SortedPos)
  4386. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
  4387. ++SortedPos;
  4388. } else {
  4389. // Temporarily use the Node Id as scratch space for the degree count.
  4390. N->setNodeId(Degree);
  4391. }
  4392. }
  4393. // Visit all the nodes. As we iterate, moves nodes into sorted order,
  4394. // such that by the time the end is reached all nodes will be sorted.
  4395. for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
  4396. SDNode *N = I;
  4397. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  4398. UI != UE; ++UI) {
  4399. SDNode *P = *UI;
  4400. unsigned Degree = P->getNodeId();
  4401. --Degree;
  4402. if (Degree == 0) {
  4403. // All of P's operands are sorted, so P may sorted now.
  4404. P->setNodeId(DAGSize++);
  4405. if (P != SortedPos)
  4406. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
  4407. ++SortedPos;
  4408. } else {
  4409. // Update P's outstanding operand count.
  4410. P->setNodeId(Degree);
  4411. }
  4412. }
  4413. }
  4414. assert(SortedPos == AllNodes.end() &&
  4415. "Topological sort incomplete!");
  4416. assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
  4417. "First node in topological sort is not the entry token!");
  4418. assert(AllNodes.front().getNodeId() == 0 &&
  4419. "First node in topological sort has non-zero id!");
  4420. assert(AllNodes.front().getNumOperands() == 0 &&
  4421. "First node in topological sort has operands!");
  4422. assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
  4423. "Last node in topologic sort has unexpected id!");
  4424. assert(AllNodes.back().use_empty() &&
  4425. "Last node in topologic sort has users!");
  4426. assert(DAGSize == allnodes_size() && "Node count mismatch!");
  4427. return DAGSize;
  4428. }
  4429. //===----------------------------------------------------------------------===//
  4430. // SDNode Class
  4431. //===----------------------------------------------------------------------===//
  4432. HandleSDNode::~HandleSDNode() {
  4433. DropOperands();
  4434. }
  4435. GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, const GlobalValue *GA,
  4436. MVT VT, int64_t o, unsigned char TF)
  4437. : SDNode(Opc, DebugLoc::getUnknownLoc(), getSDVTList(VT)),
  4438. Offset(o), TargetFlags(TF) {
  4439. TheGlobal = const_cast<GlobalValue*>(GA);
  4440. }
  4441. MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, MVT memvt,
  4442. const Value *srcValue, int SVO,
  4443. unsigned alignment, bool vol)
  4444. : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
  4445. SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
  4446. assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
  4447. assert(getAlignment() == alignment && "Alignment representation error!");
  4448. assert(isVolatile() == vol && "Volatile representation error!");
  4449. }
  4450. MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
  4451. const SDValue *Ops,
  4452. unsigned NumOps, MVT memvt, const Value *srcValue,
  4453. int SVO, unsigned alignment, bool vol)
  4454. : SDNode(Opc, dl, VTs, Ops, NumOps),
  4455. MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
  4456. SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
  4457. assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
  4458. assert(getAlignment() == alignment && "Alignment representation error!");
  4459. assert(isVolatile() == vol && "Volatile representation error!");
  4460. }
  4461. /// getMemOperand - Return a MachineMemOperand object describing the memory
  4462. /// reference performed by this memory reference.
  4463. MachineMemOperand MemSDNode::getMemOperand() const {
  4464. int Flags = 0;
  4465. if (isa<LoadSDNode>(this))
  4466. Flags = MachineMemOperand::MOLoad;
  4467. else if (isa<StoreSDNode>(this))
  4468. Flags = MachineMemOperand::MOStore;
  4469. else if (isa<AtomicSDNode>(this)) {
  4470. Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
  4471. }
  4472. else {
  4473. const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
  4474. assert(MemIntrinNode && "Unknown MemSDNode opcode!");
  4475. if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
  4476. if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
  4477. }
  4478. int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
  4479. if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
  4480. // Check if the memory reference references a frame index
  4481. const FrameIndexSDNode *FI =
  4482. dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
  4483. if (!getSrcValue() && FI)
  4484. return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
  4485. Flags, 0, Size, getAlignment());
  4486. else
  4487. return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
  4488. Size, getAlignment());
  4489. }
  4490. /// Profile - Gather unique data for the node.
  4491. ///
  4492. void SDNode::Profile(FoldingSetNodeID &ID) const {
  4493. AddNodeIDNode(ID, this);
  4494. }
  4495. static ManagedStatic<std::set<MVT, MVT::compareRawBits> > EVTs;
  4496. static MVT VTs[MVT::LAST_VALUETYPE];
  4497. static ManagedStatic<sys::SmartMutex<true> > VTMutex;
  4498. /// getValueTypeList - Return a pointer to the specified value type.
  4499. ///
  4500. const MVT *SDNode::getValueTypeList(MVT VT) {
  4501. sys::SmartScopedLock<true> Lock(*VTMutex);
  4502. if (VT.isExtended()) {
  4503. return &(*EVTs->insert(VT).first);
  4504. } else {
  4505. VTs[VT.getSimpleVT()] = VT;
  4506. return &VTs[VT.getSimpleVT()];
  4507. }
  4508. }
  4509. /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
  4510. /// indicated value. This method ignores uses of other values defined by this
  4511. /// operation.
  4512. bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
  4513. assert(Value < getNumValues() && "Bad value!");
  4514. // TODO: Only iterate over uses of a given value of the node
  4515. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
  4516. if (UI.getUse().getResNo() == Value) {
  4517. if (NUses == 0)
  4518. return false;
  4519. --NUses;
  4520. }
  4521. }
  4522. // Found exactly the right number of uses?
  4523. return NUses == 0;
  4524. }
  4525. /// hasAnyUseOfValue - Return true if there are any use of the indicated
  4526. /// value. This method ignores uses of other values defined by this operation.
  4527. bool SDNode::hasAnyUseOfValue(unsigned Value) const {
  4528. assert(Value < getNumValues() && "Bad value!");
  4529. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
  4530. if (UI.getUse().getResNo() == Value)
  4531. return true;
  4532. return false;
  4533. }
  4534. /// isOnlyUserOf - Return true if this node is the only use of N.
  4535. ///
  4536. bool SDNode::isOnlyUserOf(SDNode *N) const {
  4537. bool Seen = false;
  4538. for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
  4539. SDNode *User = *I;
  4540. if (User == this)
  4541. Seen = true;
  4542. else
  4543. return false;
  4544. }
  4545. return Seen;
  4546. }
  4547. /// isOperand - Return true if this node is an operand of N.
  4548. ///
  4549. bool SDValue::isOperandOf(SDNode *N) const {
  4550. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  4551. if (*this == N->getOperand(i))
  4552. return true;
  4553. return false;
  4554. }
  4555. bool SDNode::isOperandOf(SDNode *N) const {
  4556. for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
  4557. if (this == N->OperandList[i].getNode())
  4558. return true;
  4559. return false;
  4560. }
  4561. /// reachesChainWithoutSideEffects - Return true if this operand (which must
  4562. /// be a chain) reaches the specified operand without crossing any
  4563. /// side-effecting instructions. In practice, this looks through token
  4564. /// factors and non-volatile loads. In order to remain efficient, this only
  4565. /// looks a couple of nodes in, it does not do an exhaustive search.
  4566. bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
  4567. unsigned Depth) const {
  4568. if (*this == Dest) return true;
  4569. // Don't search too deeply, we just want to be able to see through
  4570. // TokenFactor's etc.
  4571. if (Depth == 0) return false;
  4572. // If this is a token factor, all inputs to the TF happen in parallel. If any
  4573. // of the operands of the TF reach dest, then we can do the xform.
  4574. if (getOpcode() == ISD::TokenFactor) {
  4575. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  4576. if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
  4577. return true;
  4578. return false;
  4579. }
  4580. // Loads don't have side effects, look through them.
  4581. if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
  4582. if (!Ld->isVolatile())
  4583. return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
  4584. }
  4585. return false;
  4586. }
  4587. static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
  4588. SmallPtrSet<SDNode *, 32> &Visited) {
  4589. if (found || !Visited.insert(N))
  4590. return;
  4591. for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
  4592. SDNode *Op = N->getOperand(i).getNode();
  4593. if (Op == P) {
  4594. found = true;
  4595. return;
  4596. }
  4597. findPredecessor(Op, P, found, Visited);
  4598. }
  4599. }
  4600. /// isPredecessorOf - Return true if this node is a predecessor of N. This node
  4601. /// is either an operand of N or it can be reached by recursively traversing
  4602. /// up the operands.
  4603. /// NOTE: this is an expensive method. Use it carefully.
  4604. bool SDNode::isPredecessorOf(SDNode *N) const {
  4605. SmallPtrSet<SDNode *, 32> Visited;
  4606. bool found = false;
  4607. findPredecessor(N, this, found, Visited);
  4608. return found;
  4609. }
  4610. uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
  4611. assert(Num < NumOperands && "Invalid child # of SDNode!");
  4612. return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
  4613. }
  4614. std::string SDNode::getOperationName(const SelectionDAG *G) const {
  4615. switch (getOpcode()) {
  4616. default:
  4617. if (getOpcode() < ISD::BUILTIN_OP_END)
  4618. return "<<Unknown DAG Node>>";
  4619. if (isMachineOpcode()) {
  4620. if (G)
  4621. if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
  4622. if (getMachineOpcode() < TII->getNumOpcodes())
  4623. return TII->get(getMachineOpcode()).getName();
  4624. return "<<Unknown Machine Node>>";
  4625. }
  4626. if (G) {
  4627. const TargetLowering &TLI = G->getTargetLoweringInfo();
  4628. const char *Name = TLI.getTargetNodeName(getOpcode());
  4629. if (Name) return Name;
  4630. return "<<Unknown Target Node>>";
  4631. }
  4632. return "<<Unknown Node>>";
  4633. #ifndef NDEBUG
  4634. case ISD::DELETED_NODE:
  4635. return "<<Deleted Node!>>";
  4636. #endif
  4637. case ISD::PREFETCH: return "Prefetch";
  4638. case ISD::MEMBARRIER: return "MemBarrier";
  4639. case ISD::ATOMIC_CMP_SWAP: return "AtomicCmpSwap";
  4640. case ISD::ATOMIC_SWAP: return "AtomicSwap";
  4641. case ISD::ATOMIC_LOAD_ADD: return "AtomicLoadAdd";
  4642. case ISD::ATOMIC_LOAD_SUB: return "AtomicLoadSub";
  4643. case ISD::ATOMIC_LOAD_AND: return "AtomicLoadAnd";
  4644. case ISD::ATOMIC_LOAD_OR: return "AtomicLoadOr";
  4645. case ISD::ATOMIC_LOAD_XOR: return "AtomicLoadXor";
  4646. case ISD::ATOMIC_LOAD_NAND: return "AtomicLoadNand";
  4647. case ISD::ATOMIC_LOAD_MIN: return "AtomicLoadMin";
  4648. case ISD::ATOMIC_LOAD_MAX: return "AtomicLoadMax";
  4649. case ISD::ATOMIC_LOAD_UMIN: return "AtomicLoadUMin";
  4650. case ISD::ATOMIC_LOAD_UMAX: return "AtomicLoadUMax";
  4651. case ISD::PCMARKER: return "PCMarker";
  4652. case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
  4653. case ISD::SRCVALUE: return "SrcValue";
  4654. case ISD::MEMOPERAND: return "MemOperand";
  4655. case ISD::EntryToken: return "EntryToken";
  4656. case ISD::TokenFactor: return "TokenFactor";
  4657. case ISD::AssertSext: return "AssertSext";
  4658. case ISD::AssertZext: return "AssertZext";
  4659. case ISD::BasicBlock: return "BasicBlock";
  4660. case ISD::ARG_FLAGS: return "ArgFlags";
  4661. case ISD::VALUETYPE: return "ValueType";
  4662. case ISD::Register: return "Register";
  4663. case ISD::Constant: return "Constant";
  4664. case ISD::ConstantFP: return "ConstantFP";
  4665. case ISD::GlobalAddress: return "GlobalAddress";
  4666. case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
  4667. case ISD::FrameIndex: return "FrameIndex";
  4668. case ISD::JumpTable: return "JumpTable";
  4669. case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
  4670. case ISD::RETURNADDR: return "RETURNADDR";
  4671. case ISD::FRAMEADDR: return "FRAMEADDR";
  4672. case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
  4673. case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
  4674. case ISD::EHSELECTION: return "EHSELECTION";
  4675. case ISD::EH_RETURN: return "EH_RETURN";
  4676. case ISD::ConstantPool: return "ConstantPool";
  4677. case ISD::ExternalSymbol: return "ExternalSymbol";
  4678. case ISD::INTRINSIC_WO_CHAIN: {
  4679. unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
  4680. return Intrinsic::getName((Intrinsic::ID)IID);
  4681. }
  4682. case ISD::INTRINSIC_VOID:
  4683. case ISD::INTRINSIC_W_CHAIN: {
  4684. unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
  4685. return Intrinsic::getName((Intrinsic::ID)IID);
  4686. }
  4687. case ISD::BUILD_VECTOR: return "BUILD_VECTOR";
  4688. case ISD::TargetConstant: return "TargetConstant";
  4689. case ISD::TargetConstantFP:return "TargetConstantFP";
  4690. case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
  4691. case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
  4692. case ISD::TargetFrameIndex: return "TargetFrameIndex";
  4693. case ISD::TargetJumpTable: return "TargetJumpTable";
  4694. case ISD::TargetConstantPool: return "TargetConstantPool";
  4695. case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
  4696. case ISD::CopyToReg: return "CopyToReg";
  4697. case ISD::CopyFromReg: return "CopyFromReg";
  4698. case ISD::UNDEF: return "undef";
  4699. case ISD::MERGE_VALUES: return "merge_values";
  4700. case ISD::INLINEASM: return "inlineasm";
  4701. case ISD::DBG_LABEL: return "dbg_label";
  4702. case ISD::EH_LABEL: return "eh_label";
  4703. case ISD::DECLARE: return "declare";
  4704. case ISD::HANDLENODE: return "handlenode";
  4705. case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
  4706. case ISD::CALL: return "call";
  4707. // Unary operators
  4708. case ISD::FABS: return "fabs";
  4709. case ISD::FNEG: return "fneg";
  4710. case ISD::FSQRT: return "fsqrt";
  4711. case ISD::FSIN: return "fsin";
  4712. case ISD::FCOS: return "fcos";
  4713. case ISD::FPOWI: return "fpowi";
  4714. case ISD::FPOW: return "fpow";
  4715. case ISD::FTRUNC: return "ftrunc";
  4716. case ISD::FFLOOR: return "ffloor";
  4717. case ISD::FCEIL: return "fceil";
  4718. case ISD::FRINT: return "frint";
  4719. case ISD::FNEARBYINT: return "fnearbyint";
  4720. // Binary operators
  4721. case ISD::ADD: return "add";
  4722. case ISD::SUB: return "sub";
  4723. case ISD::MUL: return "mul";
  4724. case ISD::MULHU: return "mulhu";
  4725. case ISD::MULHS: return "mulhs";
  4726. case ISD::SDIV: return "sdiv";
  4727. case ISD::UDIV: return "udiv";
  4728. case ISD::SREM: return "srem";
  4729. case ISD::UREM: return "urem";
  4730. case ISD::SMUL_LOHI: return "smul_lohi";
  4731. case ISD::UMUL_LOHI: return "umul_lohi";
  4732. case ISD::SDIVREM: return "sdivrem";
  4733. case ISD::UDIVREM: return "udivrem";
  4734. case ISD::AND: return "and";
  4735. case ISD::OR: return "or";
  4736. case ISD::XOR: return "xor";
  4737. case ISD::SHL: return "shl";
  4738. case ISD::SRA: return "sra";
  4739. case ISD::SRL: return "srl";
  4740. case ISD::ROTL: return "rotl";
  4741. case ISD::ROTR: return "rotr";
  4742. case ISD::FADD: return "fadd";
  4743. case ISD::FSUB: return "fsub";
  4744. case ISD::FMUL: return "fmul";
  4745. case ISD::FDIV: return "fdiv";
  4746. case ISD::FREM: return "frem";
  4747. case ISD::FCOPYSIGN: return "fcopysign";
  4748. case ISD::FGETSIGN: return "fgetsign";
  4749. case ISD::SETCC: return "setcc";
  4750. case ISD::VSETCC: return "vsetcc";
  4751. case ISD::SELECT: return "select";
  4752. case ISD::SELECT_CC: return "select_cc";
  4753. case ISD::INSERT_VECTOR_ELT: return "insert_vector_elt";
  4754. case ISD::EXTRACT_VECTOR_ELT: return "extract_vector_elt";
  4755. case ISD::CONCAT_VECTORS: return "concat_vectors";
  4756. case ISD::EXTRACT_SUBVECTOR: return "extract_subvector";
  4757. case ISD::SCALAR_TO_VECTOR: return "scalar_to_vector";
  4758. case ISD::VECTOR_SHUFFLE: return "vector_shuffle";
  4759. case ISD::CARRY_FALSE: return "carry_false";
  4760. case ISD::ADDC: return "addc";
  4761. case ISD::ADDE: return "adde";
  4762. case ISD::SADDO: return "saddo";
  4763. case ISD::UADDO: return "uaddo";
  4764. case ISD::SSUBO: return "ssubo";
  4765. case ISD::USUBO: return "usubo";
  4766. case ISD::SMULO: return "smulo";
  4767. case ISD::UMULO: return "umulo";
  4768. case ISD::SUBC: return "subc";
  4769. case ISD::SUBE: return "sube";
  4770. case ISD::SHL_PARTS: return "shl_parts";
  4771. case ISD::SRA_PARTS: return "sra_parts";
  4772. case ISD::SRL_PARTS: return "srl_parts";
  4773. // Conversion operators.
  4774. case ISD::SIGN_EXTEND: return "sign_extend";
  4775. case ISD::ZERO_EXTEND: return "zero_extend";
  4776. case ISD::ANY_EXTEND: return "any_extend";
  4777. case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
  4778. case ISD::TRUNCATE: return "truncate";
  4779. case ISD::FP_ROUND: return "fp_round";
  4780. case ISD::FLT_ROUNDS_: return "flt_rounds";
  4781. case ISD::FP_ROUND_INREG: return "fp_round_inreg";
  4782. case ISD::FP_EXTEND: return "fp_extend";
  4783. case ISD::SINT_TO_FP: return "sint_to_fp";
  4784. case ISD::UINT_TO_FP: return "uint_to_fp";
  4785. case ISD::FP_TO_SINT: return "fp_to_sint";
  4786. case ISD::FP_TO_UINT: return "fp_to_uint";
  4787. case ISD::BIT_CONVERT: return "bit_convert";
  4788. case ISD::CONVERT_RNDSAT: {
  4789. switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
  4790. default: LLVM_UNREACHABLE("Unknown cvt code!");
  4791. case ISD::CVT_FF: return "cvt_ff";
  4792. case ISD::CVT_FS: return "cvt_fs";
  4793. case ISD::CVT_FU: return "cvt_fu";
  4794. case ISD::CVT_SF: return "cvt_sf";
  4795. case ISD::CVT_UF: return "cvt_uf";
  4796. case ISD::CVT_SS: return "cvt_ss";
  4797. case ISD::CVT_SU: return "cvt_su";
  4798. case ISD::CVT_US: return "cvt_us";
  4799. case ISD::CVT_UU: return "cvt_uu";
  4800. }
  4801. }
  4802. // Control flow instructions
  4803. case ISD::BR: return "br";
  4804. case ISD::BRIND: return "brind";
  4805. case ISD::BR_JT: return "br_jt";
  4806. case ISD::BRCOND: return "brcond";
  4807. case ISD::BR_CC: return "br_cc";
  4808. case ISD::RET: return "ret";
  4809. case ISD::CALLSEQ_START: return "callseq_start";
  4810. case ISD::CALLSEQ_END: return "callseq_end";
  4811. // Other operators
  4812. case ISD::LOAD: return "load";
  4813. case ISD::STORE: return "store";
  4814. case ISD::VAARG: return "vaarg";
  4815. case ISD::VACOPY: return "vacopy";
  4816. case ISD::VAEND: return "vaend";
  4817. case ISD::VASTART: return "vastart";
  4818. case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
  4819. case ISD::EXTRACT_ELEMENT: return "extract_element";
  4820. case ISD::BUILD_PAIR: return "build_pair";
  4821. case ISD::STACKSAVE: return "stacksave";
  4822. case ISD::STACKRESTORE: return "stackrestore";
  4823. case ISD::TRAP: return "trap";
  4824. // Bit manipulation
  4825. case ISD::BSWAP: return "bswap";
  4826. case ISD::CTPOP: return "ctpop";
  4827. case ISD::CTTZ: return "cttz";
  4828. case ISD::CTLZ: return "ctlz";
  4829. // Debug info
  4830. case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
  4831. case ISD::DEBUG_LOC: return "debug_loc";
  4832. // Trampolines
  4833. case ISD::TRAMPOLINE: return "trampoline";
  4834. case ISD::CONDCODE:
  4835. switch (cast<CondCodeSDNode>(this)->get()) {
  4836. default: LLVM_UNREACHABLE("Unknown setcc condition!");
  4837. case ISD::SETOEQ: return "setoeq";
  4838. case ISD::SETOGT: return "setogt";
  4839. case ISD::SETOGE: return "setoge";
  4840. case ISD::SETOLT: return "setolt";
  4841. case ISD::SETOLE: return "setole";
  4842. case ISD::SETONE: return "setone";
  4843. case ISD::SETO: return "seto";
  4844. case ISD::SETUO: return "setuo";
  4845. case ISD::SETUEQ: return "setue";
  4846. case ISD::SETUGT: return "setugt";
  4847. case ISD::SETUGE: return "setuge";
  4848. case ISD::SETULT: return "setult";
  4849. case ISD::SETULE: return "setule";
  4850. case ISD::SETUNE: return "setune";
  4851. case ISD::SETEQ: return "seteq";
  4852. case ISD::SETGT: return "setgt";
  4853. case ISD::SETGE: return "setge";
  4854. case ISD::SETLT: return "setlt";
  4855. case ISD::SETLE: return "setle";
  4856. case ISD::SETNE: return "setne";
  4857. }
  4858. }
  4859. }
  4860. const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
  4861. switch (AM) {
  4862. default:
  4863. return "";
  4864. case ISD::PRE_INC:
  4865. return "<pre-inc>";
  4866. case ISD::PRE_DEC:
  4867. return "<pre-dec>";
  4868. case ISD::POST_INC:
  4869. return "<post-inc>";
  4870. case ISD::POST_DEC:
  4871. return "<post-dec>";
  4872. }
  4873. }
  4874. std::string ISD::ArgFlagsTy::getArgFlagsString() {
  4875. std::string S = "< ";
  4876. if (isZExt())
  4877. S += "zext ";
  4878. if (isSExt())
  4879. S += "sext ";
  4880. if (isInReg())
  4881. S += "inreg ";
  4882. if (isSRet())
  4883. S += "sret ";
  4884. if (isByVal())
  4885. S += "byval ";
  4886. if (isNest())
  4887. S += "nest ";
  4888. if (getByValAlign())
  4889. S += "byval-align:" + utostr(getByValAlign()) + " ";
  4890. if (getOrigAlign())
  4891. S += "orig-align:" + utostr(getOrigAlign()) + " ";
  4892. if (getByValSize())
  4893. S += "byval-size:" + utostr(getByValSize()) + " ";
  4894. return S + ">";
  4895. }
  4896. void SDNode::dump() const { dump(0); }
  4897. void SDNode::dump(const SelectionDAG *G) const {
  4898. print(errs(), G);
  4899. }
  4900. void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
  4901. OS << (void*)this << ": ";
  4902. for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
  4903. if (i) OS << ",";
  4904. if (getValueType(i) == MVT::Other)
  4905. OS << "ch";
  4906. else
  4907. OS << getValueType(i).getMVTString();
  4908. }
  4909. OS << " = " << getOperationName(G);
  4910. }
  4911. void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
  4912. if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
  4913. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(this);
  4914. OS << "<";
  4915. for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
  4916. int Idx = SVN->getMaskElt(i);
  4917. if (i) OS << ",";
  4918. if (Idx < 0)
  4919. OS << "u";
  4920. else
  4921. OS << Idx;
  4922. }
  4923. OS << ">";
  4924. }
  4925. if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
  4926. OS << '<' << CSDN->getAPIntValue() << '>';
  4927. } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
  4928. if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
  4929. OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
  4930. else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
  4931. OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
  4932. else {
  4933. OS << "<APFloat(";
  4934. CSDN->getValueAPF().bitcastToAPInt().dump();
  4935. OS << ")>";
  4936. }
  4937. } else if (const GlobalAddressSDNode *GADN =
  4938. dyn_cast<GlobalAddressSDNode>(this)) {
  4939. int64_t offset = GADN->getOffset();
  4940. OS << '<';
  4941. WriteAsOperand(OS, GADN->getGlobal());
  4942. OS << '>';
  4943. if (offset > 0)
  4944. OS << " + " << offset;
  4945. else
  4946. OS << " " << offset;
  4947. if (unsigned char TF = GADN->getTargetFlags())
  4948. OS << " [TF=" << TF << ']';
  4949. } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
  4950. OS << "<" << FIDN->getIndex() << ">";
  4951. } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
  4952. OS << "<" << JTDN->getIndex() << ">";
  4953. if (unsigned char TF = JTDN->getTargetFlags())
  4954. OS << " [TF=" << TF << ']';
  4955. } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
  4956. int offset = CP->getOffset();
  4957. if (CP->isMachineConstantPoolEntry())
  4958. OS << "<" << *CP->getMachineCPVal() << ">";
  4959. else
  4960. OS << "<" << *CP->getConstVal() << ">";
  4961. if (offset > 0)
  4962. OS << " + " << offset;
  4963. else
  4964. OS << " " << offset;
  4965. if (unsigned char TF = CP->getTargetFlags())
  4966. OS << " [TF=" << TF << ']';
  4967. } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
  4968. OS << "<";
  4969. const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
  4970. if (LBB)
  4971. OS << LBB->getName() << " ";
  4972. OS << (const void*)BBDN->getBasicBlock() << ">";
  4973. } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
  4974. if (G && R->getReg() &&
  4975. TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
  4976. OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
  4977. } else {
  4978. OS << " #" << R->getReg();
  4979. }
  4980. } else if (const ExternalSymbolSDNode *ES =
  4981. dyn_cast<ExternalSymbolSDNode>(this)) {
  4982. OS << "'" << ES->getSymbol() << "'";
  4983. if (unsigned char TF = ES->getTargetFlags())
  4984. OS << " [TF=" << TF << ']';
  4985. } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
  4986. if (M->getValue())
  4987. OS << "<" << M->getValue() << ">";
  4988. else
  4989. OS << "<null>";
  4990. } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
  4991. if (M->MO.getValue())
  4992. OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
  4993. else
  4994. OS << "<null:" << M->MO.getOffset() << ">";
  4995. } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
  4996. OS << N->getArgFlags().getArgFlagsString();
  4997. } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
  4998. OS << ":" << N->getVT().getMVTString();
  4999. }
  5000. else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
  5001. const Value *SrcValue = LD->getSrcValue();
  5002. int SrcOffset = LD->getSrcValueOffset();
  5003. OS << " <";
  5004. if (SrcValue)
  5005. OS << SrcValue;
  5006. else
  5007. OS << "null";
  5008. OS << ":" << SrcOffset << ">";
  5009. bool doExt = true;
  5010. switch (LD->getExtensionType()) {
  5011. default: doExt = false; break;
  5012. case ISD::EXTLOAD: OS << " <anyext "; break;
  5013. case ISD::SEXTLOAD: OS << " <sext "; break;
  5014. case ISD::ZEXTLOAD: OS << " <zext "; break;
  5015. }
  5016. if (doExt)
  5017. OS << LD->getMemoryVT().getMVTString() << ">";
  5018. const char *AM = getIndexedModeName(LD->getAddressingMode());
  5019. if (*AM)
  5020. OS << " " << AM;
  5021. if (LD->isVolatile())
  5022. OS << " <volatile>";
  5023. OS << " alignment=" << LD->getAlignment();
  5024. } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
  5025. const Value *SrcValue = ST->getSrcValue();
  5026. int SrcOffset = ST->getSrcValueOffset();
  5027. OS << " <";
  5028. if (SrcValue)
  5029. OS << SrcValue;
  5030. else
  5031. OS << "null";
  5032. OS << ":" << SrcOffset << ">";
  5033. if (ST->isTruncatingStore())
  5034. OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
  5035. const char *AM = getIndexedModeName(ST->getAddressingMode());
  5036. if (*AM)
  5037. OS << " " << AM;
  5038. if (ST->isVolatile())
  5039. OS << " <volatile>";
  5040. OS << " alignment=" << ST->getAlignment();
  5041. } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
  5042. const Value *SrcValue = AT->getSrcValue();
  5043. int SrcOffset = AT->getSrcValueOffset();
  5044. OS << " <";
  5045. if (SrcValue)
  5046. OS << SrcValue;
  5047. else
  5048. OS << "null";
  5049. OS << ":" << SrcOffset << ">";
  5050. if (AT->isVolatile())
  5051. OS << " <volatile>";
  5052. OS << " alignment=" << AT->getAlignment();
  5053. }
  5054. }
  5055. void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
  5056. print_types(OS, G);
  5057. OS << " ";
  5058. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  5059. if (i) OS << ", ";
  5060. OS << (void*)getOperand(i).getNode();
  5061. if (unsigned RN = getOperand(i).getResNo())
  5062. OS << ":" << RN;
  5063. }
  5064. print_details(OS, G);
  5065. }
  5066. static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
  5067. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  5068. if (N->getOperand(i).getNode()->hasOneUse())
  5069. DumpNodes(N->getOperand(i).getNode(), indent+2, G);
  5070. else
  5071. cerr << "\n" << std::string(indent+2, ' ')
  5072. << (void*)N->getOperand(i).getNode() << ": <multiple use>";
  5073. cerr << "\n" << std::string(indent, ' ');
  5074. N->dump(G);
  5075. }
  5076. void SelectionDAG::dump() const {
  5077. cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
  5078. for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
  5079. I != E; ++I) {
  5080. const SDNode *N = I;
  5081. if (!N->hasOneUse() && N != getRoot().getNode())
  5082. DumpNodes(N, 2, this);
  5083. }
  5084. if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
  5085. cerr << "\n\n";
  5086. }
  5087. void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
  5088. print_types(OS, G);
  5089. print_details(OS, G);
  5090. }
  5091. typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
  5092. static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
  5093. const SelectionDAG *G, VisitedSDNodeSet &once) {
  5094. if (!once.insert(N)) // If we've been here before, return now.
  5095. return;
  5096. // Dump the current SDNode, but don't end the line yet.
  5097. OS << std::string(indent, ' ');
  5098. N->printr(OS, G);
  5099. // Having printed this SDNode, walk the children:
  5100. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  5101. const SDNode *child = N->getOperand(i).getNode();
  5102. if (i) OS << ",";
  5103. OS << " ";
  5104. if (child->getNumOperands() == 0) {
  5105. // This child has no grandchildren; print it inline right here.
  5106. child->printr(OS, G);
  5107. once.insert(child);
  5108. } else { // Just the address. FIXME: also print the child's opcode
  5109. OS << (void*)child;
  5110. if (unsigned RN = N->getOperand(i).getResNo())
  5111. OS << ":" << RN;
  5112. }
  5113. }
  5114. OS << "\n";
  5115. // Dump children that have grandchildren on their own line(s).
  5116. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  5117. const SDNode *child = N->getOperand(i).getNode();
  5118. DumpNodesr(OS, child, indent+2, G, once);
  5119. }
  5120. }
  5121. void SDNode::dumpr() const {
  5122. VisitedSDNodeSet once;
  5123. DumpNodesr(errs(), this, 0, 0, once);
  5124. }
  5125. // getAddressSpace - Return the address space this GlobalAddress belongs to.
  5126. unsigned GlobalAddressSDNode::getAddressSpace() const {
  5127. return getGlobal()->getType()->getAddressSpace();
  5128. }
  5129. const Type *ConstantPoolSDNode::getType() const {
  5130. if (isMachineConstantPoolEntry())
  5131. return Val.MachineCPVal->getType();
  5132. return Val.ConstVal->getType();
  5133. }
  5134. bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
  5135. APInt &SplatUndef,
  5136. unsigned &SplatBitSize,
  5137. bool &HasAnyUndefs,
  5138. unsigned MinSplatBits) {
  5139. MVT VT = getValueType(0);
  5140. assert(VT.isVector() && "Expected a vector type");
  5141. unsigned sz = VT.getSizeInBits();
  5142. if (MinSplatBits > sz)
  5143. return false;
  5144. SplatValue = APInt(sz, 0);
  5145. SplatUndef = APInt(sz, 0);
  5146. // Get the bits. Bits with undefined values (when the corresponding element
  5147. // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
  5148. // in SplatValue. If any of the values are not constant, give up and return
  5149. // false.
  5150. unsigned int nOps = getNumOperands();
  5151. assert(nOps > 0 && "isConstantSplat has 0-size build vector");
  5152. unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
  5153. for (unsigned i = 0; i < nOps; ++i) {
  5154. SDValue OpVal = getOperand(i);
  5155. unsigned BitPos = i * EltBitSize;
  5156. if (OpVal.getOpcode() == ISD::UNDEF)
  5157. SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos +EltBitSize);
  5158. else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
  5159. SplatValue |= (APInt(CN->getAPIntValue()).zextOrTrunc(EltBitSize).
  5160. zextOrTrunc(sz) << BitPos);
  5161. else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
  5162. SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
  5163. else
  5164. return false;
  5165. }
  5166. // The build_vector is all constants or undefs. Find the smallest element
  5167. // size that splats the vector.
  5168. HasAnyUndefs = (SplatUndef != 0);
  5169. while (sz > 8) {
  5170. unsigned HalfSize = sz / 2;
  5171. APInt HighValue = APInt(SplatValue).lshr(HalfSize).trunc(HalfSize);
  5172. APInt LowValue = APInt(SplatValue).trunc(HalfSize);
  5173. APInt HighUndef = APInt(SplatUndef).lshr(HalfSize).trunc(HalfSize);
  5174. APInt LowUndef = APInt(SplatUndef).trunc(HalfSize);
  5175. // If the two halves do not match (ignoring undef bits), stop here.
  5176. if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
  5177. MinSplatBits > HalfSize)
  5178. break;
  5179. SplatValue = HighValue | LowValue;
  5180. SplatUndef = HighUndef & LowUndef;
  5181. sz = HalfSize;
  5182. }
  5183. SplatBitSize = sz;
  5184. return true;
  5185. }
  5186. bool ShuffleVectorSDNode::isSplatMask(const int *Mask, MVT VT) {
  5187. // Find the first non-undef value in the shuffle mask.
  5188. unsigned i, e;
  5189. for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
  5190. /* search */;
  5191. assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
  5192. // Make sure all remaining elements are either undef or the same as the first
  5193. // non-undef value.
  5194. for (int Idx = Mask[i]; i != e; ++i)
  5195. if (Mask[i] >= 0 && Mask[i] != Idx)
  5196. return false;
  5197. return true;
  5198. }