2
0

LegalizeDAG.cpp 179 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396
  1. //===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
  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 file implements the SelectionDAG::Legalize method.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/SelectionDAG.h"
  14. #include "llvm/ADT/SetVector.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/CodeGen/Analysis.h"
  20. #include "llvm/CodeGen/MachineFunction.h"
  21. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  22. #include "llvm/IR/CallingConv.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/DebugInfo.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/Function.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/Support/Debug.h"
  30. #include "llvm/Support/ErrorHandling.h"
  31. #include "llvm/Support/MathExtras.h"
  32. #include "llvm/Support/raw_ostream.h"
  33. #include "llvm/Target/TargetFrameLowering.h"
  34. #include "llvm/Target/TargetLowering.h"
  35. #include "llvm/Target/TargetMachine.h"
  36. #include "llvm/Target/TargetSubtargetInfo.h"
  37. using namespace llvm;
  38. #define DEBUG_TYPE "legalizedag"
  39. //===----------------------------------------------------------------------===//
  40. /// This takes an arbitrary SelectionDAG as input and
  41. /// hacks on it until the target machine can handle it. This involves
  42. /// eliminating value sizes the machine cannot handle (promoting small sizes to
  43. /// large sizes or splitting up large values into small values) as well as
  44. /// eliminating operations the machine cannot handle.
  45. ///
  46. /// This code also does a small amount of optimization and recognition of idioms
  47. /// as part of its processing. For example, if a target does not support a
  48. /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
  49. /// will attempt merge setcc and brc instructions into brcc's.
  50. ///
  51. namespace {
  52. class SelectionDAGLegalize {
  53. const TargetMachine &TM;
  54. const TargetLowering &TLI;
  55. SelectionDAG &DAG;
  56. /// \brief The set of nodes which have already been legalized. We hold a
  57. /// reference to it in order to update as necessary on node deletion.
  58. SmallPtrSetImpl<SDNode *> &LegalizedNodes;
  59. /// \brief A set of all the nodes updated during legalization.
  60. SmallSetVector<SDNode *, 16> *UpdatedNodes;
  61. EVT getSetCCResultType(EVT VT) const {
  62. return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
  63. }
  64. // Libcall insertion helpers.
  65. public:
  66. SelectionDAGLegalize(SelectionDAG &DAG,
  67. SmallPtrSetImpl<SDNode *> &LegalizedNodes,
  68. SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
  69. : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
  70. LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
  71. /// \brief Legalizes the given operation.
  72. void LegalizeOp(SDNode *Node);
  73. private:
  74. SDValue OptimizeFloatStore(StoreSDNode *ST);
  75. void LegalizeLoadOps(SDNode *Node);
  76. void LegalizeStoreOps(SDNode *Node);
  77. /// Some targets cannot handle a variable
  78. /// insertion index for the INSERT_VECTOR_ELT instruction. In this case, it
  79. /// is necessary to spill the vector being inserted into to memory, perform
  80. /// the insert there, and then read the result back.
  81. SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
  82. SDValue Idx, SDLoc dl);
  83. SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
  84. SDValue Idx, SDLoc dl);
  85. /// Return a vector shuffle operation which
  86. /// performs the same shuffe in terms of order or result bytes, but on a type
  87. /// whose vector element type is narrower than the original shuffle type.
  88. /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
  89. SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, SDLoc dl,
  90. SDValue N1, SDValue N2,
  91. ArrayRef<int> Mask) const;
  92. bool LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
  93. bool &NeedInvert, SDLoc dl);
  94. SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
  95. SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops,
  96. unsigned NumOps, bool isSigned, SDLoc dl);
  97. std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
  98. SDNode *Node, bool isSigned);
  99. SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
  100. RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
  101. RTLIB::Libcall Call_F128,
  102. RTLIB::Libcall Call_PPCF128);
  103. SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
  104. RTLIB::Libcall Call_I8,
  105. RTLIB::Libcall Call_I16,
  106. RTLIB::Libcall Call_I32,
  107. RTLIB::Libcall Call_I64,
  108. RTLIB::Libcall Call_I128);
  109. void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
  110. void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
  111. SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, SDLoc dl);
  112. SDValue ExpandBUILD_VECTOR(SDNode *Node);
  113. SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
  114. void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
  115. SmallVectorImpl<SDValue> &Results);
  116. SDValue ExpandFCOPYSIGN(SDNode *Node);
  117. SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
  118. SDLoc dl);
  119. SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
  120. SDLoc dl);
  121. SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
  122. SDLoc dl);
  123. SDValue ExpandBSWAP(SDValue Op, SDLoc dl);
  124. SDValue ExpandBitCount(unsigned Opc, SDValue Op, SDLoc dl);
  125. SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
  126. SDValue ExpandInsertToVectorThroughStack(SDValue Op);
  127. SDValue ExpandVectorBuildThroughStack(SDNode* Node);
  128. SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
  129. std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
  130. void ExpandNode(SDNode *Node);
  131. void PromoteNode(SDNode *Node);
  132. public:
  133. // Node replacement helpers
  134. void ReplacedNode(SDNode *N) {
  135. LegalizedNodes.erase(N);
  136. if (UpdatedNodes)
  137. UpdatedNodes->insert(N);
  138. }
  139. void ReplaceNode(SDNode *Old, SDNode *New) {
  140. DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
  141. dbgs() << " with: "; New->dump(&DAG));
  142. assert(Old->getNumValues() == New->getNumValues() &&
  143. "Replacing one node with another that produces a different number "
  144. "of values!");
  145. DAG.ReplaceAllUsesWith(Old, New);
  146. for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i)
  147. DAG.TransferDbgValues(SDValue(Old, i), SDValue(New, i));
  148. if (UpdatedNodes)
  149. UpdatedNodes->insert(New);
  150. ReplacedNode(Old);
  151. }
  152. void ReplaceNode(SDValue Old, SDValue New) {
  153. DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
  154. dbgs() << " with: "; New->dump(&DAG));
  155. DAG.ReplaceAllUsesWith(Old, New);
  156. DAG.TransferDbgValues(Old, New);
  157. if (UpdatedNodes)
  158. UpdatedNodes->insert(New.getNode());
  159. ReplacedNode(Old.getNode());
  160. }
  161. void ReplaceNode(SDNode *Old, const SDValue *New) {
  162. DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
  163. DAG.ReplaceAllUsesWith(Old, New);
  164. for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
  165. DEBUG(dbgs() << (i == 0 ? " with: "
  166. : " and: ");
  167. New[i]->dump(&DAG));
  168. DAG.TransferDbgValues(SDValue(Old, i), New[i]);
  169. if (UpdatedNodes)
  170. UpdatedNodes->insert(New[i].getNode());
  171. }
  172. ReplacedNode(Old);
  173. }
  174. };
  175. }
  176. /// Return a vector shuffle operation which
  177. /// performs the same shuffe in terms of order or result bytes, but on a type
  178. /// whose vector element type is narrower than the original shuffle type.
  179. /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
  180. SDValue
  181. SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT, SDLoc dl,
  182. SDValue N1, SDValue N2,
  183. ArrayRef<int> Mask) const {
  184. unsigned NumMaskElts = VT.getVectorNumElements();
  185. unsigned NumDestElts = NVT.getVectorNumElements();
  186. unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
  187. assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
  188. if (NumEltsGrowth == 1)
  189. return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
  190. SmallVector<int, 8> NewMask;
  191. for (unsigned i = 0; i != NumMaskElts; ++i) {
  192. int Idx = Mask[i];
  193. for (unsigned j = 0; j != NumEltsGrowth; ++j) {
  194. if (Idx < 0)
  195. NewMask.push_back(-1);
  196. else
  197. NewMask.push_back(Idx * NumEltsGrowth + j);
  198. }
  199. }
  200. assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
  201. assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
  202. return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
  203. }
  204. /// Expands the ConstantFP node to an integer constant or
  205. /// a load from the constant pool.
  206. SDValue
  207. SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
  208. bool Extend = false;
  209. SDLoc dl(CFP);
  210. // If a FP immediate is precise when represented as a float and if the
  211. // target can do an extending load from float to double, we put it into
  212. // the constant pool as a float, even if it's is statically typed as a
  213. // double. This shrinks FP constants and canonicalizes them for targets where
  214. // an FP extending load is the same cost as a normal load (such as on the x87
  215. // fp stack or PPC FP unit).
  216. EVT VT = CFP->getValueType(0);
  217. ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
  218. if (!UseCP) {
  219. assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
  220. return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
  221. (VT == MVT::f64) ? MVT::i64 : MVT::i32);
  222. }
  223. EVT OrigVT = VT;
  224. EVT SVT = VT;
  225. while (SVT != MVT::f32 && SVT != MVT::f16) {
  226. SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
  227. if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
  228. // Only do this if the target has a native EXTLOAD instruction from
  229. // smaller type.
  230. TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) &&
  231. TLI.ShouldShrinkFPConstant(OrigVT)) {
  232. Type *SType = SVT.getTypeForEVT(*DAG.getContext());
  233. LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
  234. VT = SVT;
  235. Extend = true;
  236. }
  237. }
  238. SDValue CPIdx =
  239. DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout()));
  240. unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
  241. if (Extend) {
  242. SDValue Result =
  243. DAG.getExtLoad(ISD::EXTLOAD, dl, OrigVT,
  244. DAG.getEntryNode(),
  245. CPIdx, MachinePointerInfo::getConstantPool(),
  246. VT, false, false, false, Alignment);
  247. return Result;
  248. }
  249. SDValue Result =
  250. DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
  251. MachinePointerInfo::getConstantPool(), false, false, false,
  252. Alignment);
  253. return Result;
  254. }
  255. /// Expands an unaligned store to 2 half-size stores.
  256. static void ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
  257. const TargetLowering &TLI,
  258. SelectionDAGLegalize *DAGLegalize) {
  259. assert(ST->getAddressingMode() == ISD::UNINDEXED &&
  260. "unaligned indexed stores not implemented!");
  261. SDValue Chain = ST->getChain();
  262. SDValue Ptr = ST->getBasePtr();
  263. SDValue Val = ST->getValue();
  264. EVT VT = Val.getValueType();
  265. int Alignment = ST->getAlignment();
  266. unsigned AS = ST->getAddressSpace();
  267. SDLoc dl(ST);
  268. if (ST->getMemoryVT().isFloatingPoint() ||
  269. ST->getMemoryVT().isVector()) {
  270. EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
  271. if (TLI.isTypeLegal(intVT)) {
  272. // Expand to a bitconvert of the value to the integer type of the
  273. // same size, then a (misaligned) int store.
  274. // FIXME: Does not handle truncating floating point stores!
  275. SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
  276. Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
  277. ST->isVolatile(), ST->isNonTemporal(), Alignment);
  278. DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
  279. return;
  280. }
  281. // Do a (aligned) store to a stack slot, then copy from the stack slot
  282. // to the final destination using (unaligned) integer loads and stores.
  283. EVT StoredVT = ST->getMemoryVT();
  284. MVT RegVT =
  285. TLI.getRegisterType(*DAG.getContext(),
  286. EVT::getIntegerVT(*DAG.getContext(),
  287. StoredVT.getSizeInBits()));
  288. unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
  289. unsigned RegBytes = RegVT.getSizeInBits() / 8;
  290. unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
  291. // Make sure the stack slot is also aligned for the register type.
  292. SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
  293. // Perform the original store, only redirected to the stack slot.
  294. SDValue Store = DAG.getTruncStore(Chain, dl,
  295. Val, StackPtr, MachinePointerInfo(),
  296. StoredVT, false, false, 0);
  297. SDValue Increment = DAG.getConstant(
  298. RegBytes, dl, TLI.getPointerTy(DAG.getDataLayout(), AS));
  299. SmallVector<SDValue, 8> Stores;
  300. unsigned Offset = 0;
  301. // Do all but one copies using the full register width.
  302. for (unsigned i = 1; i < NumRegs; i++) {
  303. // Load one integer register's worth from the stack slot.
  304. SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr,
  305. MachinePointerInfo(),
  306. false, false, false, 0);
  307. // Store it to the final location. Remember the store.
  308. Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
  309. ST->getPointerInfo().getWithOffset(Offset),
  310. ST->isVolatile(), ST->isNonTemporal(),
  311. MinAlign(ST->getAlignment(), Offset)));
  312. // Increment the pointers.
  313. Offset += RegBytes;
  314. StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
  315. Increment);
  316. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
  317. }
  318. // The last store may be partial. Do a truncating store. On big-endian
  319. // machines this requires an extending load from the stack slot to ensure
  320. // that the bits are in the right place.
  321. EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
  322. 8 * (StoredBytes - Offset));
  323. // Load from the stack slot.
  324. SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
  325. MachinePointerInfo(),
  326. MemVT, false, false, false, 0);
  327. Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
  328. ST->getPointerInfo()
  329. .getWithOffset(Offset),
  330. MemVT, ST->isVolatile(),
  331. ST->isNonTemporal(),
  332. MinAlign(ST->getAlignment(), Offset),
  333. ST->getAAInfo()));
  334. // The order of the stores doesn't matter - say it with a TokenFactor.
  335. SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
  336. DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
  337. return;
  338. }
  339. assert(ST->getMemoryVT().isInteger() &&
  340. !ST->getMemoryVT().isVector() &&
  341. "Unaligned store of unknown type.");
  342. // Get the half-size VT
  343. EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
  344. int NumBits = NewStoredVT.getSizeInBits();
  345. int IncrementSize = NumBits / 8;
  346. // Divide the stored value in two parts.
  347. SDValue ShiftAmount =
  348. DAG.getConstant(NumBits, dl, TLI.getShiftAmountTy(Val.getValueType(),
  349. DAG.getDataLayout()));
  350. SDValue Lo = Val;
  351. SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
  352. // Store the two parts
  353. SDValue Store1, Store2;
  354. Store1 = DAG.getTruncStore(Chain, dl,
  355. DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
  356. Ptr, ST->getPointerInfo(), NewStoredVT,
  357. ST->isVolatile(), ST->isNonTemporal(), Alignment);
  358. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  359. DAG.getConstant(IncrementSize, dl,
  360. TLI.getPointerTy(DAG.getDataLayout(), AS)));
  361. Alignment = MinAlign(Alignment, IncrementSize);
  362. Store2 = DAG.getTruncStore(
  363. Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
  364. ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT,
  365. ST->isVolatile(), ST->isNonTemporal(), Alignment, ST->getAAInfo());
  366. SDValue Result =
  367. DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
  368. DAGLegalize->ReplaceNode(SDValue(ST, 0), Result);
  369. }
  370. /// Expands an unaligned load to 2 half-size loads.
  371. static void
  372. ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
  373. const TargetLowering &TLI,
  374. SDValue &ValResult, SDValue &ChainResult) {
  375. assert(LD->getAddressingMode() == ISD::UNINDEXED &&
  376. "unaligned indexed loads not implemented!");
  377. SDValue Chain = LD->getChain();
  378. SDValue Ptr = LD->getBasePtr();
  379. EVT VT = LD->getValueType(0);
  380. EVT LoadedVT = LD->getMemoryVT();
  381. SDLoc dl(LD);
  382. if (VT.isFloatingPoint() || VT.isVector()) {
  383. EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
  384. if (TLI.isTypeLegal(intVT) && TLI.isTypeLegal(LoadedVT)) {
  385. // Expand to a (misaligned) integer load of the same size,
  386. // then bitconvert to floating point or vector.
  387. SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
  388. LD->getMemOperand());
  389. SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
  390. if (LoadedVT != VT)
  391. Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
  392. ISD::ANY_EXTEND, dl, VT, Result);
  393. ValResult = Result;
  394. ChainResult = Chain;
  395. return;
  396. }
  397. // Copy the value to a (aligned) stack slot using (unaligned) integer
  398. // loads and stores, then do a (aligned) load from the stack slot.
  399. MVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
  400. unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
  401. unsigned RegBytes = RegVT.getSizeInBits() / 8;
  402. unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
  403. // Make sure the stack slot is also aligned for the register type.
  404. SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
  405. SDValue Increment =
  406. DAG.getConstant(RegBytes, dl, TLI.getPointerTy(DAG.getDataLayout()));
  407. SmallVector<SDValue, 8> Stores;
  408. SDValue StackPtr = StackBase;
  409. unsigned Offset = 0;
  410. // Do all but one copies using the full register width.
  411. for (unsigned i = 1; i < NumRegs; i++) {
  412. // Load one integer register's worth from the original location.
  413. SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
  414. LD->getPointerInfo().getWithOffset(Offset),
  415. LD->isVolatile(), LD->isNonTemporal(),
  416. LD->isInvariant(),
  417. MinAlign(LD->getAlignment(), Offset),
  418. LD->getAAInfo());
  419. // Follow the load with a store to the stack slot. Remember the store.
  420. Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
  421. MachinePointerInfo(), false, false, 0));
  422. // Increment the pointers.
  423. Offset += RegBytes;
  424. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
  425. StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
  426. Increment);
  427. }
  428. // The last copy may be partial. Do an extending load.
  429. EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
  430. 8 * (LoadedBytes - Offset));
  431. SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
  432. LD->getPointerInfo().getWithOffset(Offset),
  433. MemVT, LD->isVolatile(),
  434. LD->isNonTemporal(),
  435. LD->isInvariant(),
  436. MinAlign(LD->getAlignment(), Offset),
  437. LD->getAAInfo());
  438. // Follow the load with a store to the stack slot. Remember the store.
  439. // On big-endian machines this requires a truncating store to ensure
  440. // that the bits end up in the right place.
  441. Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
  442. MachinePointerInfo(), MemVT,
  443. false, false, 0));
  444. // The order of the stores doesn't matter - say it with a TokenFactor.
  445. SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
  446. // Finally, perform the original load only redirected to the stack slot.
  447. Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
  448. MachinePointerInfo(), LoadedVT, false,false, false,
  449. 0);
  450. // Callers expect a MERGE_VALUES node.
  451. ValResult = Load;
  452. ChainResult = TF;
  453. return;
  454. }
  455. assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
  456. "Unaligned load of unsupported type.");
  457. // Compute the new VT that is half the size of the old one. This is an
  458. // integer MVT.
  459. unsigned NumBits = LoadedVT.getSizeInBits();
  460. EVT NewLoadedVT;
  461. NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
  462. NumBits >>= 1;
  463. unsigned Alignment = LD->getAlignment();
  464. unsigned IncrementSize = NumBits / 8;
  465. ISD::LoadExtType HiExtType = LD->getExtensionType();
  466. // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
  467. if (HiExtType == ISD::NON_EXTLOAD)
  468. HiExtType = ISD::ZEXTLOAD;
  469. // Load the value in two parts
  470. SDValue Lo, Hi;
  471. if (DAG.getDataLayout().isLittleEndian()) {
  472. Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
  473. NewLoadedVT, LD->isVolatile(),
  474. LD->isNonTemporal(), LD->isInvariant(), Alignment,
  475. LD->getAAInfo());
  476. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  477. DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
  478. Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
  479. LD->getPointerInfo().getWithOffset(IncrementSize),
  480. NewLoadedVT, LD->isVolatile(),
  481. LD->isNonTemporal(),LD->isInvariant(),
  482. MinAlign(Alignment, IncrementSize), LD->getAAInfo());
  483. } else {
  484. Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
  485. NewLoadedVT, LD->isVolatile(),
  486. LD->isNonTemporal(), LD->isInvariant(), Alignment,
  487. LD->getAAInfo());
  488. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  489. DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
  490. Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
  491. LD->getPointerInfo().getWithOffset(IncrementSize),
  492. NewLoadedVT, LD->isVolatile(),
  493. LD->isNonTemporal(), LD->isInvariant(),
  494. MinAlign(Alignment, IncrementSize), LD->getAAInfo());
  495. }
  496. // aggregate the two parts
  497. SDValue ShiftAmount =
  498. DAG.getConstant(NumBits, dl, TLI.getShiftAmountTy(Hi.getValueType(),
  499. DAG.getDataLayout()));
  500. SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
  501. Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
  502. SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
  503. Hi.getValue(1));
  504. ValResult = Result;
  505. ChainResult = TF;
  506. }
  507. /// Some target cannot handle a variable insertion index for the
  508. /// INSERT_VECTOR_ELT instruction. In this case, it
  509. /// is necessary to spill the vector being inserted into to memory, perform
  510. /// the insert there, and then read the result back.
  511. SDValue SelectionDAGLegalize::
  512. PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
  513. SDLoc dl) {
  514. SDValue Tmp1 = Vec;
  515. SDValue Tmp2 = Val;
  516. SDValue Tmp3 = Idx;
  517. // If the target doesn't support this, we have to spill the input vector
  518. // to a temporary stack slot, update the element, then reload it. This is
  519. // badness. We could also load the value into a vector register (either
  520. // with a "move to register" or "extload into register" instruction, then
  521. // permute it into place, if the idx is a constant and if the idx is
  522. // supported by the target.
  523. EVT VT = Tmp1.getValueType();
  524. EVT EltVT = VT.getVectorElementType();
  525. EVT IdxVT = Tmp3.getValueType();
  526. EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
  527. SDValue StackPtr = DAG.CreateStackTemporary(VT);
  528. int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
  529. // Store the vector.
  530. SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
  531. MachinePointerInfo::getFixedStack(SPFI),
  532. false, false, 0);
  533. // Truncate or zero extend offset to target pointer type.
  534. unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
  535. Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
  536. // Add the offset to the index.
  537. unsigned EltSize = EltVT.getSizeInBits()/8;
  538. Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,
  539. DAG.getConstant(EltSize, dl, IdxVT));
  540. SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
  541. // Store the scalar value.
  542. Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
  543. false, false, 0);
  544. // Load the updated vector.
  545. return DAG.getLoad(VT, dl, Ch, StackPtr,
  546. MachinePointerInfo::getFixedStack(SPFI), false, false,
  547. false, 0);
  548. }
  549. SDValue SelectionDAGLegalize::
  550. ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, SDLoc dl) {
  551. if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
  552. // SCALAR_TO_VECTOR requires that the type of the value being inserted
  553. // match the element type of the vector being created, except for
  554. // integers in which case the inserted value can be over width.
  555. EVT EltVT = Vec.getValueType().getVectorElementType();
  556. if (Val.getValueType() == EltVT ||
  557. (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
  558. SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
  559. Vec.getValueType(), Val);
  560. unsigned NumElts = Vec.getValueType().getVectorNumElements();
  561. // We generate a shuffle of InVec and ScVec, so the shuffle mask
  562. // should be 0,1,2,3,4,5... with the appropriate element replaced with
  563. // elt 0 of the RHS.
  564. SmallVector<int, 8> ShufOps;
  565. for (unsigned i = 0; i != NumElts; ++i)
  566. ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
  567. return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
  568. &ShufOps[0]);
  569. }
  570. }
  571. return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
  572. }
  573. SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
  574. // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
  575. // FIXME: We shouldn't do this for TargetConstantFP's.
  576. // FIXME: move this to the DAG Combiner! Note that we can't regress due
  577. // to phase ordering between legalized code and the dag combiner. This
  578. // probably means that we need to integrate dag combiner and legalizer
  579. // together.
  580. // We generally can't do this one for long doubles.
  581. SDValue Chain = ST->getChain();
  582. SDValue Ptr = ST->getBasePtr();
  583. unsigned Alignment = ST->getAlignment();
  584. bool isVolatile = ST->isVolatile();
  585. bool isNonTemporal = ST->isNonTemporal();
  586. AAMDNodes AAInfo = ST->getAAInfo();
  587. SDLoc dl(ST);
  588. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
  589. if (CFP->getValueType(0) == MVT::f32 &&
  590. TLI.isTypeLegal(MVT::i32)) {
  591. SDValue Con = DAG.getConstant(CFP->getValueAPF().
  592. bitcastToAPInt().zextOrTrunc(32),
  593. SDLoc(CFP), MVT::i32);
  594. return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
  595. isVolatile, isNonTemporal, Alignment, AAInfo);
  596. }
  597. if (CFP->getValueType(0) == MVT::f64) {
  598. // If this target supports 64-bit registers, do a single 64-bit store.
  599. if (TLI.isTypeLegal(MVT::i64)) {
  600. SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
  601. zextOrTrunc(64), SDLoc(CFP), MVT::i64);
  602. return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
  603. isVolatile, isNonTemporal, Alignment, AAInfo);
  604. }
  605. if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
  606. // Otherwise, if the target supports 32-bit registers, use 2 32-bit
  607. // stores. If the target supports neither 32- nor 64-bits, this
  608. // xform is certainly not worth it.
  609. const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
  610. SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
  611. SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
  612. if (DAG.getDataLayout().isBigEndian())
  613. std::swap(Lo, Hi);
  614. Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(), isVolatile,
  615. isNonTemporal, Alignment, AAInfo);
  616. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  617. DAG.getConstant(4, dl, Ptr.getValueType()));
  618. Hi = DAG.getStore(Chain, dl, Hi, Ptr,
  619. ST->getPointerInfo().getWithOffset(4),
  620. isVolatile, isNonTemporal, MinAlign(Alignment, 4U),
  621. AAInfo);
  622. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
  623. }
  624. }
  625. }
  626. return SDValue(nullptr, 0);
  627. }
  628. void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
  629. StoreSDNode *ST = cast<StoreSDNode>(Node);
  630. SDValue Chain = ST->getChain();
  631. SDValue Ptr = ST->getBasePtr();
  632. SDLoc dl(Node);
  633. unsigned Alignment = ST->getAlignment();
  634. bool isVolatile = ST->isVolatile();
  635. bool isNonTemporal = ST->isNonTemporal();
  636. AAMDNodes AAInfo = ST->getAAInfo();
  637. if (!ST->isTruncatingStore()) {
  638. if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
  639. ReplaceNode(ST, OptStore);
  640. return;
  641. }
  642. {
  643. SDValue Value = ST->getValue();
  644. MVT VT = Value.getSimpleValueType();
  645. switch (TLI.getOperationAction(ISD::STORE, VT)) {
  646. default: llvm_unreachable("This action is not supported yet!");
  647. case TargetLowering::Legal: {
  648. // If this is an unaligned store and the target doesn't support it,
  649. // expand it.
  650. unsigned AS = ST->getAddressSpace();
  651. unsigned Align = ST->getAlignment();
  652. if (!TLI.allowsMisalignedMemoryAccesses(ST->getMemoryVT(), AS, Align)) {
  653. Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
  654. unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
  655. if (Align < ABIAlignment)
  656. ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this);
  657. }
  658. break;
  659. }
  660. case TargetLowering::Custom: {
  661. SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
  662. if (Res && Res != SDValue(Node, 0))
  663. ReplaceNode(SDValue(Node, 0), Res);
  664. return;
  665. }
  666. case TargetLowering::Promote: {
  667. MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
  668. assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
  669. "Can only promote stores to same size type");
  670. Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
  671. SDValue Result =
  672. DAG.getStore(Chain, dl, Value, Ptr,
  673. ST->getPointerInfo(), isVolatile,
  674. isNonTemporal, Alignment, AAInfo);
  675. ReplaceNode(SDValue(Node, 0), Result);
  676. break;
  677. }
  678. }
  679. return;
  680. }
  681. } else {
  682. SDValue Value = ST->getValue();
  683. EVT StVT = ST->getMemoryVT();
  684. unsigned StWidth = StVT.getSizeInBits();
  685. auto &DL = DAG.getDataLayout();
  686. if (StWidth != StVT.getStoreSizeInBits()) {
  687. // Promote to a byte-sized store with upper bits zero if not
  688. // storing an integral number of bytes. For example, promote
  689. // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
  690. EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
  691. StVT.getStoreSizeInBits());
  692. Value = DAG.getZeroExtendInReg(Value, dl, StVT);
  693. SDValue Result =
  694. DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
  695. NVT, isVolatile, isNonTemporal, Alignment, AAInfo);
  696. ReplaceNode(SDValue(Node, 0), Result);
  697. } else if (StWidth & (StWidth - 1)) {
  698. // If not storing a power-of-2 number of bits, expand as two stores.
  699. assert(!StVT.isVector() && "Unsupported truncstore!");
  700. unsigned RoundWidth = 1 << Log2_32(StWidth);
  701. assert(RoundWidth < StWidth);
  702. unsigned ExtraWidth = StWidth - RoundWidth;
  703. assert(ExtraWidth < RoundWidth);
  704. assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
  705. "Store size not an integral number of bytes!");
  706. EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
  707. EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
  708. SDValue Lo, Hi;
  709. unsigned IncrementSize;
  710. if (DL.isLittleEndian()) {
  711. // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
  712. // Store the bottom RoundWidth bits.
  713. Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
  714. RoundVT,
  715. isVolatile, isNonTemporal, Alignment,
  716. AAInfo);
  717. // Store the remaining ExtraWidth bits.
  718. IncrementSize = RoundWidth / 8;
  719. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  720. DAG.getConstant(IncrementSize, dl,
  721. Ptr.getValueType()));
  722. Hi = DAG.getNode(
  723. ISD::SRL, dl, Value.getValueType(), Value,
  724. DAG.getConstant(RoundWidth, dl,
  725. TLI.getShiftAmountTy(Value.getValueType(), DL)));
  726. Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
  727. ST->getPointerInfo().getWithOffset(IncrementSize),
  728. ExtraVT, isVolatile, isNonTemporal,
  729. MinAlign(Alignment, IncrementSize), AAInfo);
  730. } else {
  731. // Big endian - avoid unaligned stores.
  732. // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
  733. // Store the top RoundWidth bits.
  734. Hi = DAG.getNode(
  735. ISD::SRL, dl, Value.getValueType(), Value,
  736. DAG.getConstant(ExtraWidth, dl,
  737. TLI.getShiftAmountTy(Value.getValueType(), DL)));
  738. Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(),
  739. RoundVT, isVolatile, isNonTemporal, Alignment,
  740. AAInfo);
  741. // Store the remaining ExtraWidth bits.
  742. IncrementSize = RoundWidth / 8;
  743. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  744. DAG.getConstant(IncrementSize, dl,
  745. Ptr.getValueType()));
  746. Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
  747. ST->getPointerInfo().getWithOffset(IncrementSize),
  748. ExtraVT, isVolatile, isNonTemporal,
  749. MinAlign(Alignment, IncrementSize), AAInfo);
  750. }
  751. // The order of the stores doesn't matter.
  752. SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
  753. ReplaceNode(SDValue(Node, 0), Result);
  754. } else {
  755. switch (TLI.getTruncStoreAction(ST->getValue().getSimpleValueType(),
  756. StVT.getSimpleVT())) {
  757. default: llvm_unreachable("This action is not supported yet!");
  758. case TargetLowering::Legal: {
  759. unsigned AS = ST->getAddressSpace();
  760. unsigned Align = ST->getAlignment();
  761. // If this is an unaligned store and the target doesn't support it,
  762. // expand it.
  763. if (!TLI.allowsMisalignedMemoryAccesses(ST->getMemoryVT(), AS, Align)) {
  764. Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
  765. unsigned ABIAlignment = DL.getABITypeAlignment(Ty);
  766. if (Align < ABIAlignment)
  767. ExpandUnalignedStore(cast<StoreSDNode>(Node), DAG, TLI, this);
  768. }
  769. break;
  770. }
  771. case TargetLowering::Custom: {
  772. SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
  773. if (Res && Res != SDValue(Node, 0))
  774. ReplaceNode(SDValue(Node, 0), Res);
  775. return;
  776. }
  777. case TargetLowering::Expand:
  778. assert(!StVT.isVector() &&
  779. "Vector Stores are handled in LegalizeVectorOps");
  780. // TRUNCSTORE:i16 i32 -> STORE i16
  781. assert(TLI.isTypeLegal(StVT) &&
  782. "Do not know how to expand this store!");
  783. Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
  784. SDValue Result =
  785. DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
  786. isVolatile, isNonTemporal, Alignment, AAInfo);
  787. ReplaceNode(SDValue(Node, 0), Result);
  788. break;
  789. }
  790. }
  791. }
  792. }
  793. void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
  794. LoadSDNode *LD = cast<LoadSDNode>(Node);
  795. SDValue Chain = LD->getChain(); // The chain.
  796. SDValue Ptr = LD->getBasePtr(); // The base pointer.
  797. SDValue Value; // The value returned by the load op.
  798. SDLoc dl(Node);
  799. ISD::LoadExtType ExtType = LD->getExtensionType();
  800. if (ExtType == ISD::NON_EXTLOAD) {
  801. MVT VT = Node->getSimpleValueType(0);
  802. SDValue RVal = SDValue(Node, 0);
  803. SDValue RChain = SDValue(Node, 1);
  804. switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
  805. default: llvm_unreachable("This action is not supported yet!");
  806. case TargetLowering::Legal: {
  807. unsigned AS = LD->getAddressSpace();
  808. unsigned Align = LD->getAlignment();
  809. // If this is an unaligned load and the target doesn't support it,
  810. // expand it.
  811. if (!TLI.allowsMisalignedMemoryAccesses(LD->getMemoryVT(), AS, Align)) {
  812. Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
  813. unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
  814. if (Align < ABIAlignment){
  815. ExpandUnalignedLoad(cast<LoadSDNode>(Node), DAG, TLI, RVal, RChain);
  816. }
  817. }
  818. break;
  819. }
  820. case TargetLowering::Custom: {
  821. SDValue Res = TLI.LowerOperation(RVal, DAG);
  822. if (Res.getNode()) {
  823. RVal = Res;
  824. RChain = Res.getValue(1);
  825. }
  826. break;
  827. }
  828. case TargetLowering::Promote: {
  829. MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
  830. assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
  831. "Can only promote loads to same size type");
  832. SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
  833. RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
  834. RChain = Res.getValue(1);
  835. break;
  836. }
  837. }
  838. if (RChain.getNode() != Node) {
  839. assert(RVal.getNode() != Node && "Load must be completely replaced");
  840. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
  841. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
  842. if (UpdatedNodes) {
  843. UpdatedNodes->insert(RVal.getNode());
  844. UpdatedNodes->insert(RChain.getNode());
  845. }
  846. ReplacedNode(Node);
  847. }
  848. return;
  849. }
  850. EVT SrcVT = LD->getMemoryVT();
  851. unsigned SrcWidth = SrcVT.getSizeInBits();
  852. unsigned Alignment = LD->getAlignment();
  853. bool isVolatile = LD->isVolatile();
  854. bool isNonTemporal = LD->isNonTemporal();
  855. bool isInvariant = LD->isInvariant();
  856. AAMDNodes AAInfo = LD->getAAInfo();
  857. if (SrcWidth != SrcVT.getStoreSizeInBits() &&
  858. // Some targets pretend to have an i1 loading operation, and actually
  859. // load an i8. This trick is correct for ZEXTLOAD because the top 7
  860. // bits are guaranteed to be zero; it helps the optimizers understand
  861. // that these bits are zero. It is also useful for EXTLOAD, since it
  862. // tells the optimizers that those bits are undefined. It would be
  863. // nice to have an effective generic way of getting these benefits...
  864. // Until such a way is found, don't insist on promoting i1 here.
  865. (SrcVT != MVT::i1 ||
  866. TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) ==
  867. TargetLowering::Promote)) {
  868. // Promote to a byte-sized load if not loading an integral number of
  869. // bytes. For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
  870. unsigned NewWidth = SrcVT.getStoreSizeInBits();
  871. EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
  872. SDValue Ch;
  873. // The extra bits are guaranteed to be zero, since we stored them that
  874. // way. A zext load from NVT thus automatically gives zext from SrcVT.
  875. ISD::LoadExtType NewExtType =
  876. ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
  877. SDValue Result =
  878. DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
  879. Chain, Ptr, LD->getPointerInfo(),
  880. NVT, isVolatile, isNonTemporal, isInvariant, Alignment,
  881. AAInfo);
  882. Ch = Result.getValue(1); // The chain.
  883. if (ExtType == ISD::SEXTLOAD)
  884. // Having the top bits zero doesn't help when sign extending.
  885. Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
  886. Result.getValueType(),
  887. Result, DAG.getValueType(SrcVT));
  888. else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
  889. // All the top bits are guaranteed to be zero - inform the optimizers.
  890. Result = DAG.getNode(ISD::AssertZext, dl,
  891. Result.getValueType(), Result,
  892. DAG.getValueType(SrcVT));
  893. Value = Result;
  894. Chain = Ch;
  895. } else if (SrcWidth & (SrcWidth - 1)) {
  896. // If not loading a power-of-2 number of bits, expand as two loads.
  897. assert(!SrcVT.isVector() && "Unsupported extload!");
  898. unsigned RoundWidth = 1 << Log2_32(SrcWidth);
  899. assert(RoundWidth < SrcWidth);
  900. unsigned ExtraWidth = SrcWidth - RoundWidth;
  901. assert(ExtraWidth < RoundWidth);
  902. assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
  903. "Load size not an integral number of bytes!");
  904. EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
  905. EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
  906. SDValue Lo, Hi, Ch;
  907. unsigned IncrementSize;
  908. auto &DL = DAG.getDataLayout();
  909. if (DL.isLittleEndian()) {
  910. // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
  911. // Load the bottom RoundWidth bits.
  912. Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0),
  913. Chain, Ptr,
  914. LD->getPointerInfo(), RoundVT, isVolatile,
  915. isNonTemporal, isInvariant, Alignment, AAInfo);
  916. // Load the remaining ExtraWidth bits.
  917. IncrementSize = RoundWidth / 8;
  918. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  919. DAG.getConstant(IncrementSize, dl,
  920. Ptr.getValueType()));
  921. Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
  922. LD->getPointerInfo().getWithOffset(IncrementSize),
  923. ExtraVT, isVolatile, isNonTemporal, isInvariant,
  924. MinAlign(Alignment, IncrementSize), AAInfo);
  925. // Build a factor node to remember that this load is independent of
  926. // the other one.
  927. Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
  928. Hi.getValue(1));
  929. // Move the top bits to the right place.
  930. Hi = DAG.getNode(
  931. ISD::SHL, dl, Hi.getValueType(), Hi,
  932. DAG.getConstant(RoundWidth, dl,
  933. TLI.getShiftAmountTy(Hi.getValueType(), DL)));
  934. // Join the hi and lo parts.
  935. Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
  936. } else {
  937. // Big endian - avoid unaligned loads.
  938. // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
  939. // Load the top RoundWidth bits.
  940. Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
  941. LD->getPointerInfo(), RoundVT, isVolatile,
  942. isNonTemporal, isInvariant, Alignment, AAInfo);
  943. // Load the remaining ExtraWidth bits.
  944. IncrementSize = RoundWidth / 8;
  945. Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
  946. DAG.getConstant(IncrementSize, dl,
  947. Ptr.getValueType()));
  948. Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
  949. dl, Node->getValueType(0), Chain, Ptr,
  950. LD->getPointerInfo().getWithOffset(IncrementSize),
  951. ExtraVT, isVolatile, isNonTemporal, isInvariant,
  952. MinAlign(Alignment, IncrementSize), AAInfo);
  953. // Build a factor node to remember that this load is independent of
  954. // the other one.
  955. Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
  956. Hi.getValue(1));
  957. // Move the top bits to the right place.
  958. Hi = DAG.getNode(
  959. ISD::SHL, dl, Hi.getValueType(), Hi,
  960. DAG.getConstant(ExtraWidth, dl,
  961. TLI.getShiftAmountTy(Hi.getValueType(), DL)));
  962. // Join the hi and lo parts.
  963. Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
  964. }
  965. Chain = Ch;
  966. } else {
  967. bool isCustom = false;
  968. switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0),
  969. SrcVT.getSimpleVT())) {
  970. default: llvm_unreachable("This action is not supported yet!");
  971. case TargetLowering::Custom:
  972. isCustom = true;
  973. // FALLTHROUGH
  974. case TargetLowering::Legal: {
  975. Value = SDValue(Node, 0);
  976. Chain = SDValue(Node, 1);
  977. if (isCustom) {
  978. SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
  979. if (Res.getNode()) {
  980. Value = Res;
  981. Chain = Res.getValue(1);
  982. }
  983. } else {
  984. // If this is an unaligned load and the target doesn't support
  985. // it, expand it.
  986. EVT MemVT = LD->getMemoryVT();
  987. unsigned AS = LD->getAddressSpace();
  988. unsigned Align = LD->getAlignment();
  989. if (!TLI.allowsMisalignedMemoryAccesses(MemVT, AS, Align)) {
  990. Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
  991. unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
  992. if (Align < ABIAlignment){
  993. ExpandUnalignedLoad(cast<LoadSDNode>(Node), DAG, TLI, Value, Chain);
  994. }
  995. }
  996. }
  997. break;
  998. }
  999. case TargetLowering::Expand:
  1000. if (!TLI.isLoadExtLegal(ISD::EXTLOAD, Node->getValueType(0), SrcVT)) {
  1001. // If the source type is not legal, see if there is a legal extload to
  1002. // an intermediate type that we can then extend further.
  1003. EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT());
  1004. if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
  1005. TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) {
  1006. // If we are loading a legal type, this is a non-extload followed by a
  1007. // full extend.
  1008. ISD::LoadExtType MidExtType =
  1009. (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
  1010. SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
  1011. SrcVT, LD->getMemOperand());
  1012. unsigned ExtendOp =
  1013. ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType);
  1014. Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
  1015. Chain = Load.getValue(1);
  1016. break;
  1017. }
  1018. }
  1019. assert(!SrcVT.isVector() &&
  1020. "Vector Loads are handled in LegalizeVectorOps");
  1021. // FIXME: This does not work for vectors on most targets. Sign-
  1022. // and zero-extend operations are currently folded into extending
  1023. // loads, whether they are legal or not, and then we end up here
  1024. // without any support for legalizing them.
  1025. assert(ExtType != ISD::EXTLOAD &&
  1026. "EXTLOAD should always be supported!");
  1027. // Turn the unsupported load into an EXTLOAD followed by an
  1028. // explicit zero/sign extend inreg.
  1029. SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
  1030. Node->getValueType(0),
  1031. Chain, Ptr, SrcVT,
  1032. LD->getMemOperand());
  1033. SDValue ValRes;
  1034. if (ExtType == ISD::SEXTLOAD)
  1035. ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
  1036. Result.getValueType(),
  1037. Result, DAG.getValueType(SrcVT));
  1038. else
  1039. ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
  1040. Value = ValRes;
  1041. Chain = Result.getValue(1);
  1042. break;
  1043. }
  1044. }
  1045. // Since loads produce two values, make sure to remember that we legalized
  1046. // both of them.
  1047. if (Chain.getNode() != Node) {
  1048. assert(Value.getNode() != Node && "Load must be completely replaced");
  1049. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
  1050. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
  1051. if (UpdatedNodes) {
  1052. UpdatedNodes->insert(Value.getNode());
  1053. UpdatedNodes->insert(Chain.getNode());
  1054. }
  1055. ReplacedNode(Node);
  1056. }
  1057. }
  1058. /// Return a legal replacement for the given operation, with all legal operands.
  1059. void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
  1060. DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
  1061. if (Node->getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
  1062. return;
  1063. #ifndef NDEBUG
  1064. for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
  1065. assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
  1066. TargetLowering::TypeLegal &&
  1067. "Unexpected illegal type!");
  1068. for (const SDValue &Op : Node->op_values())
  1069. assert((TLI.getTypeAction(*DAG.getContext(),
  1070. Op.getValueType()) == TargetLowering::TypeLegal ||
  1071. Op.getOpcode() == ISD::TargetConstant) &&
  1072. "Unexpected illegal type!");
  1073. #endif
  1074. // Figure out the correct action; the way to query this varies by opcode
  1075. TargetLowering::LegalizeAction Action = TargetLowering::Legal;
  1076. bool SimpleFinishLegalizing = true;
  1077. switch (Node->getOpcode()) {
  1078. case ISD::INTRINSIC_W_CHAIN:
  1079. case ISD::INTRINSIC_WO_CHAIN:
  1080. case ISD::INTRINSIC_VOID:
  1081. case ISD::STACKSAVE:
  1082. Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
  1083. break;
  1084. case ISD::VAARG:
  1085. Action = TLI.getOperationAction(Node->getOpcode(),
  1086. Node->getValueType(0));
  1087. if (Action != TargetLowering::Promote)
  1088. Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
  1089. break;
  1090. case ISD::FP_TO_FP16:
  1091. case ISD::SINT_TO_FP:
  1092. case ISD::UINT_TO_FP:
  1093. case ISD::EXTRACT_VECTOR_ELT:
  1094. Action = TLI.getOperationAction(Node->getOpcode(),
  1095. Node->getOperand(0).getValueType());
  1096. break;
  1097. case ISD::FP_ROUND_INREG:
  1098. case ISD::SIGN_EXTEND_INREG: {
  1099. EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
  1100. Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
  1101. break;
  1102. }
  1103. case ISD::ATOMIC_STORE: {
  1104. Action = TLI.getOperationAction(Node->getOpcode(),
  1105. Node->getOperand(2).getValueType());
  1106. break;
  1107. }
  1108. case ISD::SELECT_CC:
  1109. case ISD::SETCC:
  1110. case ISD::BR_CC: {
  1111. unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
  1112. Node->getOpcode() == ISD::SETCC ? 2 : 1;
  1113. unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
  1114. MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
  1115. ISD::CondCode CCCode =
  1116. cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
  1117. Action = TLI.getCondCodeAction(CCCode, OpVT);
  1118. if (Action == TargetLowering::Legal) {
  1119. if (Node->getOpcode() == ISD::SELECT_CC)
  1120. Action = TLI.getOperationAction(Node->getOpcode(),
  1121. Node->getValueType(0));
  1122. else
  1123. Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
  1124. }
  1125. break;
  1126. }
  1127. case ISD::LOAD:
  1128. case ISD::STORE:
  1129. // FIXME: Model these properly. LOAD and STORE are complicated, and
  1130. // STORE expects the unlegalized operand in some cases.
  1131. SimpleFinishLegalizing = false;
  1132. break;
  1133. case ISD::CALLSEQ_START:
  1134. case ISD::CALLSEQ_END:
  1135. // FIXME: This shouldn't be necessary. These nodes have special properties
  1136. // dealing with the recursive nature of legalization. Removing this
  1137. // special case should be done as part of making LegalizeDAG non-recursive.
  1138. SimpleFinishLegalizing = false;
  1139. break;
  1140. case ISD::EXTRACT_ELEMENT:
  1141. case ISD::FLT_ROUNDS_:
  1142. case ISD::FPOWI:
  1143. case ISD::MERGE_VALUES:
  1144. case ISD::EH_RETURN:
  1145. case ISD::FRAME_TO_ARGS_OFFSET:
  1146. case ISD::EH_SJLJ_SETJMP:
  1147. case ISD::EH_SJLJ_LONGJMP:
  1148. // These operations lie about being legal: when they claim to be legal,
  1149. // they should actually be expanded.
  1150. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  1151. if (Action == TargetLowering::Legal)
  1152. Action = TargetLowering::Expand;
  1153. break;
  1154. case ISD::INIT_TRAMPOLINE:
  1155. case ISD::ADJUST_TRAMPOLINE:
  1156. case ISD::FRAMEADDR:
  1157. case ISD::RETURNADDR:
  1158. // These operations lie about being legal: when they claim to be legal,
  1159. // they should actually be custom-lowered.
  1160. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  1161. if (Action == TargetLowering::Legal)
  1162. Action = TargetLowering::Custom;
  1163. break;
  1164. case ISD::READ_REGISTER:
  1165. case ISD::WRITE_REGISTER:
  1166. // Named register is legal in the DAG, but blocked by register name
  1167. // selection if not implemented by target (to chose the correct register)
  1168. // They'll be converted to Copy(To/From)Reg.
  1169. Action = TargetLowering::Legal;
  1170. break;
  1171. case ISD::DEBUGTRAP:
  1172. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  1173. if (Action == TargetLowering::Expand) {
  1174. // replace ISD::DEBUGTRAP with ISD::TRAP
  1175. SDValue NewVal;
  1176. NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
  1177. Node->getOperand(0));
  1178. ReplaceNode(Node, NewVal.getNode());
  1179. LegalizeOp(NewVal.getNode());
  1180. return;
  1181. }
  1182. break;
  1183. default:
  1184. if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
  1185. Action = TargetLowering::Legal;
  1186. } else {
  1187. Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
  1188. }
  1189. break;
  1190. }
  1191. if (SimpleFinishLegalizing) {
  1192. SDNode *NewNode = Node;
  1193. switch (Node->getOpcode()) {
  1194. default: break;
  1195. case ISD::SHL:
  1196. case ISD::SRL:
  1197. case ISD::SRA:
  1198. case ISD::ROTL:
  1199. case ISD::ROTR:
  1200. // Legalizing shifts/rotates requires adjusting the shift amount
  1201. // to the appropriate width.
  1202. if (!Node->getOperand(1).getValueType().isVector()) {
  1203. SDValue SAO =
  1204. DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
  1205. Node->getOperand(1));
  1206. HandleSDNode Handle(SAO);
  1207. LegalizeOp(SAO.getNode());
  1208. NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
  1209. Handle.getValue());
  1210. }
  1211. break;
  1212. case ISD::SRL_PARTS:
  1213. case ISD::SRA_PARTS:
  1214. case ISD::SHL_PARTS:
  1215. // Legalizing shifts/rotates requires adjusting the shift amount
  1216. // to the appropriate width.
  1217. if (!Node->getOperand(2).getValueType().isVector()) {
  1218. SDValue SAO =
  1219. DAG.getShiftAmountOperand(Node->getOperand(0).getValueType(),
  1220. Node->getOperand(2));
  1221. HandleSDNode Handle(SAO);
  1222. LegalizeOp(SAO.getNode());
  1223. NewNode = DAG.UpdateNodeOperands(Node, Node->getOperand(0),
  1224. Node->getOperand(1),
  1225. Handle.getValue());
  1226. }
  1227. break;
  1228. }
  1229. if (NewNode != Node) {
  1230. ReplaceNode(Node, NewNode);
  1231. Node = NewNode;
  1232. }
  1233. switch (Action) {
  1234. case TargetLowering::Legal:
  1235. return;
  1236. case TargetLowering::Custom: {
  1237. // FIXME: The handling for custom lowering with multiple results is
  1238. // a complete mess.
  1239. SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
  1240. if (Res.getNode()) {
  1241. if (!(Res.getNode() != Node || Res.getResNo() != 0))
  1242. return;
  1243. if (Node->getNumValues() == 1) {
  1244. // We can just directly replace this node with the lowered value.
  1245. ReplaceNode(SDValue(Node, 0), Res);
  1246. return;
  1247. }
  1248. SmallVector<SDValue, 8> ResultVals;
  1249. for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
  1250. ResultVals.push_back(Res.getValue(i));
  1251. ReplaceNode(Node, ResultVals.data());
  1252. return;
  1253. }
  1254. }
  1255. // FALL THROUGH
  1256. case TargetLowering::Expand:
  1257. ExpandNode(Node);
  1258. return;
  1259. case TargetLowering::Promote:
  1260. PromoteNode(Node);
  1261. return;
  1262. }
  1263. }
  1264. switch (Node->getOpcode()) {
  1265. default:
  1266. #ifndef NDEBUG
  1267. dbgs() << "NODE: ";
  1268. Node->dump( &DAG);
  1269. dbgs() << "\n";
  1270. #endif
  1271. llvm_unreachable("Do not know how to legalize this operator!");
  1272. case ISD::CALLSEQ_START:
  1273. case ISD::CALLSEQ_END:
  1274. break;
  1275. case ISD::LOAD: {
  1276. return LegalizeLoadOps(Node);
  1277. }
  1278. case ISD::STORE: {
  1279. return LegalizeStoreOps(Node);
  1280. }
  1281. }
  1282. }
  1283. SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
  1284. SDValue Vec = Op.getOperand(0);
  1285. SDValue Idx = Op.getOperand(1);
  1286. SDLoc dl(Op);
  1287. // Before we generate a new store to a temporary stack slot, see if there is
  1288. // already one that we can use. There often is because when we scalarize
  1289. // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
  1290. // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
  1291. // the vector. If all are expanded here, we don't want one store per vector
  1292. // element.
  1293. SDValue StackPtr, Ch;
  1294. for (SDNode::use_iterator UI = Vec.getNode()->use_begin(),
  1295. UE = Vec.getNode()->use_end(); UI != UE; ++UI) {
  1296. SDNode *User = *UI;
  1297. if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
  1298. if (ST->isIndexed() || ST->isTruncatingStore() ||
  1299. ST->getValue() != Vec)
  1300. continue;
  1301. // Make sure that nothing else could have stored into the destination of
  1302. // this store.
  1303. if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
  1304. continue;
  1305. StackPtr = ST->getBasePtr();
  1306. Ch = SDValue(ST, 0);
  1307. break;
  1308. }
  1309. }
  1310. if (!Ch.getNode()) {
  1311. // Store the value to a temporary stack slot, then LOAD the returned part.
  1312. StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
  1313. Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
  1314. MachinePointerInfo(), false, false, 0);
  1315. }
  1316. // Add the offset to the index.
  1317. unsigned EltSize =
  1318. Vec.getValueType().getVectorElementType().getSizeInBits()/8;
  1319. Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
  1320. DAG.getConstant(EltSize, SDLoc(Vec), Idx.getValueType()));
  1321. Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1322. StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
  1323. SDValue NewLoad;
  1324. if (Op.getValueType().isVector())
  1325. NewLoad = DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,
  1326. MachinePointerInfo(), false, false, false, 0);
  1327. else
  1328. NewLoad = DAG.getExtLoad(
  1329. ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr, MachinePointerInfo(),
  1330. Vec.getValueType().getVectorElementType(), false, false, false, 0);
  1331. // Replace the chain going out of the store, by the one out of the load.
  1332. DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
  1333. // We introduced a cycle though, so update the loads operands, making sure
  1334. // to use the original store's chain as an incoming chain.
  1335. SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(),
  1336. NewLoad->op_end());
  1337. NewLoadOperands[0] = Ch;
  1338. NewLoad =
  1339. SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
  1340. return NewLoad;
  1341. }
  1342. SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
  1343. assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
  1344. SDValue Vec = Op.getOperand(0);
  1345. SDValue Part = Op.getOperand(1);
  1346. SDValue Idx = Op.getOperand(2);
  1347. SDLoc dl(Op);
  1348. // Store the value to a temporary stack slot, then LOAD the returned part.
  1349. SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
  1350. int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
  1351. MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
  1352. // First store the whole vector.
  1353. SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
  1354. false, false, 0);
  1355. // Then store the inserted part.
  1356. // Add the offset to the index.
  1357. unsigned EltSize =
  1358. Vec.getValueType().getVectorElementType().getSizeInBits()/8;
  1359. Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
  1360. DAG.getConstant(EltSize, SDLoc(Vec), Idx.getValueType()));
  1361. Idx = DAG.getZExtOrTrunc(Idx, dl, TLI.getPointerTy(DAG.getDataLayout()));
  1362. SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
  1363. StackPtr);
  1364. // Store the subvector.
  1365. Ch = DAG.getStore(Ch, dl, Part, SubStackPtr,
  1366. MachinePointerInfo(), false, false, 0);
  1367. // Finally, load the updated vector.
  1368. return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
  1369. false, false, false, 0);
  1370. }
  1371. SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
  1372. // We can't handle this case efficiently. Allocate a sufficiently
  1373. // aligned object on the stack, store each element into it, then load
  1374. // the result as a vector.
  1375. // Create the stack frame object.
  1376. EVT VT = Node->getValueType(0);
  1377. EVT EltVT = VT.getVectorElementType();
  1378. SDLoc dl(Node);
  1379. SDValue FIPtr = DAG.CreateStackTemporary(VT);
  1380. int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
  1381. MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
  1382. // Emit a store of each element to the stack slot.
  1383. SmallVector<SDValue, 8> Stores;
  1384. unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
  1385. // Store (in the right endianness) the elements to memory.
  1386. for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
  1387. // Ignore undef elements.
  1388. if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
  1389. unsigned Offset = TypeByteSize*i;
  1390. SDValue Idx = DAG.getConstant(Offset, dl, FIPtr.getValueType());
  1391. Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
  1392. // If the destination vector element type is narrower than the source
  1393. // element type, only store the bits necessary.
  1394. if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
  1395. Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
  1396. Node->getOperand(i), Idx,
  1397. PtrInfo.getWithOffset(Offset),
  1398. EltVT, false, false, 0));
  1399. } else
  1400. Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
  1401. Node->getOperand(i), Idx,
  1402. PtrInfo.getWithOffset(Offset),
  1403. false, false, 0));
  1404. }
  1405. SDValue StoreChain;
  1406. if (!Stores.empty()) // Not all undef elements?
  1407. StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
  1408. else
  1409. StoreChain = DAG.getEntryNode();
  1410. // Result is a load from the stack slot.
  1411. return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo,
  1412. false, false, false, 0);
  1413. }
  1414. SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
  1415. SDLoc dl(Node);
  1416. SDValue Tmp1 = Node->getOperand(0);
  1417. SDValue Tmp2 = Node->getOperand(1);
  1418. // Get the sign bit of the RHS. First obtain a value that has the same
  1419. // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
  1420. SDValue SignBit;
  1421. EVT FloatVT = Tmp2.getValueType();
  1422. EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
  1423. if (TLI.isTypeLegal(IVT)) {
  1424. // Convert to an integer with the same sign bit.
  1425. SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
  1426. } else {
  1427. auto &DL = DAG.getDataLayout();
  1428. // Store the float to memory, then load the sign part out as an integer.
  1429. MVT LoadTy = TLI.getPointerTy(DL);
  1430. // First create a temporary that is aligned for both the load and store.
  1431. SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
  1432. // Then store the float to it.
  1433. SDValue Ch =
  1434. DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
  1435. false, false, 0);
  1436. if (DL.isBigEndian()) {
  1437. assert(FloatVT.isByteSized() && "Unsupported floating point type!");
  1438. // Load out a legal integer with the same sign bit as the float.
  1439. SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
  1440. false, false, false, 0);
  1441. } else { // Little endian
  1442. SDValue LoadPtr = StackPtr;
  1443. // The float may be wider than the integer we are going to load. Advance
  1444. // the pointer so that the loaded integer will contain the sign bit.
  1445. unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
  1446. unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
  1447. LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(), LoadPtr,
  1448. DAG.getConstant(ByteOffset, dl,
  1449. LoadPtr.getValueType()));
  1450. // Load a legal integer containing the sign bit.
  1451. SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
  1452. false, false, false, 0);
  1453. // Move the sign bit to the top bit of the loaded integer.
  1454. unsigned BitShift = LoadTy.getSizeInBits() -
  1455. (FloatVT.getSizeInBits() - 8 * ByteOffset);
  1456. assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
  1457. if (BitShift)
  1458. SignBit = DAG.getNode(
  1459. ISD::SHL, dl, LoadTy, SignBit,
  1460. DAG.getConstant(BitShift, dl,
  1461. TLI.getShiftAmountTy(SignBit.getValueType(), DL)));
  1462. }
  1463. }
  1464. // Now get the sign bit proper, by seeing whether the value is negative.
  1465. SignBit = DAG.getSetCC(dl, getSetCCResultType(SignBit.getValueType()),
  1466. SignBit,
  1467. DAG.getConstant(0, dl, SignBit.getValueType()),
  1468. ISD::SETLT);
  1469. // Get the absolute value of the result.
  1470. SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
  1471. // Select between the nabs and abs value based on the sign bit of
  1472. // the input.
  1473. return DAG.getSelect(dl, AbsVal.getValueType(), SignBit,
  1474. DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
  1475. AbsVal);
  1476. }
  1477. void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
  1478. SmallVectorImpl<SDValue> &Results) {
  1479. unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
  1480. assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
  1481. " not tell us which reg is the stack pointer!");
  1482. SDLoc dl(Node);
  1483. EVT VT = Node->getValueType(0);
  1484. SDValue Tmp1 = SDValue(Node, 0);
  1485. SDValue Tmp2 = SDValue(Node, 1);
  1486. SDValue Tmp3 = Node->getOperand(2);
  1487. SDValue Chain = Tmp1.getOperand(0);
  1488. // Chain the dynamic stack allocation so that it doesn't modify the stack
  1489. // pointer when other instructions are using the stack.
  1490. Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true), dl);
  1491. SDValue Size = Tmp2.getOperand(1);
  1492. SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
  1493. Chain = SP.getValue(1);
  1494. unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
  1495. unsigned StackAlign =
  1496. DAG.getSubtarget().getFrameLowering()->getStackAlignment();
  1497. Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
  1498. if (Align > StackAlign)
  1499. Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
  1500. DAG.getConstant(-(uint64_t)Align, dl, VT));
  1501. Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
  1502. Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
  1503. DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
  1504. Results.push_back(Tmp1);
  1505. Results.push_back(Tmp2);
  1506. }
  1507. /// Legalize a SETCC with given LHS and RHS and condition code CC on the current
  1508. /// target.
  1509. ///
  1510. /// If the SETCC has been legalized using AND / OR, then the legalized node
  1511. /// will be stored in LHS. RHS and CC will be set to SDValue(). NeedInvert
  1512. /// will be set to false.
  1513. ///
  1514. /// If the SETCC has been legalized by using getSetCCSwappedOperands(),
  1515. /// then the values of LHS and RHS will be swapped, CC will be set to the
  1516. /// new condition, and NeedInvert will be set to false.
  1517. ///
  1518. /// If the SETCC has been legalized using the inverse condcode, then LHS and
  1519. /// RHS will be unchanged, CC will set to the inverted condcode, and NeedInvert
  1520. /// will be set to true. The caller must invert the result of the SETCC with
  1521. /// SelectionDAG::getLogicalNOT() or take equivalent action to swap the effect
  1522. /// of a true/false result.
  1523. ///
  1524. /// \returns true if the SetCC has been legalized, false if it hasn't.
  1525. bool SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
  1526. SDValue &LHS, SDValue &RHS,
  1527. SDValue &CC,
  1528. bool &NeedInvert,
  1529. SDLoc dl) {
  1530. MVT OpVT = LHS.getSimpleValueType();
  1531. ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
  1532. NeedInvert = false;
  1533. switch (TLI.getCondCodeAction(CCCode, OpVT)) {
  1534. default: llvm_unreachable("Unknown condition code action!");
  1535. case TargetLowering::Legal:
  1536. // Nothing to do.
  1537. break;
  1538. case TargetLowering::Expand: {
  1539. ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
  1540. if (TLI.isCondCodeLegal(InvCC, OpVT)) {
  1541. std::swap(LHS, RHS);
  1542. CC = DAG.getCondCode(InvCC);
  1543. return true;
  1544. }
  1545. ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
  1546. unsigned Opc = 0;
  1547. switch (CCCode) {
  1548. default: llvm_unreachable("Don't know how to expand this condition!");
  1549. case ISD::SETO:
  1550. assert(TLI.getCondCodeAction(ISD::SETOEQ, OpVT)
  1551. == TargetLowering::Legal
  1552. && "If SETO is expanded, SETOEQ must be legal!");
  1553. CC1 = ISD::SETOEQ; CC2 = ISD::SETOEQ; Opc = ISD::AND; break;
  1554. case ISD::SETUO:
  1555. assert(TLI.getCondCodeAction(ISD::SETUNE, OpVT)
  1556. == TargetLowering::Legal
  1557. && "If SETUO is expanded, SETUNE must be legal!");
  1558. CC1 = ISD::SETUNE; CC2 = ISD::SETUNE; Opc = ISD::OR; break;
  1559. case ISD::SETOEQ:
  1560. case ISD::SETOGT:
  1561. case ISD::SETOGE:
  1562. case ISD::SETOLT:
  1563. case ISD::SETOLE:
  1564. case ISD::SETONE:
  1565. case ISD::SETUEQ:
  1566. case ISD::SETUNE:
  1567. case ISD::SETUGT:
  1568. case ISD::SETUGE:
  1569. case ISD::SETULT:
  1570. case ISD::SETULE:
  1571. // If we are floating point, assign and break, otherwise fall through.
  1572. if (!OpVT.isInteger()) {
  1573. // We can use the 4th bit to tell if we are the unordered
  1574. // or ordered version of the opcode.
  1575. CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
  1576. Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
  1577. CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
  1578. break;
  1579. }
  1580. // Fallthrough if we are unsigned integer.
  1581. case ISD::SETLE:
  1582. case ISD::SETGT:
  1583. case ISD::SETGE:
  1584. case ISD::SETLT:
  1585. // We only support using the inverted operation, which is computed above
  1586. // and not a different manner of supporting expanding these cases.
  1587. llvm_unreachable("Don't know how to expand this condition!");
  1588. case ISD::SETNE:
  1589. case ISD::SETEQ:
  1590. // Try inverting the result of the inverse condition.
  1591. InvCC = CCCode == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ;
  1592. if (TLI.isCondCodeLegal(InvCC, OpVT)) {
  1593. CC = DAG.getCondCode(InvCC);
  1594. NeedInvert = true;
  1595. return true;
  1596. }
  1597. // If inverting the condition didn't work then we have no means to expand
  1598. // the condition.
  1599. llvm_unreachable("Don't know how to expand this condition!");
  1600. }
  1601. SDValue SetCC1, SetCC2;
  1602. if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
  1603. // If we aren't the ordered or unorder operation,
  1604. // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
  1605. SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
  1606. SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
  1607. } else {
  1608. // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
  1609. SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1);
  1610. SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2);
  1611. }
  1612. LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
  1613. RHS = SDValue();
  1614. CC = SDValue();
  1615. return true;
  1616. }
  1617. }
  1618. return false;
  1619. }
  1620. /// Emit a store/load combination to the stack. This stores
  1621. /// SrcOp to a stack slot of type SlotVT, truncating it if needed. It then does
  1622. /// a load from the stack slot to DestVT, extending it if needed.
  1623. /// The resultant code need not be legal.
  1624. SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
  1625. EVT SlotVT,
  1626. EVT DestVT,
  1627. SDLoc dl) {
  1628. // Create the stack frame object.
  1629. unsigned SrcAlign = DAG.getDataLayout().getPrefTypeAlignment(
  1630. SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
  1631. SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
  1632. FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
  1633. int SPFI = StackPtrFI->getIndex();
  1634. MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
  1635. unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
  1636. unsigned SlotSize = SlotVT.getSizeInBits();
  1637. unsigned DestSize = DestVT.getSizeInBits();
  1638. Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
  1639. unsigned DestAlign = DAG.getDataLayout().getPrefTypeAlignment(DestType);
  1640. // Emit a store to the stack slot. Use a truncstore if the input value is
  1641. // later than DestVT.
  1642. SDValue Store;
  1643. if (SrcSize > SlotSize)
  1644. Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
  1645. PtrInfo, SlotVT, false, false, SrcAlign);
  1646. else {
  1647. assert(SrcSize == SlotSize && "Invalid store");
  1648. Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
  1649. PtrInfo, false, false, SrcAlign);
  1650. }
  1651. // Result is a load from the stack slot.
  1652. if (SlotSize == DestSize)
  1653. return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
  1654. false, false, false, DestAlign);
  1655. assert(SlotSize < DestSize && "Unknown extension!");
  1656. return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
  1657. PtrInfo, SlotVT, false, false, false, DestAlign);
  1658. }
  1659. SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
  1660. SDLoc dl(Node);
  1661. // Create a vector sized/aligned stack slot, store the value to element #0,
  1662. // then load the whole vector back out.
  1663. SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
  1664. FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
  1665. int SPFI = StackPtrFI->getIndex();
  1666. SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
  1667. StackPtr,
  1668. MachinePointerInfo::getFixedStack(SPFI),
  1669. Node->getValueType(0).getVectorElementType(),
  1670. false, false, 0);
  1671. return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
  1672. MachinePointerInfo::getFixedStack(SPFI),
  1673. false, false, false, 0);
  1674. }
  1675. static bool
  1676. ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
  1677. const TargetLowering &TLI, SDValue &Res) {
  1678. unsigned NumElems = Node->getNumOperands();
  1679. SDLoc dl(Node);
  1680. EVT VT = Node->getValueType(0);
  1681. // Try to group the scalars into pairs, shuffle the pairs together, then
  1682. // shuffle the pairs of pairs together, etc. until the vector has
  1683. // been built. This will work only if all of the necessary shuffle masks
  1684. // are legal.
  1685. // We do this in two phases; first to check the legality of the shuffles,
  1686. // and next, assuming that all shuffles are legal, to create the new nodes.
  1687. for (int Phase = 0; Phase < 2; ++Phase) {
  1688. SmallVector<std::pair<SDValue, SmallVector<int, 16> >, 16> IntermedVals,
  1689. NewIntermedVals;
  1690. for (unsigned i = 0; i < NumElems; ++i) {
  1691. SDValue V = Node->getOperand(i);
  1692. if (V.getOpcode() == ISD::UNDEF)
  1693. continue;
  1694. SDValue Vec;
  1695. if (Phase)
  1696. Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
  1697. IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
  1698. }
  1699. while (IntermedVals.size() > 2) {
  1700. NewIntermedVals.clear();
  1701. for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
  1702. // This vector and the next vector are shuffled together (simply to
  1703. // append the one to the other).
  1704. SmallVector<int, 16> ShuffleVec(NumElems, -1);
  1705. SmallVector<int, 16> FinalIndices;
  1706. FinalIndices.reserve(IntermedVals[i].second.size() +
  1707. IntermedVals[i+1].second.size());
  1708. int k = 0;
  1709. for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
  1710. ++j, ++k) {
  1711. ShuffleVec[k] = j;
  1712. FinalIndices.push_back(IntermedVals[i].second[j]);
  1713. }
  1714. for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
  1715. ++j, ++k) {
  1716. ShuffleVec[k] = NumElems + j;
  1717. FinalIndices.push_back(IntermedVals[i+1].second[j]);
  1718. }
  1719. SDValue Shuffle;
  1720. if (Phase)
  1721. Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
  1722. IntermedVals[i+1].first,
  1723. ShuffleVec.data());
  1724. else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
  1725. return false;
  1726. NewIntermedVals.push_back(
  1727. std::make_pair(Shuffle, std::move(FinalIndices)));
  1728. }
  1729. // If we had an odd number of defined values, then append the last
  1730. // element to the array of new vectors.
  1731. if ((IntermedVals.size() & 1) != 0)
  1732. NewIntermedVals.push_back(IntermedVals.back());
  1733. IntermedVals.swap(NewIntermedVals);
  1734. }
  1735. assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
  1736. "Invalid number of intermediate vectors");
  1737. SDValue Vec1 = IntermedVals[0].first;
  1738. SDValue Vec2;
  1739. if (IntermedVals.size() > 1)
  1740. Vec2 = IntermedVals[1].first;
  1741. else if (Phase)
  1742. Vec2 = DAG.getUNDEF(VT);
  1743. SmallVector<int, 16> ShuffleVec(NumElems, -1);
  1744. for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
  1745. ShuffleVec[IntermedVals[0].second[i]] = i;
  1746. for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
  1747. ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
  1748. if (Phase)
  1749. Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
  1750. else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
  1751. return false;
  1752. }
  1753. return true;
  1754. }
  1755. /// Expand a BUILD_VECTOR node on targets that don't
  1756. /// support the operation, but do support the resultant vector type.
  1757. SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
  1758. unsigned NumElems = Node->getNumOperands();
  1759. SDValue Value1, Value2;
  1760. SDLoc dl(Node);
  1761. EVT VT = Node->getValueType(0);
  1762. EVT OpVT = Node->getOperand(0).getValueType();
  1763. EVT EltVT = VT.getVectorElementType();
  1764. // If the only non-undef value is the low element, turn this into a
  1765. // SCALAR_TO_VECTOR node. If this is { X, X, X, X }, determine X.
  1766. bool isOnlyLowElement = true;
  1767. bool MoreThanTwoValues = false;
  1768. bool isConstant = true;
  1769. for (unsigned i = 0; i < NumElems; ++i) {
  1770. SDValue V = Node->getOperand(i);
  1771. if (V.getOpcode() == ISD::UNDEF)
  1772. continue;
  1773. if (i > 0)
  1774. isOnlyLowElement = false;
  1775. if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
  1776. isConstant = false;
  1777. if (!Value1.getNode()) {
  1778. Value1 = V;
  1779. } else if (!Value2.getNode()) {
  1780. if (V != Value1)
  1781. Value2 = V;
  1782. } else if (V != Value1 && V != Value2) {
  1783. MoreThanTwoValues = true;
  1784. }
  1785. }
  1786. if (!Value1.getNode())
  1787. return DAG.getUNDEF(VT);
  1788. if (isOnlyLowElement)
  1789. return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
  1790. // If all elements are constants, create a load from the constant pool.
  1791. if (isConstant) {
  1792. SmallVector<Constant*, 16> CV;
  1793. for (unsigned i = 0, e = NumElems; i != e; ++i) {
  1794. if (ConstantFPSDNode *V =
  1795. dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
  1796. CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
  1797. } else if (ConstantSDNode *V =
  1798. dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
  1799. if (OpVT==EltVT)
  1800. CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
  1801. else {
  1802. // If OpVT and EltVT don't match, EltVT is not legal and the
  1803. // element values have been promoted/truncated earlier. Undo this;
  1804. // we don't want a v16i8 to become a v16i32 for example.
  1805. const ConstantInt *CI = V->getConstantIntValue();
  1806. CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
  1807. CI->getZExtValue()));
  1808. }
  1809. } else {
  1810. assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
  1811. Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
  1812. CV.push_back(UndefValue::get(OpNTy));
  1813. }
  1814. }
  1815. Constant *CP = ConstantVector::get(CV);
  1816. SDValue CPIdx =
  1817. DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout()));
  1818. unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
  1819. return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
  1820. MachinePointerInfo::getConstantPool(),
  1821. false, false, false, Alignment);
  1822. }
  1823. SmallSet<SDValue, 16> DefinedValues;
  1824. for (unsigned i = 0; i < NumElems; ++i) {
  1825. if (Node->getOperand(i).getOpcode() == ISD::UNDEF)
  1826. continue;
  1827. DefinedValues.insert(Node->getOperand(i));
  1828. }
  1829. if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
  1830. if (!MoreThanTwoValues) {
  1831. SmallVector<int, 8> ShuffleVec(NumElems, -1);
  1832. for (unsigned i = 0; i < NumElems; ++i) {
  1833. SDValue V = Node->getOperand(i);
  1834. if (V.getOpcode() == ISD::UNDEF)
  1835. continue;
  1836. ShuffleVec[i] = V == Value1 ? 0 : NumElems;
  1837. }
  1838. if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
  1839. // Get the splatted value into the low element of a vector register.
  1840. SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
  1841. SDValue Vec2;
  1842. if (Value2.getNode())
  1843. Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
  1844. else
  1845. Vec2 = DAG.getUNDEF(VT);
  1846. // Return shuffle(LowValVec, undef, <0,0,0,0>)
  1847. return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
  1848. }
  1849. } else {
  1850. SDValue Res;
  1851. if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
  1852. return Res;
  1853. }
  1854. }
  1855. // Otherwise, we can't handle this case efficiently.
  1856. return ExpandVectorBuildThroughStack(Node);
  1857. }
  1858. // Expand a node into a call to a libcall. If the result value
  1859. // does not fit into a register, return the lo part and set the hi part to the
  1860. // by-reg argument. If it does fit into a single register, return the result
  1861. // and leave the Hi part unset.
  1862. SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
  1863. bool isSigned) {
  1864. TargetLowering::ArgListTy Args;
  1865. TargetLowering::ArgListEntry Entry;
  1866. for (const SDValue &Op : Node->op_values()) {
  1867. EVT ArgVT = Op.getValueType();
  1868. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  1869. Entry.Node = Op;
  1870. Entry.Ty = ArgTy;
  1871. Entry.isSExt = isSigned;
  1872. Entry.isZExt = !isSigned;
  1873. Args.push_back(Entry);
  1874. }
  1875. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  1876. TLI.getPointerTy(DAG.getDataLayout()));
  1877. Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
  1878. // By default, the input chain to this libcall is the entry node of the
  1879. // function. If the libcall is going to be emitted as a tail call then
  1880. // TLI.isUsedByReturnOnly will change it to the right chain if the return
  1881. // node which is being folded has a non-entry input chain.
  1882. SDValue InChain = DAG.getEntryNode();
  1883. // isTailCall may be true since the callee does not reference caller stack
  1884. // frame. Check if it's in the right position.
  1885. SDValue TCChain = InChain;
  1886. bool isTailCall = TLI.isInTailCallPosition(DAG, Node, TCChain);
  1887. if (isTailCall)
  1888. InChain = TCChain;
  1889. TargetLowering::CallLoweringInfo CLI(DAG);
  1890. CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
  1891. .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
  1892. .setTailCall(isTailCall).setSExtResult(isSigned).setZExtResult(!isSigned);
  1893. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  1894. if (!CallInfo.second.getNode())
  1895. // It's a tailcall, return the chain (which is the DAG root).
  1896. return DAG.getRoot();
  1897. return CallInfo.first;
  1898. }
  1899. /// Generate a libcall taking the given operands as arguments
  1900. /// and returning a result of type RetVT.
  1901. SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
  1902. const SDValue *Ops, unsigned NumOps,
  1903. bool isSigned, SDLoc dl) {
  1904. TargetLowering::ArgListTy Args;
  1905. Args.reserve(NumOps);
  1906. TargetLowering::ArgListEntry Entry;
  1907. for (unsigned i = 0; i != NumOps; ++i) {
  1908. Entry.Node = Ops[i];
  1909. Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
  1910. Entry.isSExt = isSigned;
  1911. Entry.isZExt = !isSigned;
  1912. Args.push_back(Entry);
  1913. }
  1914. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  1915. TLI.getPointerTy(DAG.getDataLayout()));
  1916. Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
  1917. TargetLowering::CallLoweringInfo CLI(DAG);
  1918. CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
  1919. .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
  1920. .setSExtResult(isSigned).setZExtResult(!isSigned);
  1921. std::pair<SDValue,SDValue> CallInfo = TLI.LowerCallTo(CLI);
  1922. return CallInfo.first;
  1923. }
  1924. // Expand a node into a call to a libcall. Similar to
  1925. // ExpandLibCall except that the first operand is the in-chain.
  1926. std::pair<SDValue, SDValue>
  1927. SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
  1928. SDNode *Node,
  1929. bool isSigned) {
  1930. SDValue InChain = Node->getOperand(0);
  1931. TargetLowering::ArgListTy Args;
  1932. TargetLowering::ArgListEntry Entry;
  1933. for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
  1934. EVT ArgVT = Node->getOperand(i).getValueType();
  1935. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  1936. Entry.Node = Node->getOperand(i);
  1937. Entry.Ty = ArgTy;
  1938. Entry.isSExt = isSigned;
  1939. Entry.isZExt = !isSigned;
  1940. Args.push_back(Entry);
  1941. }
  1942. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  1943. TLI.getPointerTy(DAG.getDataLayout()));
  1944. Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
  1945. TargetLowering::CallLoweringInfo CLI(DAG);
  1946. CLI.setDebugLoc(SDLoc(Node)).setChain(InChain)
  1947. .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
  1948. .setSExtResult(isSigned).setZExtResult(!isSigned);
  1949. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  1950. return CallInfo;
  1951. }
  1952. SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
  1953. RTLIB::Libcall Call_F32,
  1954. RTLIB::Libcall Call_F64,
  1955. RTLIB::Libcall Call_F80,
  1956. RTLIB::Libcall Call_F128,
  1957. RTLIB::Libcall Call_PPCF128) {
  1958. RTLIB::Libcall LC;
  1959. switch (Node->getSimpleValueType(0).SimpleTy) {
  1960. default: llvm_unreachable("Unexpected request for libcall!");
  1961. case MVT::f32: LC = Call_F32; break;
  1962. case MVT::f64: LC = Call_F64; break;
  1963. case MVT::f80: LC = Call_F80; break;
  1964. case MVT::f128: LC = Call_F128; break;
  1965. case MVT::ppcf128: LC = Call_PPCF128; break;
  1966. }
  1967. return ExpandLibCall(LC, Node, false);
  1968. }
  1969. SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
  1970. RTLIB::Libcall Call_I8,
  1971. RTLIB::Libcall Call_I16,
  1972. RTLIB::Libcall Call_I32,
  1973. RTLIB::Libcall Call_I64,
  1974. RTLIB::Libcall Call_I128) {
  1975. RTLIB::Libcall LC;
  1976. switch (Node->getSimpleValueType(0).SimpleTy) {
  1977. default: llvm_unreachable("Unexpected request for libcall!");
  1978. case MVT::i8: LC = Call_I8; break;
  1979. case MVT::i16: LC = Call_I16; break;
  1980. case MVT::i32: LC = Call_I32; break;
  1981. case MVT::i64: LC = Call_I64; break;
  1982. case MVT::i128: LC = Call_I128; break;
  1983. }
  1984. return ExpandLibCall(LC, Node, isSigned);
  1985. }
  1986. /// Return true if divmod libcall is available.
  1987. static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
  1988. const TargetLowering &TLI) {
  1989. RTLIB::Libcall LC;
  1990. switch (Node->getSimpleValueType(0).SimpleTy) {
  1991. default: llvm_unreachable("Unexpected request for libcall!");
  1992. case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
  1993. case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
  1994. case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
  1995. case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
  1996. case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
  1997. }
  1998. return TLI.getLibcallName(LC) != nullptr;
  1999. }
  2000. /// Only issue divrem libcall if both quotient and remainder are needed.
  2001. static bool useDivRem(SDNode *Node, bool isSigned, bool isDIV) {
  2002. // The other use might have been replaced with a divrem already.
  2003. unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
  2004. unsigned OtherOpcode = 0;
  2005. if (isSigned)
  2006. OtherOpcode = isDIV ? ISD::SREM : ISD::SDIV;
  2007. else
  2008. OtherOpcode = isDIV ? ISD::UREM : ISD::UDIV;
  2009. SDValue Op0 = Node->getOperand(0);
  2010. SDValue Op1 = Node->getOperand(1);
  2011. for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
  2012. UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
  2013. SDNode *User = *UI;
  2014. if (User == Node)
  2015. continue;
  2016. if ((User->getOpcode() == OtherOpcode || User->getOpcode() == DivRemOpc) &&
  2017. User->getOperand(0) == Op0 &&
  2018. User->getOperand(1) == Op1)
  2019. return true;
  2020. }
  2021. return false;
  2022. }
  2023. /// Issue libcalls to __{u}divmod to compute div / rem pairs.
  2024. void
  2025. SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
  2026. SmallVectorImpl<SDValue> &Results) {
  2027. unsigned Opcode = Node->getOpcode();
  2028. bool isSigned = Opcode == ISD::SDIVREM;
  2029. RTLIB::Libcall LC;
  2030. switch (Node->getSimpleValueType(0).SimpleTy) {
  2031. default: llvm_unreachable("Unexpected request for libcall!");
  2032. case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
  2033. case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
  2034. case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
  2035. case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
  2036. case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
  2037. }
  2038. // The input chain to this libcall is the entry node of the function.
  2039. // Legalizing the call will automatically add the previous call to the
  2040. // dependence.
  2041. SDValue InChain = DAG.getEntryNode();
  2042. EVT RetVT = Node->getValueType(0);
  2043. Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
  2044. TargetLowering::ArgListTy Args;
  2045. TargetLowering::ArgListEntry Entry;
  2046. for (const SDValue &Op : Node->op_values()) {
  2047. EVT ArgVT = Op.getValueType();
  2048. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  2049. Entry.Node = Op;
  2050. Entry.Ty = ArgTy;
  2051. Entry.isSExt = isSigned;
  2052. Entry.isZExt = !isSigned;
  2053. Args.push_back(Entry);
  2054. }
  2055. // Also pass the return address of the remainder.
  2056. SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
  2057. Entry.Node = FIPtr;
  2058. Entry.Ty = RetTy->getPointerTo();
  2059. Entry.isSExt = isSigned;
  2060. Entry.isZExt = !isSigned;
  2061. Args.push_back(Entry);
  2062. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  2063. TLI.getPointerTy(DAG.getDataLayout()));
  2064. SDLoc dl(Node);
  2065. TargetLowering::CallLoweringInfo CLI(DAG);
  2066. CLI.setDebugLoc(dl).setChain(InChain)
  2067. .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
  2068. .setSExtResult(isSigned).setZExtResult(!isSigned);
  2069. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  2070. // Remainder is loaded back from the stack frame.
  2071. SDValue Rem = DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr,
  2072. MachinePointerInfo(), false, false, false, 0);
  2073. Results.push_back(CallInfo.first);
  2074. Results.push_back(Rem);
  2075. }
  2076. /// Return true if sincos libcall is available.
  2077. static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
  2078. RTLIB::Libcall LC;
  2079. switch (Node->getSimpleValueType(0).SimpleTy) {
  2080. default: llvm_unreachable("Unexpected request for libcall!");
  2081. case MVT::f32: LC = RTLIB::SINCOS_F32; break;
  2082. case MVT::f64: LC = RTLIB::SINCOS_F64; break;
  2083. case MVT::f80: LC = RTLIB::SINCOS_F80; break;
  2084. case MVT::f128: LC = RTLIB::SINCOS_F128; break;
  2085. case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
  2086. }
  2087. return TLI.getLibcallName(LC) != nullptr;
  2088. }
  2089. /// Return true if sincos libcall is available and can be used to combine sin
  2090. /// and cos.
  2091. static bool canCombineSinCosLibcall(SDNode *Node, const TargetLowering &TLI,
  2092. const TargetMachine &TM) {
  2093. if (!isSinCosLibcallAvailable(Node, TLI))
  2094. return false;
  2095. // GNU sin/cos functions set errno while sincos does not. Therefore
  2096. // combining sin and cos is only safe if unsafe-fpmath is enabled.
  2097. bool isGNU = Triple(TM.getTargetTriple()).getEnvironment() == Triple::GNU;
  2098. if (isGNU && !TM.Options.UnsafeFPMath)
  2099. return false;
  2100. return true;
  2101. }
  2102. /// Only issue sincos libcall if both sin and cos are needed.
  2103. static bool useSinCos(SDNode *Node) {
  2104. unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
  2105. ? ISD::FCOS : ISD::FSIN;
  2106. SDValue Op0 = Node->getOperand(0);
  2107. for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
  2108. UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
  2109. SDNode *User = *UI;
  2110. if (User == Node)
  2111. continue;
  2112. // The other user might have been turned into sincos already.
  2113. if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
  2114. return true;
  2115. }
  2116. return false;
  2117. }
  2118. /// Issue libcalls to sincos to compute sin / cos pairs.
  2119. void
  2120. SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
  2121. SmallVectorImpl<SDValue> &Results) {
  2122. RTLIB::Libcall LC;
  2123. switch (Node->getSimpleValueType(0).SimpleTy) {
  2124. default: llvm_unreachable("Unexpected request for libcall!");
  2125. case MVT::f32: LC = RTLIB::SINCOS_F32; break;
  2126. case MVT::f64: LC = RTLIB::SINCOS_F64; break;
  2127. case MVT::f80: LC = RTLIB::SINCOS_F80; break;
  2128. case MVT::f128: LC = RTLIB::SINCOS_F128; break;
  2129. case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
  2130. }
  2131. // The input chain to this libcall is the entry node of the function.
  2132. // Legalizing the call will automatically add the previous call to the
  2133. // dependence.
  2134. SDValue InChain = DAG.getEntryNode();
  2135. EVT RetVT = Node->getValueType(0);
  2136. Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
  2137. TargetLowering::ArgListTy Args;
  2138. TargetLowering::ArgListEntry Entry;
  2139. // Pass the argument.
  2140. Entry.Node = Node->getOperand(0);
  2141. Entry.Ty = RetTy;
  2142. Entry.isSExt = false;
  2143. Entry.isZExt = false;
  2144. Args.push_back(Entry);
  2145. // Pass the return address of sin.
  2146. SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
  2147. Entry.Node = SinPtr;
  2148. Entry.Ty = RetTy->getPointerTo();
  2149. Entry.isSExt = false;
  2150. Entry.isZExt = false;
  2151. Args.push_back(Entry);
  2152. // Also pass the return address of the cos.
  2153. SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
  2154. Entry.Node = CosPtr;
  2155. Entry.Ty = RetTy->getPointerTo();
  2156. Entry.isSExt = false;
  2157. Entry.isZExt = false;
  2158. Args.push_back(Entry);
  2159. SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
  2160. TLI.getPointerTy(DAG.getDataLayout()));
  2161. SDLoc dl(Node);
  2162. TargetLowering::CallLoweringInfo CLI(DAG);
  2163. CLI.setDebugLoc(dl).setChain(InChain)
  2164. .setCallee(TLI.getLibcallCallingConv(LC),
  2165. Type::getVoidTy(*DAG.getContext()), Callee, std::move(Args), 0);
  2166. std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
  2167. Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr,
  2168. MachinePointerInfo(), false, false, false, 0));
  2169. Results.push_back(DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr,
  2170. MachinePointerInfo(), false, false, false, 0));
  2171. }
  2172. /// This function is responsible for legalizing a
  2173. /// INT_TO_FP operation of the specified operand when the target requests that
  2174. /// we expand it. At this point, we know that the result and operand types are
  2175. /// legal for the target.
  2176. SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
  2177. SDValue Op0,
  2178. EVT DestVT,
  2179. SDLoc dl) {
  2180. if (Op0.getValueType() == MVT::i32 && TLI.isTypeLegal(MVT::f64)) {
  2181. // simple 32-bit [signed|unsigned] integer to float/double expansion
  2182. // Get the stack frame index of a 8 byte buffer.
  2183. SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
  2184. // word offset constant for Hi/Lo address computation
  2185. SDValue WordOff = DAG.getConstant(sizeof(int), dl,
  2186. StackSlot.getValueType());
  2187. // set up Hi and Lo (into buffer) address based on endian
  2188. SDValue Hi = StackSlot;
  2189. SDValue Lo = DAG.getNode(ISD::ADD, dl, StackSlot.getValueType(),
  2190. StackSlot, WordOff);
  2191. if (DAG.getDataLayout().isLittleEndian())
  2192. std::swap(Hi, Lo);
  2193. // if signed map to unsigned space
  2194. SDValue Op0Mapped;
  2195. if (isSigned) {
  2196. // constant used to invert sign bit (signed to unsigned mapping)
  2197. SDValue SignBit = DAG.getConstant(0x80000000u, dl, MVT::i32);
  2198. Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
  2199. } else {
  2200. Op0Mapped = Op0;
  2201. }
  2202. // store the lo of the constructed double - based on integer input
  2203. SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
  2204. Op0Mapped, Lo, MachinePointerInfo(),
  2205. false, false, 0);
  2206. // initial hi portion of constructed double
  2207. SDValue InitialHi = DAG.getConstant(0x43300000u, dl, MVT::i32);
  2208. // store the hi of the constructed double - biased exponent
  2209. SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
  2210. MachinePointerInfo(),
  2211. false, false, 0);
  2212. // load the constructed double
  2213. SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
  2214. MachinePointerInfo(), false, false, false, 0);
  2215. // FP constant to bias correct the final result
  2216. SDValue Bias = DAG.getConstantFP(isSigned ?
  2217. BitsToDouble(0x4330000080000000ULL) :
  2218. BitsToDouble(0x4330000000000000ULL),
  2219. dl, MVT::f64);
  2220. // subtract the bias
  2221. SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
  2222. // final result
  2223. SDValue Result;
  2224. // handle final rounding
  2225. if (DestVT == MVT::f64) {
  2226. // do nothing
  2227. Result = Sub;
  2228. } else if (DestVT.bitsLT(MVT::f64)) {
  2229. Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
  2230. DAG.getIntPtrConstant(0, dl));
  2231. } else if (DestVT.bitsGT(MVT::f64)) {
  2232. Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
  2233. }
  2234. return Result;
  2235. }
  2236. assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
  2237. // Code below here assumes !isSigned without checking again.
  2238. // Implementation of unsigned i64 to f64 following the algorithm in
  2239. // __floatundidf in compiler_rt. This implementation has the advantage
  2240. // of performing rounding correctly, both in the default rounding mode
  2241. // and in all alternate rounding modes.
  2242. // TODO: Generalize this for use with other types.
  2243. if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
  2244. SDValue TwoP52 =
  2245. DAG.getConstant(UINT64_C(0x4330000000000000), dl, MVT::i64);
  2246. SDValue TwoP84PlusTwoP52 =
  2247. DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), dl,
  2248. MVT::f64);
  2249. SDValue TwoP84 =
  2250. DAG.getConstant(UINT64_C(0x4530000000000000), dl, MVT::i64);
  2251. SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
  2252. SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
  2253. DAG.getConstant(32, dl, MVT::i64));
  2254. SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
  2255. SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
  2256. SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
  2257. SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
  2258. SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
  2259. TwoP84PlusTwoP52);
  2260. return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
  2261. }
  2262. // Implementation of unsigned i64 to f32.
  2263. // TODO: Generalize this for use with other types.
  2264. if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
  2265. // For unsigned conversions, convert them to signed conversions using the
  2266. // algorithm from the x86_64 __floatundidf in compiler_rt.
  2267. if (!isSigned) {
  2268. SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
  2269. SDValue ShiftConst = DAG.getConstant(
  2270. 1, dl, TLI.getShiftAmountTy(Op0.getValueType(), DAG.getDataLayout()));
  2271. SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
  2272. SDValue AndConst = DAG.getConstant(1, dl, MVT::i64);
  2273. SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
  2274. SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
  2275. SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
  2276. SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
  2277. // TODO: This really should be implemented using a branch rather than a
  2278. // select. We happen to get lucky and machinesink does the right
  2279. // thing most of the time. This would be a good candidate for a
  2280. //pseudo-op, or, even better, for whole-function isel.
  2281. SDValue SignBitTest = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
  2282. Op0, DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
  2283. return DAG.getSelect(dl, MVT::f32, SignBitTest, Slow, Fast);
  2284. }
  2285. // Otherwise, implement the fully general conversion.
  2286. SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
  2287. DAG.getConstant(UINT64_C(0xfffffffffffff800), dl, MVT::i64));
  2288. SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
  2289. DAG.getConstant(UINT64_C(0x800), dl, MVT::i64));
  2290. SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
  2291. DAG.getConstant(UINT64_C(0x7ff), dl, MVT::i64));
  2292. SDValue Ne = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), And2,
  2293. DAG.getConstant(UINT64_C(0), dl, MVT::i64),
  2294. ISD::SETNE);
  2295. SDValue Sel = DAG.getSelect(dl, MVT::i64, Ne, Or, Op0);
  2296. SDValue Ge = DAG.getSetCC(dl, getSetCCResultType(MVT::i64), Op0,
  2297. DAG.getConstant(UINT64_C(0x0020000000000000), dl,
  2298. MVT::i64),
  2299. ISD::SETUGE);
  2300. SDValue Sel2 = DAG.getSelect(dl, MVT::i64, Ge, Sel, Op0);
  2301. EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType(), DAG.getDataLayout());
  2302. SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
  2303. DAG.getConstant(32, dl, SHVT));
  2304. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
  2305. SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
  2306. SDValue TwoP32 =
  2307. DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), dl,
  2308. MVT::f64);
  2309. SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
  2310. SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
  2311. SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
  2312. SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
  2313. return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
  2314. DAG.getIntPtrConstant(0, dl));
  2315. }
  2316. SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
  2317. SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(Op0.getValueType()),
  2318. Op0,
  2319. DAG.getConstant(0, dl, Op0.getValueType()),
  2320. ISD::SETLT);
  2321. SDValue Zero = DAG.getIntPtrConstant(0, dl),
  2322. Four = DAG.getIntPtrConstant(4, dl);
  2323. SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
  2324. SignSet, Four, Zero);
  2325. // If the sign bit of the integer is set, the large number will be treated
  2326. // as a negative number. To counteract this, the dynamic code adds an
  2327. // offset depending on the data type.
  2328. uint64_t FF;
  2329. switch (Op0.getSimpleValueType().SimpleTy) {
  2330. default: llvm_unreachable("Unsupported integer type!");
  2331. case MVT::i8 : FF = 0x43800000ULL; break; // 2^8 (as a float)
  2332. case MVT::i16: FF = 0x47800000ULL; break; // 2^16 (as a float)
  2333. case MVT::i32: FF = 0x4F800000ULL; break; // 2^32 (as a float)
  2334. case MVT::i64: FF = 0x5F800000ULL; break; // 2^64 (as a float)
  2335. }
  2336. if (DAG.getDataLayout().isLittleEndian())
  2337. FF <<= 32;
  2338. Constant *FudgeFactor = ConstantInt::get(
  2339. Type::getInt64Ty(*DAG.getContext()), FF);
  2340. SDValue CPIdx =
  2341. DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
  2342. unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
  2343. CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
  2344. Alignment = std::min(Alignment, 4u);
  2345. SDValue FudgeInReg;
  2346. if (DestVT == MVT::f32)
  2347. FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
  2348. MachinePointerInfo::getConstantPool(),
  2349. false, false, false, Alignment);
  2350. else {
  2351. SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
  2352. DAG.getEntryNode(), CPIdx,
  2353. MachinePointerInfo::getConstantPool(),
  2354. MVT::f32, false, false, false, Alignment);
  2355. HandleSDNode Handle(Load);
  2356. LegalizeOp(Load.getNode());
  2357. FudgeInReg = Handle.getValue();
  2358. }
  2359. return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
  2360. }
  2361. /// This function is responsible for legalizing a
  2362. /// *INT_TO_FP operation of the specified operand when the target requests that
  2363. /// we promote it. At this point, we know that the result and operand types are
  2364. /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
  2365. /// operation that takes a larger input.
  2366. SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
  2367. EVT DestVT,
  2368. bool isSigned,
  2369. SDLoc dl) {
  2370. // First step, figure out the appropriate *INT_TO_FP operation to use.
  2371. EVT NewInTy = LegalOp.getValueType();
  2372. unsigned OpToUse = 0;
  2373. // Scan for the appropriate larger type to use.
  2374. while (1) {
  2375. NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
  2376. assert(NewInTy.isInteger() && "Ran out of possibilities!");
  2377. // If the target supports SINT_TO_FP of this type, use it.
  2378. if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
  2379. OpToUse = ISD::SINT_TO_FP;
  2380. break;
  2381. }
  2382. if (isSigned) continue;
  2383. // If the target supports UINT_TO_FP of this type, use it.
  2384. if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
  2385. OpToUse = ISD::UINT_TO_FP;
  2386. break;
  2387. }
  2388. // Otherwise, try a larger type.
  2389. }
  2390. // Okay, we found the operation and type to use. Zero extend our input to the
  2391. // desired type then run the operation on it.
  2392. return DAG.getNode(OpToUse, dl, DestVT,
  2393. DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
  2394. dl, NewInTy, LegalOp));
  2395. }
  2396. /// This function is responsible for legalizing a
  2397. /// FP_TO_*INT operation of the specified operand when the target requests that
  2398. /// we promote it. At this point, we know that the result and operand types are
  2399. /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
  2400. /// operation that returns a larger result.
  2401. SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
  2402. EVT DestVT,
  2403. bool isSigned,
  2404. SDLoc dl) {
  2405. // First step, figure out the appropriate FP_TO*INT operation to use.
  2406. EVT NewOutTy = DestVT;
  2407. unsigned OpToUse = 0;
  2408. // Scan for the appropriate larger type to use.
  2409. while (1) {
  2410. NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
  2411. assert(NewOutTy.isInteger() && "Ran out of possibilities!");
  2412. // A larger signed type can hold all unsigned values of the requested type,
  2413. // so using FP_TO_SINT is valid
  2414. if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
  2415. OpToUse = ISD::FP_TO_SINT;
  2416. break;
  2417. }
  2418. // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
  2419. if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
  2420. OpToUse = ISD::FP_TO_UINT;
  2421. break;
  2422. }
  2423. // Otherwise, try a larger type.
  2424. }
  2425. // Okay, we found the operation and type to use.
  2426. SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
  2427. // Truncate the result of the extended FP_TO_*INT operation to the desired
  2428. // size.
  2429. return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
  2430. }
  2431. /// Open code the operations for BSWAP of the specified operation.
  2432. SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, SDLoc dl) {
  2433. EVT VT = Op.getValueType();
  2434. EVT SHVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
  2435. SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
  2436. switch (VT.getSimpleVT().SimpleTy) {
  2437. default: llvm_unreachable("Unhandled Expand type in BSWAP!");
  2438. case MVT::i16:
  2439. Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
  2440. Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
  2441. return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
  2442. case MVT::i32:
  2443. Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
  2444. Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
  2445. Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
  2446. Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
  2447. Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
  2448. DAG.getConstant(0xFF0000, dl, VT));
  2449. Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
  2450. Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
  2451. Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
  2452. return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
  2453. case MVT::i64:
  2454. Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
  2455. Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
  2456. Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
  2457. Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
  2458. Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
  2459. Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
  2460. Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
  2461. Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
  2462. Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
  2463. DAG.getConstant(255ULL<<48, dl, VT));
  2464. Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
  2465. DAG.getConstant(255ULL<<40, dl, VT));
  2466. Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
  2467. DAG.getConstant(255ULL<<32, dl, VT));
  2468. Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
  2469. DAG.getConstant(255ULL<<24, dl, VT));
  2470. Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
  2471. DAG.getConstant(255ULL<<16, dl, VT));
  2472. Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
  2473. DAG.getConstant(255ULL<<8 , dl, VT));
  2474. Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
  2475. Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
  2476. Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
  2477. Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
  2478. Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
  2479. Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
  2480. return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
  2481. }
  2482. }
  2483. /// Expand the specified bitcount instruction into operations.
  2484. SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
  2485. SDLoc dl) {
  2486. switch (Opc) {
  2487. default: llvm_unreachable("Cannot expand this yet!");
  2488. case ISD::CTPOP: {
  2489. EVT VT = Op.getValueType();
  2490. EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
  2491. unsigned Len = VT.getSizeInBits();
  2492. assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
  2493. "CTPOP not implemented for this type.");
  2494. // This is the "best" algorithm from
  2495. // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
  2496. SDValue Mask55 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)),
  2497. dl, VT);
  2498. SDValue Mask33 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)),
  2499. dl, VT);
  2500. SDValue Mask0F = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)),
  2501. dl, VT);
  2502. SDValue Mask01 = DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)),
  2503. dl, VT);
  2504. // v = v - ((v >> 1) & 0x55555555...)
  2505. Op = DAG.getNode(ISD::SUB, dl, VT, Op,
  2506. DAG.getNode(ISD::AND, dl, VT,
  2507. DAG.getNode(ISD::SRL, dl, VT, Op,
  2508. DAG.getConstant(1, dl, ShVT)),
  2509. Mask55));
  2510. // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
  2511. Op = DAG.getNode(ISD::ADD, dl, VT,
  2512. DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
  2513. DAG.getNode(ISD::AND, dl, VT,
  2514. DAG.getNode(ISD::SRL, dl, VT, Op,
  2515. DAG.getConstant(2, dl, ShVT)),
  2516. Mask33));
  2517. // v = (v + (v >> 4)) & 0x0F0F0F0F...
  2518. Op = DAG.getNode(ISD::AND, dl, VT,
  2519. DAG.getNode(ISD::ADD, dl, VT, Op,
  2520. DAG.getNode(ISD::SRL, dl, VT, Op,
  2521. DAG.getConstant(4, dl, ShVT))),
  2522. Mask0F);
  2523. // v = (v * 0x01010101...) >> (Len - 8)
  2524. Op = DAG.getNode(ISD::SRL, dl, VT,
  2525. DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
  2526. DAG.getConstant(Len - 8, dl, ShVT));
  2527. return Op;
  2528. }
  2529. case ISD::CTLZ_ZERO_UNDEF:
  2530. // This trivially expands to CTLZ.
  2531. return DAG.getNode(ISD::CTLZ, dl, Op.getValueType(), Op);
  2532. case ISD::CTLZ: {
  2533. // for now, we do this:
  2534. // x = x | (x >> 1);
  2535. // x = x | (x >> 2);
  2536. // ...
  2537. // x = x | (x >>16);
  2538. // x = x | (x >>32); // for 64-bit input
  2539. // return popcount(~x);
  2540. //
  2541. // Ref: "Hacker's Delight" by Henry Warren
  2542. EVT VT = Op.getValueType();
  2543. EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
  2544. unsigned len = VT.getSizeInBits();
  2545. for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
  2546. SDValue Tmp3 = DAG.getConstant(1ULL << i, dl, ShVT);
  2547. Op = DAG.getNode(ISD::OR, dl, VT, Op,
  2548. DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
  2549. }
  2550. Op = DAG.getNOT(dl, Op, VT);
  2551. return DAG.getNode(ISD::CTPOP, dl, VT, Op);
  2552. }
  2553. case ISD::CTTZ_ZERO_UNDEF:
  2554. // This trivially expands to CTTZ.
  2555. return DAG.getNode(ISD::CTTZ, dl, Op.getValueType(), Op);
  2556. case ISD::CTTZ: {
  2557. // for now, we use: { return popcount(~x & (x - 1)); }
  2558. // unless the target has ctlz but not ctpop, in which case we use:
  2559. // { return 32 - nlz(~x & (x-1)); }
  2560. // Ref: "Hacker's Delight" by Henry Warren
  2561. EVT VT = Op.getValueType();
  2562. SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
  2563. DAG.getNOT(dl, Op, VT),
  2564. DAG.getNode(ISD::SUB, dl, VT, Op,
  2565. DAG.getConstant(1, dl, VT)));
  2566. // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
  2567. if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
  2568. TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
  2569. return DAG.getNode(ISD::SUB, dl, VT,
  2570. DAG.getConstant(VT.getSizeInBits(), dl, VT),
  2571. DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
  2572. return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
  2573. }
  2574. }
  2575. }
  2576. std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
  2577. unsigned Opc = Node->getOpcode();
  2578. MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
  2579. RTLIB::Libcall LC = RTLIB::getATOMIC(Opc, VT);
  2580. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
  2581. return ExpandChainLibCall(LC, Node, false);
  2582. }
  2583. void SelectionDAGLegalize::ExpandNode(SDNode *Node) {
  2584. SmallVector<SDValue, 8> Results;
  2585. SDLoc dl(Node);
  2586. SDValue Tmp1, Tmp2, Tmp3, Tmp4;
  2587. bool NeedInvert;
  2588. switch (Node->getOpcode()) {
  2589. case ISD::CTPOP:
  2590. case ISD::CTLZ:
  2591. case ISD::CTLZ_ZERO_UNDEF:
  2592. case ISD::CTTZ:
  2593. case ISD::CTTZ_ZERO_UNDEF:
  2594. Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
  2595. Results.push_back(Tmp1);
  2596. break;
  2597. case ISD::BSWAP:
  2598. Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
  2599. break;
  2600. case ISD::FRAMEADDR:
  2601. case ISD::RETURNADDR:
  2602. case ISD::FRAME_TO_ARGS_OFFSET:
  2603. Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
  2604. break;
  2605. case ISD::FLT_ROUNDS_:
  2606. Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
  2607. break;
  2608. case ISD::EH_RETURN:
  2609. case ISD::EH_LABEL:
  2610. case ISD::PREFETCH:
  2611. case ISD::VAEND:
  2612. case ISD::EH_SJLJ_LONGJMP:
  2613. // If the target didn't expand these, there's nothing to do, so just
  2614. // preserve the chain and be done.
  2615. Results.push_back(Node->getOperand(0));
  2616. break;
  2617. case ISD::EH_SJLJ_SETJMP:
  2618. // If the target didn't expand this, just return 'zero' and preserve the
  2619. // chain.
  2620. Results.push_back(DAG.getConstant(0, dl, MVT::i32));
  2621. Results.push_back(Node->getOperand(0));
  2622. break;
  2623. case ISD::ATOMIC_FENCE: {
  2624. // If the target didn't lower this, lower it to '__sync_synchronize()' call
  2625. // FIXME: handle "fence singlethread" more efficiently.
  2626. TargetLowering::ArgListTy Args;
  2627. TargetLowering::CallLoweringInfo CLI(DAG);
  2628. CLI.setDebugLoc(dl)
  2629. .setChain(Node->getOperand(0))
  2630. .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
  2631. DAG.getExternalSymbol("__sync_synchronize",
  2632. TLI.getPointerTy(DAG.getDataLayout())),
  2633. std::move(Args), 0);
  2634. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  2635. Results.push_back(CallResult.second);
  2636. break;
  2637. }
  2638. case ISD::ATOMIC_LOAD: {
  2639. // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
  2640. SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
  2641. SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
  2642. SDValue Swap = DAG.getAtomicCmpSwap(
  2643. ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
  2644. Node->getOperand(0), Node->getOperand(1), Zero, Zero,
  2645. cast<AtomicSDNode>(Node)->getMemOperand(),
  2646. cast<AtomicSDNode>(Node)->getOrdering(),
  2647. cast<AtomicSDNode>(Node)->getOrdering(),
  2648. cast<AtomicSDNode>(Node)->getSynchScope());
  2649. Results.push_back(Swap.getValue(0));
  2650. Results.push_back(Swap.getValue(1));
  2651. break;
  2652. }
  2653. case ISD::ATOMIC_STORE: {
  2654. // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
  2655. SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
  2656. cast<AtomicSDNode>(Node)->getMemoryVT(),
  2657. Node->getOperand(0),
  2658. Node->getOperand(1), Node->getOperand(2),
  2659. cast<AtomicSDNode>(Node)->getMemOperand(),
  2660. cast<AtomicSDNode>(Node)->getOrdering(),
  2661. cast<AtomicSDNode>(Node)->getSynchScope());
  2662. Results.push_back(Swap.getValue(1));
  2663. break;
  2664. }
  2665. // By default, atomic intrinsics are marked Legal and lowered. Targets
  2666. // which don't support them directly, however, may want libcalls, in which
  2667. // case they mark them Expand, and we get here.
  2668. case ISD::ATOMIC_SWAP:
  2669. case ISD::ATOMIC_LOAD_ADD:
  2670. case ISD::ATOMIC_LOAD_SUB:
  2671. case ISD::ATOMIC_LOAD_AND:
  2672. case ISD::ATOMIC_LOAD_OR:
  2673. case ISD::ATOMIC_LOAD_XOR:
  2674. case ISD::ATOMIC_LOAD_NAND:
  2675. case ISD::ATOMIC_LOAD_MIN:
  2676. case ISD::ATOMIC_LOAD_MAX:
  2677. case ISD::ATOMIC_LOAD_UMIN:
  2678. case ISD::ATOMIC_LOAD_UMAX:
  2679. case ISD::ATOMIC_CMP_SWAP: {
  2680. std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
  2681. Results.push_back(Tmp.first);
  2682. Results.push_back(Tmp.second);
  2683. break;
  2684. }
  2685. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
  2686. // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
  2687. // splits out the success value as a comparison. Expanding the resulting
  2688. // ATOMIC_CMP_SWAP will produce a libcall.
  2689. SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
  2690. SDValue Res = DAG.getAtomicCmpSwap(
  2691. ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
  2692. Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
  2693. Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand(),
  2694. cast<AtomicSDNode>(Node)->getSuccessOrdering(),
  2695. cast<AtomicSDNode>(Node)->getFailureOrdering(),
  2696. cast<AtomicSDNode>(Node)->getSynchScope());
  2697. SDValue Success = DAG.getSetCC(SDLoc(Node), Node->getValueType(1),
  2698. Res, Node->getOperand(2), ISD::SETEQ);
  2699. Results.push_back(Res.getValue(0));
  2700. Results.push_back(Success);
  2701. Results.push_back(Res.getValue(1));
  2702. break;
  2703. }
  2704. case ISD::DYNAMIC_STACKALLOC:
  2705. ExpandDYNAMIC_STACKALLOC(Node, Results);
  2706. break;
  2707. case ISD::MERGE_VALUES:
  2708. for (unsigned i = 0; i < Node->getNumValues(); i++)
  2709. Results.push_back(Node->getOperand(i));
  2710. break;
  2711. case ISD::UNDEF: {
  2712. EVT VT = Node->getValueType(0);
  2713. if (VT.isInteger())
  2714. Results.push_back(DAG.getConstant(0, dl, VT));
  2715. else {
  2716. assert(VT.isFloatingPoint() && "Unknown value type!");
  2717. Results.push_back(DAG.getConstantFP(0, dl, VT));
  2718. }
  2719. break;
  2720. }
  2721. case ISD::TRAP: {
  2722. // If this operation is not supported, lower it to 'abort()' call
  2723. TargetLowering::ArgListTy Args;
  2724. TargetLowering::CallLoweringInfo CLI(DAG);
  2725. CLI.setDebugLoc(dl)
  2726. .setChain(Node->getOperand(0))
  2727. .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
  2728. DAG.getExternalSymbol("abort",
  2729. TLI.getPointerTy(DAG.getDataLayout())),
  2730. std::move(Args), 0);
  2731. std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
  2732. Results.push_back(CallResult.second);
  2733. break;
  2734. }
  2735. case ISD::FP_ROUND:
  2736. case ISD::BITCAST:
  2737. Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
  2738. Node->getValueType(0), dl);
  2739. Results.push_back(Tmp1);
  2740. break;
  2741. case ISD::FP_EXTEND:
  2742. Tmp1 = EmitStackConvert(Node->getOperand(0),
  2743. Node->getOperand(0).getValueType(),
  2744. Node->getValueType(0), dl);
  2745. Results.push_back(Tmp1);
  2746. break;
  2747. case ISD::SIGN_EXTEND_INREG: {
  2748. // NOTE: we could fall back on load/store here too for targets without
  2749. // SAR. However, it is doubtful that any exist.
  2750. EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
  2751. EVT VT = Node->getValueType(0);
  2752. EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
  2753. if (VT.isVector())
  2754. ShiftAmountTy = VT;
  2755. unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
  2756. ExtraVT.getScalarType().getSizeInBits();
  2757. SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
  2758. Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
  2759. Node->getOperand(0), ShiftCst);
  2760. Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
  2761. Results.push_back(Tmp1);
  2762. break;
  2763. }
  2764. case ISD::FP_ROUND_INREG: {
  2765. // The only way we can lower this is to turn it into a TRUNCSTORE,
  2766. // EXTLOAD pair, targeting a temporary location (a stack slot).
  2767. // NOTE: there is a choice here between constantly creating new stack
  2768. // slots and always reusing the same one. We currently always create
  2769. // new ones, as reuse may inhibit scheduling.
  2770. EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
  2771. Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
  2772. Node->getValueType(0), dl);
  2773. Results.push_back(Tmp1);
  2774. break;
  2775. }
  2776. case ISD::SINT_TO_FP:
  2777. case ISD::UINT_TO_FP:
  2778. Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
  2779. Node->getOperand(0), Node->getValueType(0), dl);
  2780. Results.push_back(Tmp1);
  2781. break;
  2782. case ISD::FP_TO_SINT:
  2783. if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
  2784. Results.push_back(Tmp1);
  2785. break;
  2786. case ISD::FP_TO_UINT: {
  2787. SDValue True, False;
  2788. EVT VT = Node->getOperand(0).getValueType();
  2789. EVT NVT = Node->getValueType(0);
  2790. APFloat apf(DAG.EVTToAPFloatSemantics(VT),
  2791. APInt::getNullValue(VT.getSizeInBits()));
  2792. APInt x = APInt::getSignBit(NVT.getSizeInBits());
  2793. (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
  2794. Tmp1 = DAG.getConstantFP(apf, dl, VT);
  2795. Tmp2 = DAG.getSetCC(dl, getSetCCResultType(VT),
  2796. Node->getOperand(0),
  2797. Tmp1, ISD::SETLT);
  2798. True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
  2799. False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
  2800. DAG.getNode(ISD::FSUB, dl, VT,
  2801. Node->getOperand(0), Tmp1));
  2802. False = DAG.getNode(ISD::XOR, dl, NVT, False,
  2803. DAG.getConstant(x, dl, NVT));
  2804. Tmp1 = DAG.getSelect(dl, NVT, Tmp2, True, False);
  2805. Results.push_back(Tmp1);
  2806. break;
  2807. }
  2808. case ISD::VAARG: {
  2809. const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
  2810. EVT VT = Node->getValueType(0);
  2811. Tmp1 = Node->getOperand(0);
  2812. Tmp2 = Node->getOperand(1);
  2813. unsigned Align = Node->getConstantOperandVal(3);
  2814. SDValue VAListLoad =
  2815. DAG.getLoad(TLI.getPointerTy(DAG.getDataLayout()), dl, Tmp1, Tmp2,
  2816. MachinePointerInfo(V), false, false, false, 0);
  2817. SDValue VAList = VAListLoad;
  2818. if (Align > TLI.getMinStackArgumentAlignment()) {
  2819. assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
  2820. VAList = DAG.getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  2821. DAG.getConstant(Align - 1, dl,
  2822. VAList.getValueType()));
  2823. VAList = DAG.getNode(ISD::AND, dl, VAList.getValueType(), VAList,
  2824. DAG.getConstant(-(int64_t)Align, dl,
  2825. VAList.getValueType()));
  2826. }
  2827. // Increment the pointer, VAList, to the next vaarg
  2828. Tmp3 = DAG.getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  2829. DAG.getConstant(DAG.getDataLayout().getTypeAllocSize(
  2830. VT.getTypeForEVT(*DAG.getContext())),
  2831. dl, VAList.getValueType()));
  2832. // Store the incremented VAList to the legalized pointer
  2833. Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
  2834. MachinePointerInfo(V), false, false, 0);
  2835. // Load the actual argument out of the pointer VAList
  2836. Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
  2837. false, false, false, 0));
  2838. Results.push_back(Results[0].getValue(1));
  2839. break;
  2840. }
  2841. case ISD::VACOPY: {
  2842. // This defaults to loading a pointer from the input and storing it to the
  2843. // output, returning the chain.
  2844. const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
  2845. const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
  2846. Tmp1 = DAG.getLoad(TLI.getPointerTy(DAG.getDataLayout()), dl,
  2847. Node->getOperand(0), Node->getOperand(2),
  2848. MachinePointerInfo(VS), false, false, false, 0);
  2849. Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
  2850. MachinePointerInfo(VD), false, false, 0);
  2851. Results.push_back(Tmp1);
  2852. break;
  2853. }
  2854. case ISD::EXTRACT_VECTOR_ELT:
  2855. if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
  2856. // This must be an access of the only element. Return it.
  2857. Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
  2858. Node->getOperand(0));
  2859. else
  2860. Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
  2861. Results.push_back(Tmp1);
  2862. break;
  2863. case ISD::EXTRACT_SUBVECTOR:
  2864. Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
  2865. break;
  2866. case ISD::INSERT_SUBVECTOR:
  2867. Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
  2868. break;
  2869. case ISD::CONCAT_VECTORS: {
  2870. Results.push_back(ExpandVectorBuildThroughStack(Node));
  2871. break;
  2872. }
  2873. case ISD::SCALAR_TO_VECTOR:
  2874. Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
  2875. break;
  2876. case ISD::INSERT_VECTOR_ELT:
  2877. Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
  2878. Node->getOperand(1),
  2879. Node->getOperand(2), dl));
  2880. break;
  2881. case ISD::VECTOR_SHUFFLE: {
  2882. SmallVector<int, 32> NewMask;
  2883. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
  2884. EVT VT = Node->getValueType(0);
  2885. EVT EltVT = VT.getVectorElementType();
  2886. SDValue Op0 = Node->getOperand(0);
  2887. SDValue Op1 = Node->getOperand(1);
  2888. if (!TLI.isTypeLegal(EltVT)) {
  2889. EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
  2890. // BUILD_VECTOR operands are allowed to be wider than the element type.
  2891. // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
  2892. // it.
  2893. if (NewEltVT.bitsLT(EltVT)) {
  2894. // Convert shuffle node.
  2895. // If original node was v4i64 and the new EltVT is i32,
  2896. // cast operands to v8i32 and re-build the mask.
  2897. // Calculate new VT, the size of the new VT should be equal to original.
  2898. EVT NewVT =
  2899. EVT::getVectorVT(*DAG.getContext(), NewEltVT,
  2900. VT.getSizeInBits() / NewEltVT.getSizeInBits());
  2901. assert(NewVT.bitsEq(VT));
  2902. // cast operands to new VT
  2903. Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
  2904. Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
  2905. // Convert the shuffle mask
  2906. unsigned int factor =
  2907. NewVT.getVectorNumElements()/VT.getVectorNumElements();
  2908. // EltVT gets smaller
  2909. assert(factor > 0);
  2910. for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
  2911. if (Mask[i] < 0) {
  2912. for (unsigned fi = 0; fi < factor; ++fi)
  2913. NewMask.push_back(Mask[i]);
  2914. }
  2915. else {
  2916. for (unsigned fi = 0; fi < factor; ++fi)
  2917. NewMask.push_back(Mask[i]*factor+fi);
  2918. }
  2919. }
  2920. Mask = NewMask;
  2921. VT = NewVT;
  2922. }
  2923. EltVT = NewEltVT;
  2924. }
  2925. unsigned NumElems = VT.getVectorNumElements();
  2926. SmallVector<SDValue, 16> Ops;
  2927. for (unsigned i = 0; i != NumElems; ++i) {
  2928. if (Mask[i] < 0) {
  2929. Ops.push_back(DAG.getUNDEF(EltVT));
  2930. continue;
  2931. }
  2932. unsigned Idx = Mask[i];
  2933. if (Idx < NumElems)
  2934. Ops.push_back(DAG.getNode(
  2935. ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
  2936. DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))));
  2937. else
  2938. Ops.push_back(DAG.getNode(
  2939. ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
  2940. DAG.getConstant(Idx - NumElems, dl,
  2941. TLI.getVectorIdxTy(DAG.getDataLayout()))));
  2942. }
  2943. Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
  2944. // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
  2945. Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
  2946. Results.push_back(Tmp1);
  2947. break;
  2948. }
  2949. case ISD::EXTRACT_ELEMENT: {
  2950. EVT OpTy = Node->getOperand(0).getValueType();
  2951. if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
  2952. // 1 -> Hi
  2953. Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
  2954. DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
  2955. TLI.getShiftAmountTy(
  2956. Node->getOperand(0).getValueType(),
  2957. DAG.getDataLayout())));
  2958. Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
  2959. } else {
  2960. // 0 -> Lo
  2961. Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
  2962. Node->getOperand(0));
  2963. }
  2964. Results.push_back(Tmp1);
  2965. break;
  2966. }
  2967. case ISD::STACKSAVE:
  2968. // Expand to CopyFromReg if the target set
  2969. // StackPointerRegisterToSaveRestore.
  2970. if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
  2971. Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
  2972. Node->getValueType(0)));
  2973. Results.push_back(Results[0].getValue(1));
  2974. } else {
  2975. Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
  2976. Results.push_back(Node->getOperand(0));
  2977. }
  2978. break;
  2979. case ISD::STACKRESTORE:
  2980. // Expand to CopyToReg if the target set
  2981. // StackPointerRegisterToSaveRestore.
  2982. if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
  2983. Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
  2984. Node->getOperand(1)));
  2985. } else {
  2986. Results.push_back(Node->getOperand(0));
  2987. }
  2988. break;
  2989. case ISD::FCOPYSIGN:
  2990. Results.push_back(ExpandFCOPYSIGN(Node));
  2991. break;
  2992. case ISD::FNEG:
  2993. // Expand Y = FNEG(X) -> Y = SUB -0.0, X
  2994. Tmp1 = DAG.getConstantFP(-0.0, dl, Node->getValueType(0));
  2995. Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
  2996. Node->getOperand(0));
  2997. Results.push_back(Tmp1);
  2998. break;
  2999. case ISD::FABS: {
  3000. // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
  3001. EVT VT = Node->getValueType(0);
  3002. Tmp1 = Node->getOperand(0);
  3003. Tmp2 = DAG.getConstantFP(0.0, dl, VT);
  3004. Tmp2 = DAG.getSetCC(dl, getSetCCResultType(Tmp1.getValueType()),
  3005. Tmp1, Tmp2, ISD::SETUGT);
  3006. Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
  3007. Tmp1 = DAG.getSelect(dl, VT, Tmp2, Tmp1, Tmp3);
  3008. Results.push_back(Tmp1);
  3009. break;
  3010. }
  3011. case ISD::SMIN:
  3012. case ISD::SMAX:
  3013. case ISD::UMIN:
  3014. case ISD::UMAX: {
  3015. // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
  3016. ISD::CondCode Pred;
  3017. switch (Node->getOpcode()) {
  3018. default: llvm_unreachable("How did we get here?");
  3019. case ISD::SMAX: Pred = ISD::SETGT; break;
  3020. case ISD::SMIN: Pred = ISD::SETLT; break;
  3021. case ISD::UMAX: Pred = ISD::SETUGT; break;
  3022. case ISD::UMIN: Pred = ISD::SETULT; break;
  3023. }
  3024. Tmp1 = Node->getOperand(0);
  3025. Tmp2 = Node->getOperand(1);
  3026. Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
  3027. Results.push_back(Tmp1);
  3028. break;
  3029. }
  3030. case ISD::FMINNUM:
  3031. Results.push_back(ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
  3032. RTLIB::FMIN_F80, RTLIB::FMIN_F128,
  3033. RTLIB::FMIN_PPCF128));
  3034. break;
  3035. case ISD::FMAXNUM:
  3036. Results.push_back(ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
  3037. RTLIB::FMAX_F80, RTLIB::FMAX_F128,
  3038. RTLIB::FMAX_PPCF128));
  3039. break;
  3040. case ISD::FSQRT:
  3041. Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
  3042. RTLIB::SQRT_F80, RTLIB::SQRT_F128,
  3043. RTLIB::SQRT_PPCF128));
  3044. break;
  3045. case ISD::FSIN:
  3046. case ISD::FCOS: {
  3047. EVT VT = Node->getValueType(0);
  3048. bool isSIN = Node->getOpcode() == ISD::FSIN;
  3049. // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
  3050. // fcos which share the same operand and both are used.
  3051. if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
  3052. canCombineSinCosLibcall(Node, TLI, TM))
  3053. && useSinCos(Node)) {
  3054. SDVTList VTs = DAG.getVTList(VT, VT);
  3055. Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
  3056. if (!isSIN)
  3057. Tmp1 = Tmp1.getValue(1);
  3058. Results.push_back(Tmp1);
  3059. } else if (isSIN) {
  3060. Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
  3061. RTLIB::SIN_F80, RTLIB::SIN_F128,
  3062. RTLIB::SIN_PPCF128));
  3063. } else {
  3064. Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
  3065. RTLIB::COS_F80, RTLIB::COS_F128,
  3066. RTLIB::COS_PPCF128));
  3067. }
  3068. break;
  3069. }
  3070. case ISD::FSINCOS:
  3071. // Expand into sincos libcall.
  3072. ExpandSinCosLibCall(Node, Results);
  3073. break;
  3074. case ISD::FLOG:
  3075. Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
  3076. RTLIB::LOG_F80, RTLIB::LOG_F128,
  3077. RTLIB::LOG_PPCF128));
  3078. break;
  3079. case ISD::FLOG2:
  3080. Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
  3081. RTLIB::LOG2_F80, RTLIB::LOG2_F128,
  3082. RTLIB::LOG2_PPCF128));
  3083. break;
  3084. case ISD::FLOG10:
  3085. Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
  3086. RTLIB::LOG10_F80, RTLIB::LOG10_F128,
  3087. RTLIB::LOG10_PPCF128));
  3088. break;
  3089. case ISD::FEXP:
  3090. Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
  3091. RTLIB::EXP_F80, RTLIB::EXP_F128,
  3092. RTLIB::EXP_PPCF128));
  3093. break;
  3094. case ISD::FEXP2:
  3095. Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
  3096. RTLIB::EXP2_F80, RTLIB::EXP2_F128,
  3097. RTLIB::EXP2_PPCF128));
  3098. break;
  3099. case ISD::FTRUNC:
  3100. Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
  3101. RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
  3102. RTLIB::TRUNC_PPCF128));
  3103. break;
  3104. case ISD::FFLOOR:
  3105. Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
  3106. RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
  3107. RTLIB::FLOOR_PPCF128));
  3108. break;
  3109. case ISD::FCEIL:
  3110. Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
  3111. RTLIB::CEIL_F80, RTLIB::CEIL_F128,
  3112. RTLIB::CEIL_PPCF128));
  3113. break;
  3114. case ISD::FRINT:
  3115. Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
  3116. RTLIB::RINT_F80, RTLIB::RINT_F128,
  3117. RTLIB::RINT_PPCF128));
  3118. break;
  3119. case ISD::FNEARBYINT:
  3120. Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
  3121. RTLIB::NEARBYINT_F64,
  3122. RTLIB::NEARBYINT_F80,
  3123. RTLIB::NEARBYINT_F128,
  3124. RTLIB::NEARBYINT_PPCF128));
  3125. break;
  3126. case ISD::FROUND:
  3127. Results.push_back(ExpandFPLibCall(Node, RTLIB::ROUND_F32,
  3128. RTLIB::ROUND_F64,
  3129. RTLIB::ROUND_F80,
  3130. RTLIB::ROUND_F128,
  3131. RTLIB::ROUND_PPCF128));
  3132. break;
  3133. case ISD::FPOWI:
  3134. Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
  3135. RTLIB::POWI_F80, RTLIB::POWI_F128,
  3136. RTLIB::POWI_PPCF128));
  3137. break;
  3138. case ISD::FPOW:
  3139. Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
  3140. RTLIB::POW_F80, RTLIB::POW_F128,
  3141. RTLIB::POW_PPCF128));
  3142. break;
  3143. case ISD::FDIV:
  3144. Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
  3145. RTLIB::DIV_F80, RTLIB::DIV_F128,
  3146. RTLIB::DIV_PPCF128));
  3147. break;
  3148. case ISD::FREM:
  3149. Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
  3150. RTLIB::REM_F80, RTLIB::REM_F128,
  3151. RTLIB::REM_PPCF128));
  3152. break;
  3153. case ISD::FMA:
  3154. Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
  3155. RTLIB::FMA_F80, RTLIB::FMA_F128,
  3156. RTLIB::FMA_PPCF128));
  3157. break;
  3158. case ISD::FMAD:
  3159. llvm_unreachable("Illegal fmad should never be formed");
  3160. case ISD::FADD:
  3161. Results.push_back(ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
  3162. RTLIB::ADD_F80, RTLIB::ADD_F128,
  3163. RTLIB::ADD_PPCF128));
  3164. break;
  3165. case ISD::FMUL:
  3166. Results.push_back(ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
  3167. RTLIB::MUL_F80, RTLIB::MUL_F128,
  3168. RTLIB::MUL_PPCF128));
  3169. break;
  3170. case ISD::FP16_TO_FP: {
  3171. if (Node->getValueType(0) == MVT::f32) {
  3172. Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
  3173. break;
  3174. }
  3175. // We can extend to types bigger than f32 in two steps without changing the
  3176. // result. Since "f16 -> f32" is much more commonly available, give CodeGen
  3177. // the option of emitting that before resorting to a libcall.
  3178. SDValue Res =
  3179. DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
  3180. Results.push_back(
  3181. DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
  3182. break;
  3183. }
  3184. case ISD::FP_TO_FP16: {
  3185. if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
  3186. SDValue Op = Node->getOperand(0);
  3187. MVT SVT = Op.getSimpleValueType();
  3188. if ((SVT == MVT::f64 || SVT == MVT::f80) &&
  3189. TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
  3190. // Under fastmath, we can expand this node into a fround followed by
  3191. // a float-half conversion.
  3192. SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
  3193. DAG.getIntPtrConstant(0, dl));
  3194. Results.push_back(
  3195. DAG.getNode(ISD::FP_TO_FP16, dl, MVT::i16, FloatVal));
  3196. break;
  3197. }
  3198. }
  3199. RTLIB::Libcall LC =
  3200. RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
  3201. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
  3202. Results.push_back(ExpandLibCall(LC, Node, false));
  3203. break;
  3204. }
  3205. case ISD::ConstantFP: {
  3206. ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
  3207. // Check to see if this FP immediate is already legal.
  3208. // If this is a legal constant, turn it into a TargetConstantFP node.
  3209. if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
  3210. Results.push_back(ExpandConstantFP(CFP, true));
  3211. break;
  3212. }
  3213. case ISD::FSUB: {
  3214. EVT VT = Node->getValueType(0);
  3215. if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
  3216. TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
  3217. Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
  3218. Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1);
  3219. Results.push_back(Tmp1);
  3220. } else {
  3221. Results.push_back(ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
  3222. RTLIB::SUB_F80, RTLIB::SUB_F128,
  3223. RTLIB::SUB_PPCF128));
  3224. }
  3225. break;
  3226. }
  3227. case ISD::SUB: {
  3228. EVT VT = Node->getValueType(0);
  3229. assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
  3230. TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
  3231. "Don't know how to expand this subtraction!");
  3232. Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
  3233. DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
  3234. VT));
  3235. Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
  3236. Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
  3237. break;
  3238. }
  3239. case ISD::UREM:
  3240. case ISD::SREM: {
  3241. EVT VT = Node->getValueType(0);
  3242. bool isSigned = Node->getOpcode() == ISD::SREM;
  3243. unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
  3244. unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
  3245. Tmp2 = Node->getOperand(0);
  3246. Tmp3 = Node->getOperand(1);
  3247. if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
  3248. (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
  3249. // If div is legal, it's better to do the normal expansion
  3250. !TLI.isOperationLegalOrCustom(DivOpc, Node->getValueType(0)) &&
  3251. useDivRem(Node, isSigned, false))) {
  3252. SDVTList VTs = DAG.getVTList(VT, VT);
  3253. Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
  3254. } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
  3255. // X % Y -> X-X/Y*Y
  3256. Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
  3257. Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
  3258. Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
  3259. } else if (isSigned)
  3260. Tmp1 = ExpandIntLibCall(Node, true,
  3261. RTLIB::SREM_I8,
  3262. RTLIB::SREM_I16, RTLIB::SREM_I32,
  3263. RTLIB::SREM_I64, RTLIB::SREM_I128);
  3264. else
  3265. Tmp1 = ExpandIntLibCall(Node, false,
  3266. RTLIB::UREM_I8,
  3267. RTLIB::UREM_I16, RTLIB::UREM_I32,
  3268. RTLIB::UREM_I64, RTLIB::UREM_I128);
  3269. Results.push_back(Tmp1);
  3270. break;
  3271. }
  3272. case ISD::UDIV:
  3273. case ISD::SDIV: {
  3274. bool isSigned = Node->getOpcode() == ISD::SDIV;
  3275. unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
  3276. EVT VT = Node->getValueType(0);
  3277. SDVTList VTs = DAG.getVTList(VT, VT);
  3278. if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
  3279. (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
  3280. useDivRem(Node, isSigned, true)))
  3281. Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
  3282. Node->getOperand(1));
  3283. else if (isSigned)
  3284. Tmp1 = ExpandIntLibCall(Node, true,
  3285. RTLIB::SDIV_I8,
  3286. RTLIB::SDIV_I16, RTLIB::SDIV_I32,
  3287. RTLIB::SDIV_I64, RTLIB::SDIV_I128);
  3288. else
  3289. Tmp1 = ExpandIntLibCall(Node, false,
  3290. RTLIB::UDIV_I8,
  3291. RTLIB::UDIV_I16, RTLIB::UDIV_I32,
  3292. RTLIB::UDIV_I64, RTLIB::UDIV_I128);
  3293. Results.push_back(Tmp1);
  3294. break;
  3295. }
  3296. case ISD::MULHU:
  3297. case ISD::MULHS: {
  3298. unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
  3299. ISD::SMUL_LOHI;
  3300. EVT VT = Node->getValueType(0);
  3301. SDVTList VTs = DAG.getVTList(VT, VT);
  3302. assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
  3303. "If this wasn't legal, it shouldn't have been created!");
  3304. Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
  3305. Node->getOperand(1));
  3306. Results.push_back(Tmp1.getValue(1));
  3307. break;
  3308. }
  3309. case ISD::SDIVREM:
  3310. case ISD::UDIVREM:
  3311. // Expand into divrem libcall
  3312. ExpandDivRemLibCall(Node, Results);
  3313. break;
  3314. case ISD::MUL: {
  3315. EVT VT = Node->getValueType(0);
  3316. SDVTList VTs = DAG.getVTList(VT, VT);
  3317. // See if multiply or divide can be lowered using two-result operations.
  3318. // We just need the low half of the multiply; try both the signed
  3319. // and unsigned forms. If the target supports both SMUL_LOHI and
  3320. // UMUL_LOHI, form a preference by checking which forms of plain
  3321. // MULH it supports.
  3322. bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
  3323. bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
  3324. bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
  3325. bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
  3326. unsigned OpToUse = 0;
  3327. if (HasSMUL_LOHI && !HasMULHS) {
  3328. OpToUse = ISD::SMUL_LOHI;
  3329. } else if (HasUMUL_LOHI && !HasMULHU) {
  3330. OpToUse = ISD::UMUL_LOHI;
  3331. } else if (HasSMUL_LOHI) {
  3332. OpToUse = ISD::SMUL_LOHI;
  3333. } else if (HasUMUL_LOHI) {
  3334. OpToUse = ISD::UMUL_LOHI;
  3335. }
  3336. if (OpToUse) {
  3337. Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
  3338. Node->getOperand(1)));
  3339. break;
  3340. }
  3341. SDValue Lo, Hi;
  3342. EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
  3343. if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
  3344. TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
  3345. TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
  3346. TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
  3347. TLI.expandMUL(Node, Lo, Hi, HalfType, DAG)) {
  3348. Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
  3349. Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
  3350. SDValue Shift =
  3351. DAG.getConstant(HalfType.getSizeInBits(), dl,
  3352. TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
  3353. Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
  3354. Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
  3355. break;
  3356. }
  3357. Tmp1 = ExpandIntLibCall(Node, false,
  3358. RTLIB::MUL_I8,
  3359. RTLIB::MUL_I16, RTLIB::MUL_I32,
  3360. RTLIB::MUL_I64, RTLIB::MUL_I128);
  3361. Results.push_back(Tmp1);
  3362. break;
  3363. }
  3364. case ISD::SADDO:
  3365. case ISD::SSUBO: {
  3366. SDValue LHS = Node->getOperand(0);
  3367. SDValue RHS = Node->getOperand(1);
  3368. SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
  3369. ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
  3370. LHS, RHS);
  3371. Results.push_back(Sum);
  3372. EVT ResultType = Node->getValueType(1);
  3373. EVT OType = getSetCCResultType(Node->getValueType(0));
  3374. SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
  3375. // LHSSign -> LHS >= 0
  3376. // RHSSign -> RHS >= 0
  3377. // SumSign -> Sum >= 0
  3378. //
  3379. // Add:
  3380. // Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
  3381. // Sub:
  3382. // Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
  3383. //
  3384. SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
  3385. SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
  3386. SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
  3387. Node->getOpcode() == ISD::SADDO ?
  3388. ISD::SETEQ : ISD::SETNE);
  3389. SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
  3390. SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
  3391. SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
  3392. Results.push_back(DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType));
  3393. break;
  3394. }
  3395. case ISD::UADDO:
  3396. case ISD::USUBO: {
  3397. SDValue LHS = Node->getOperand(0);
  3398. SDValue RHS = Node->getOperand(1);
  3399. SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
  3400. ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
  3401. LHS, RHS);
  3402. Results.push_back(Sum);
  3403. EVT ResultType = Node->getValueType(1);
  3404. EVT SetCCType = getSetCCResultType(Node->getValueType(0));
  3405. ISD::CondCode CC
  3406. = Node->getOpcode() == ISD::UADDO ? ISD::SETULT : ISD::SETUGT;
  3407. SDValue SetCC = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
  3408. Results.push_back(DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType));
  3409. break;
  3410. }
  3411. case ISD::UMULO:
  3412. case ISD::SMULO: {
  3413. EVT VT = Node->getValueType(0);
  3414. EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
  3415. SDValue LHS = Node->getOperand(0);
  3416. SDValue RHS = Node->getOperand(1);
  3417. SDValue BottomHalf;
  3418. SDValue TopHalf;
  3419. static const unsigned Ops[2][3] =
  3420. { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
  3421. { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
  3422. bool isSigned = Node->getOpcode() == ISD::SMULO;
  3423. if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
  3424. BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
  3425. TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
  3426. } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
  3427. BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
  3428. RHS);
  3429. TopHalf = BottomHalf.getValue(1);
  3430. } else if (TLI.isTypeLegal(WideVT)) {
  3431. LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
  3432. RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
  3433. Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
  3434. BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
  3435. DAG.getIntPtrConstant(0, dl));
  3436. TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
  3437. DAG.getIntPtrConstant(1, dl));
  3438. } else {
  3439. // We can fall back to a libcall with an illegal type for the MUL if we
  3440. // have a libcall big enough.
  3441. // Also, we can fall back to a division in some cases, but that's a big
  3442. // performance hit in the general case.
  3443. RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
  3444. if (WideVT == MVT::i16)
  3445. LC = RTLIB::MUL_I16;
  3446. else if (WideVT == MVT::i32)
  3447. LC = RTLIB::MUL_I32;
  3448. else if (WideVT == MVT::i64)
  3449. LC = RTLIB::MUL_I64;
  3450. else if (WideVT == MVT::i128)
  3451. LC = RTLIB::MUL_I128;
  3452. assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
  3453. // The high part is obtained by SRA'ing all but one of the bits of low
  3454. // part.
  3455. unsigned LoSize = VT.getSizeInBits();
  3456. SDValue HiLHS =
  3457. DAG.getNode(ISD::SRA, dl, VT, RHS,
  3458. DAG.getConstant(LoSize - 1, dl,
  3459. TLI.getPointerTy(DAG.getDataLayout())));
  3460. SDValue HiRHS =
  3461. DAG.getNode(ISD::SRA, dl, VT, LHS,
  3462. DAG.getConstant(LoSize - 1, dl,
  3463. TLI.getPointerTy(DAG.getDataLayout())));
  3464. // Here we're passing the 2 arguments explicitly as 4 arguments that are
  3465. // pre-lowered to the correct types. This all depends upon WideVT not
  3466. // being a legal type for the architecture and thus has to be split to
  3467. // two arguments.
  3468. SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
  3469. SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
  3470. BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
  3471. DAG.getIntPtrConstant(0, dl));
  3472. TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
  3473. DAG.getIntPtrConstant(1, dl));
  3474. // Ret is a node with an illegal type. Because such things are not
  3475. // generally permitted during this phase of legalization, make sure the
  3476. // node has no more uses. The above EXTRACT_ELEMENT nodes should have been
  3477. // folded.
  3478. assert(Ret->use_empty() &&
  3479. "Unexpected uses of illegally type from expanded lib call.");
  3480. }
  3481. if (isSigned) {
  3482. Tmp1 = DAG.getConstant(
  3483. VT.getSizeInBits() - 1, dl,
  3484. TLI.getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
  3485. Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
  3486. TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf, Tmp1,
  3487. ISD::SETNE);
  3488. } else {
  3489. TopHalf = DAG.getSetCC(dl, getSetCCResultType(VT), TopHalf,
  3490. DAG.getConstant(0, dl, VT), ISD::SETNE);
  3491. }
  3492. Results.push_back(BottomHalf);
  3493. Results.push_back(TopHalf);
  3494. break;
  3495. }
  3496. case ISD::BUILD_PAIR: {
  3497. EVT PairTy = Node->getValueType(0);
  3498. Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
  3499. Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
  3500. Tmp2 = DAG.getNode(
  3501. ISD::SHL, dl, PairTy, Tmp2,
  3502. DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
  3503. TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
  3504. Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
  3505. break;
  3506. }
  3507. case ISD::SELECT:
  3508. Tmp1 = Node->getOperand(0);
  3509. Tmp2 = Node->getOperand(1);
  3510. Tmp3 = Node->getOperand(2);
  3511. if (Tmp1.getOpcode() == ISD::SETCC) {
  3512. Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
  3513. Tmp2, Tmp3,
  3514. cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
  3515. } else {
  3516. Tmp1 = DAG.getSelectCC(dl, Tmp1,
  3517. DAG.getConstant(0, dl, Tmp1.getValueType()),
  3518. Tmp2, Tmp3, ISD::SETNE);
  3519. }
  3520. Results.push_back(Tmp1);
  3521. break;
  3522. case ISD::BR_JT: {
  3523. SDValue Chain = Node->getOperand(0);
  3524. SDValue Table = Node->getOperand(1);
  3525. SDValue Index = Node->getOperand(2);
  3526. EVT PTy = TLI.getPointerTy(DAG.getDataLayout());
  3527. const DataLayout &TD = DAG.getDataLayout();
  3528. unsigned EntrySize =
  3529. DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
  3530. Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
  3531. DAG.getConstant(EntrySize, dl, Index.getValueType()));
  3532. SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
  3533. Index, Table);
  3534. EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
  3535. SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
  3536. MachinePointerInfo::getJumpTable(), MemVT,
  3537. false, false, false, 0);
  3538. Addr = LD;
  3539. if (TM.getRelocationModel() == Reloc::PIC_) {
  3540. // For PIC, the sequence is:
  3541. // BRIND(load(Jumptable + index) + RelocBase)
  3542. // RelocBase can be JumpTable, GOT or some sort of global base.
  3543. Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
  3544. TLI.getPICJumpTableRelocBase(Table, DAG));
  3545. }
  3546. Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
  3547. Results.push_back(Tmp1);
  3548. break;
  3549. }
  3550. case ISD::BRCOND:
  3551. // Expand brcond's setcc into its constituent parts and create a BR_CC
  3552. // Node.
  3553. Tmp1 = Node->getOperand(0);
  3554. Tmp2 = Node->getOperand(1);
  3555. if (Tmp2.getOpcode() == ISD::SETCC) {
  3556. Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
  3557. Tmp1, Tmp2.getOperand(2),
  3558. Tmp2.getOperand(0), Tmp2.getOperand(1),
  3559. Node->getOperand(2));
  3560. } else {
  3561. // We test only the i1 bit. Skip the AND if UNDEF.
  3562. Tmp3 = (Tmp2.getOpcode() == ISD::UNDEF) ? Tmp2 :
  3563. DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
  3564. DAG.getConstant(1, dl, Tmp2.getValueType()));
  3565. Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
  3566. DAG.getCondCode(ISD::SETNE), Tmp3,
  3567. DAG.getConstant(0, dl, Tmp3.getValueType()),
  3568. Node->getOperand(2));
  3569. }
  3570. Results.push_back(Tmp1);
  3571. break;
  3572. case ISD::SETCC: {
  3573. Tmp1 = Node->getOperand(0);
  3574. Tmp2 = Node->getOperand(1);
  3575. Tmp3 = Node->getOperand(2);
  3576. bool Legalized = LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2,
  3577. Tmp3, NeedInvert, dl);
  3578. if (Legalized) {
  3579. // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
  3580. // condition code, create a new SETCC node.
  3581. if (Tmp3.getNode())
  3582. Tmp1 = DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
  3583. Tmp1, Tmp2, Tmp3);
  3584. // If we expanded the SETCC by inverting the condition code, then wrap
  3585. // the existing SETCC in a NOT to restore the intended condition.
  3586. if (NeedInvert)
  3587. Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
  3588. Results.push_back(Tmp1);
  3589. break;
  3590. }
  3591. // Otherwise, SETCC for the given comparison type must be completely
  3592. // illegal; expand it into a SELECT_CC.
  3593. EVT VT = Node->getValueType(0);
  3594. int TrueValue;
  3595. switch (TLI.getBooleanContents(Tmp1->getValueType(0))) {
  3596. case TargetLowering::ZeroOrOneBooleanContent:
  3597. case TargetLowering::UndefinedBooleanContent:
  3598. TrueValue = 1;
  3599. break;
  3600. case TargetLowering::ZeroOrNegativeOneBooleanContent:
  3601. TrueValue = -1;
  3602. break;
  3603. }
  3604. Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
  3605. DAG.getConstant(TrueValue, dl, VT),
  3606. DAG.getConstant(0, dl, VT),
  3607. Tmp3);
  3608. Results.push_back(Tmp1);
  3609. break;
  3610. }
  3611. case ISD::SELECT_CC: {
  3612. Tmp1 = Node->getOperand(0); // LHS
  3613. Tmp2 = Node->getOperand(1); // RHS
  3614. Tmp3 = Node->getOperand(2); // True
  3615. Tmp4 = Node->getOperand(3); // False
  3616. EVT VT = Node->getValueType(0);
  3617. SDValue CC = Node->getOperand(4);
  3618. ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
  3619. if (TLI.isCondCodeLegal(CCOp, Tmp1.getSimpleValueType())) {
  3620. // If the condition code is legal, then we need to expand this
  3621. // node using SETCC and SELECT.
  3622. EVT CmpVT = Tmp1.getValueType();
  3623. assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
  3624. "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
  3625. "expanded.");
  3626. EVT CCVT =
  3627. TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
  3628. SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC);
  3629. Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
  3630. break;
  3631. }
  3632. // SELECT_CC is legal, so the condition code must not be.
  3633. bool Legalized = false;
  3634. // Try to legalize by inverting the condition. This is for targets that
  3635. // might support an ordered version of a condition, but not the unordered
  3636. // version (or vice versa).
  3637. ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp,
  3638. Tmp1.getValueType().isInteger());
  3639. if (TLI.isCondCodeLegal(InvCC, Tmp1.getSimpleValueType())) {
  3640. // Use the new condition code and swap true and false
  3641. Legalized = true;
  3642. Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
  3643. } else {
  3644. // If The inverse is not legal, then try to swap the arguments using
  3645. // the inverse condition code.
  3646. ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
  3647. if (TLI.isCondCodeLegal(SwapInvCC, Tmp1.getSimpleValueType())) {
  3648. // The swapped inverse condition is legal, so swap true and false,
  3649. // lhs and rhs.
  3650. Legalized = true;
  3651. Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
  3652. }
  3653. }
  3654. if (!Legalized) {
  3655. Legalized = LegalizeSetCCCondCode(
  3656. getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC, NeedInvert,
  3657. dl);
  3658. assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
  3659. // If we expanded the SETCC by inverting the condition code, then swap
  3660. // the True/False operands to match.
  3661. if (NeedInvert)
  3662. std::swap(Tmp3, Tmp4);
  3663. // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
  3664. // condition code, create a new SELECT_CC node.
  3665. if (CC.getNode()) {
  3666. Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
  3667. Tmp1, Tmp2, Tmp3, Tmp4, CC);
  3668. } else {
  3669. Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
  3670. CC = DAG.getCondCode(ISD::SETNE);
  3671. Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
  3672. Tmp2, Tmp3, Tmp4, CC);
  3673. }
  3674. }
  3675. Results.push_back(Tmp1);
  3676. break;
  3677. }
  3678. case ISD::BR_CC: {
  3679. Tmp1 = Node->getOperand(0); // Chain
  3680. Tmp2 = Node->getOperand(2); // LHS
  3681. Tmp3 = Node->getOperand(3); // RHS
  3682. Tmp4 = Node->getOperand(1); // CC
  3683. bool Legalized = LegalizeSetCCCondCode(getSetCCResultType(
  3684. Tmp2.getValueType()), Tmp2, Tmp3, Tmp4, NeedInvert, dl);
  3685. (void)Legalized;
  3686. assert(Legalized && "Can't legalize BR_CC with legal condition!");
  3687. // If we expanded the SETCC by inverting the condition code, then wrap
  3688. // the existing SETCC in a NOT to restore the intended condition.
  3689. if (NeedInvert)
  3690. Tmp4 = DAG.getNOT(dl, Tmp4, Tmp4->getValueType(0));
  3691. // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
  3692. // node.
  3693. if (Tmp4.getNode()) {
  3694. Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
  3695. Tmp4, Tmp2, Tmp3, Node->getOperand(4));
  3696. } else {
  3697. Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
  3698. Tmp4 = DAG.getCondCode(ISD::SETNE);
  3699. Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
  3700. Tmp2, Tmp3, Node->getOperand(4));
  3701. }
  3702. Results.push_back(Tmp1);
  3703. break;
  3704. }
  3705. case ISD::BUILD_VECTOR:
  3706. Results.push_back(ExpandBUILD_VECTOR(Node));
  3707. break;
  3708. case ISD::SRA:
  3709. case ISD::SRL:
  3710. case ISD::SHL: {
  3711. // Scalarize vector SRA/SRL/SHL.
  3712. EVT VT = Node->getValueType(0);
  3713. assert(VT.isVector() && "Unable to legalize non-vector shift");
  3714. assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
  3715. unsigned NumElem = VT.getVectorNumElements();
  3716. SmallVector<SDValue, 8> Scalars;
  3717. for (unsigned Idx = 0; Idx < NumElem; Idx++) {
  3718. SDValue Ex = DAG.getNode(
  3719. ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(0),
  3720. DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3721. SDValue Sh = DAG.getNode(
  3722. ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(), Node->getOperand(1),
  3723. DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
  3724. Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
  3725. VT.getScalarType(), Ex, Sh));
  3726. }
  3727. SDValue Result =
  3728. DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0), Scalars);
  3729. ReplaceNode(SDValue(Node, 0), Result);
  3730. break;
  3731. }
  3732. case ISD::GLOBAL_OFFSET_TABLE:
  3733. case ISD::GlobalAddress:
  3734. case ISD::GlobalTLSAddress:
  3735. case ISD::ExternalSymbol:
  3736. case ISD::ConstantPool:
  3737. case ISD::JumpTable:
  3738. case ISD::INTRINSIC_W_CHAIN:
  3739. case ISD::INTRINSIC_WO_CHAIN:
  3740. case ISD::INTRINSIC_VOID:
  3741. // FIXME: Custom lowering for these operations shouldn't return null!
  3742. break;
  3743. }
  3744. // Replace the original node with the legalized result.
  3745. if (!Results.empty())
  3746. ReplaceNode(Node, Results.data());
  3747. }
  3748. void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
  3749. SmallVector<SDValue, 8> Results;
  3750. MVT OVT = Node->getSimpleValueType(0);
  3751. if (Node->getOpcode() == ISD::UINT_TO_FP ||
  3752. Node->getOpcode() == ISD::SINT_TO_FP ||
  3753. Node->getOpcode() == ISD::SETCC) {
  3754. OVT = Node->getOperand(0).getSimpleValueType();
  3755. }
  3756. if (Node->getOpcode() == ISD::BR_CC)
  3757. OVT = Node->getOperand(2).getSimpleValueType();
  3758. MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
  3759. SDLoc dl(Node);
  3760. SDValue Tmp1, Tmp2, Tmp3;
  3761. switch (Node->getOpcode()) {
  3762. case ISD::CTTZ:
  3763. case ISD::CTTZ_ZERO_UNDEF:
  3764. case ISD::CTLZ:
  3765. case ISD::CTLZ_ZERO_UNDEF:
  3766. case ISD::CTPOP:
  3767. // Zero extend the argument.
  3768. Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
  3769. // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
  3770. // already the correct result.
  3771. Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
  3772. if (Node->getOpcode() == ISD::CTTZ) {
  3773. // FIXME: This should set a bit in the zero extended value instead.
  3774. Tmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT),
  3775. Tmp1, DAG.getConstant(NVT.getSizeInBits(), dl, NVT),
  3776. ISD::SETEQ);
  3777. Tmp1 = DAG.getSelect(dl, NVT, Tmp2,
  3778. DAG.getConstant(OVT.getSizeInBits(), dl, NVT), Tmp1);
  3779. } else if (Node->getOpcode() == ISD::CTLZ ||
  3780. Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
  3781. // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
  3782. Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
  3783. DAG.getConstant(NVT.getSizeInBits() -
  3784. OVT.getSizeInBits(), dl, NVT));
  3785. }
  3786. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
  3787. break;
  3788. case ISD::BSWAP: {
  3789. unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
  3790. Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
  3791. Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
  3792. Tmp1 = DAG.getNode(
  3793. ISD::SRL, dl, NVT, Tmp1,
  3794. DAG.getConstant(DiffBits, dl,
  3795. TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
  3796. Results.push_back(Tmp1);
  3797. break;
  3798. }
  3799. case ISD::FP_TO_UINT:
  3800. case ISD::FP_TO_SINT:
  3801. Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
  3802. Node->getOpcode() == ISD::FP_TO_SINT, dl);
  3803. Results.push_back(Tmp1);
  3804. break;
  3805. case ISD::UINT_TO_FP:
  3806. case ISD::SINT_TO_FP:
  3807. Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
  3808. Node->getOpcode() == ISD::SINT_TO_FP, dl);
  3809. Results.push_back(Tmp1);
  3810. break;
  3811. case ISD::VAARG: {
  3812. SDValue Chain = Node->getOperand(0); // Get the chain.
  3813. SDValue Ptr = Node->getOperand(1); // Get the pointer.
  3814. unsigned TruncOp;
  3815. if (OVT.isVector()) {
  3816. TruncOp = ISD::BITCAST;
  3817. } else {
  3818. assert(OVT.isInteger()
  3819. && "VAARG promotion is supported only for vectors or integer types");
  3820. TruncOp = ISD::TRUNCATE;
  3821. }
  3822. // Perform the larger operation, then convert back
  3823. Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
  3824. Node->getConstantOperandVal(3));
  3825. Chain = Tmp1.getValue(1);
  3826. Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
  3827. // Modified the chain result - switch anything that used the old chain to
  3828. // use the new one.
  3829. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
  3830. DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
  3831. if (UpdatedNodes) {
  3832. UpdatedNodes->insert(Tmp2.getNode());
  3833. UpdatedNodes->insert(Chain.getNode());
  3834. }
  3835. ReplacedNode(Node);
  3836. break;
  3837. }
  3838. case ISD::AND:
  3839. case ISD::OR:
  3840. case ISD::XOR: {
  3841. unsigned ExtOp, TruncOp;
  3842. if (OVT.isVector()) {
  3843. ExtOp = ISD::BITCAST;
  3844. TruncOp = ISD::BITCAST;
  3845. } else {
  3846. assert(OVT.isInteger() && "Cannot promote logic operation");
  3847. ExtOp = ISD::ANY_EXTEND;
  3848. TruncOp = ISD::TRUNCATE;
  3849. }
  3850. // Promote each of the values to the new type.
  3851. Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
  3852. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
  3853. // Perform the larger operation, then convert back
  3854. Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
  3855. Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
  3856. break;
  3857. }
  3858. case ISD::SELECT: {
  3859. unsigned ExtOp, TruncOp;
  3860. if (Node->getValueType(0).isVector() ||
  3861. Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
  3862. ExtOp = ISD::BITCAST;
  3863. TruncOp = ISD::BITCAST;
  3864. } else if (Node->getValueType(0).isInteger()) {
  3865. ExtOp = ISD::ANY_EXTEND;
  3866. TruncOp = ISD::TRUNCATE;
  3867. } else {
  3868. ExtOp = ISD::FP_EXTEND;
  3869. TruncOp = ISD::FP_ROUND;
  3870. }
  3871. Tmp1 = Node->getOperand(0);
  3872. // Promote each of the values to the new type.
  3873. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
  3874. Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
  3875. // Perform the larger operation, then round down.
  3876. Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
  3877. if (TruncOp != ISD::FP_ROUND)
  3878. Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
  3879. else
  3880. Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
  3881. DAG.getIntPtrConstant(0, dl));
  3882. Results.push_back(Tmp1);
  3883. break;
  3884. }
  3885. case ISD::VECTOR_SHUFFLE: {
  3886. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
  3887. // Cast the two input vectors.
  3888. Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
  3889. Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
  3890. // Convert the shuffle mask to the right # elements.
  3891. Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
  3892. Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
  3893. Results.push_back(Tmp1);
  3894. break;
  3895. }
  3896. case ISD::SETCC: {
  3897. unsigned ExtOp = ISD::FP_EXTEND;
  3898. if (NVT.isInteger()) {
  3899. ISD::CondCode CCCode =
  3900. cast<CondCodeSDNode>(Node->getOperand(2))->get();
  3901. ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  3902. }
  3903. Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
  3904. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
  3905. Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
  3906. Tmp1, Tmp2, Node->getOperand(2)));
  3907. break;
  3908. }
  3909. case ISD::BR_CC: {
  3910. unsigned ExtOp = ISD::FP_EXTEND;
  3911. if (NVT.isInteger()) {
  3912. ISD::CondCode CCCode =
  3913. cast<CondCodeSDNode>(Node->getOperand(1))->get();
  3914. ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  3915. }
  3916. Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
  3917. Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
  3918. Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
  3919. Node->getOperand(0), Node->getOperand(1),
  3920. Tmp1, Tmp2, Node->getOperand(4)));
  3921. break;
  3922. }
  3923. case ISD::FADD:
  3924. case ISD::FSUB:
  3925. case ISD::FMUL:
  3926. case ISD::FDIV:
  3927. case ISD::FREM:
  3928. case ISD::FMINNUM:
  3929. case ISD::FMAXNUM:
  3930. case ISD::FCOPYSIGN:
  3931. case ISD::FPOW: {
  3932. Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
  3933. Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
  3934. Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
  3935. Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
  3936. Tmp3, DAG.getIntPtrConstant(0, dl)));
  3937. break;
  3938. }
  3939. case ISD::FMA: {
  3940. Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
  3941. Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
  3942. Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
  3943. Results.push_back(
  3944. DAG.getNode(ISD::FP_ROUND, dl, OVT,
  3945. DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
  3946. DAG.getIntPtrConstant(0, dl)));
  3947. break;
  3948. }
  3949. case ISD::FPOWI: {
  3950. Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
  3951. Tmp2 = Node->getOperand(1);
  3952. Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
  3953. Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
  3954. Tmp3, DAG.getIntPtrConstant(0, dl)));
  3955. break;
  3956. }
  3957. case ISD::FFLOOR:
  3958. case ISD::FCEIL:
  3959. case ISD::FRINT:
  3960. case ISD::FNEARBYINT:
  3961. case ISD::FROUND:
  3962. case ISD::FTRUNC:
  3963. case ISD::FNEG:
  3964. case ISD::FSQRT:
  3965. case ISD::FSIN:
  3966. case ISD::FCOS:
  3967. case ISD::FLOG:
  3968. case ISD::FLOG2:
  3969. case ISD::FLOG10:
  3970. case ISD::FABS:
  3971. case ISD::FEXP:
  3972. case ISD::FEXP2: {
  3973. Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
  3974. Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
  3975. Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
  3976. Tmp2, DAG.getIntPtrConstant(0, dl)));
  3977. break;
  3978. }
  3979. }
  3980. // Replace the original node with the legalized result.
  3981. if (!Results.empty())
  3982. ReplaceNode(Node, Results.data());
  3983. }
  3984. /// This is the entry point for the file.
  3985. void SelectionDAG::Legalize() {
  3986. AssignTopologicalOrder();
  3987. SmallPtrSet<SDNode *, 16> LegalizedNodes;
  3988. SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
  3989. // Visit all the nodes. We start in topological order, so that we see
  3990. // nodes with their original operands intact. Legalization can produce
  3991. // new nodes which may themselves need to be legalized. Iterate until all
  3992. // nodes have been legalized.
  3993. for (;;) {
  3994. bool AnyLegalized = false;
  3995. for (auto NI = allnodes_end(); NI != allnodes_begin();) {
  3996. --NI;
  3997. SDNode *N = NI;
  3998. if (N->use_empty() && N != getRoot().getNode()) {
  3999. ++NI;
  4000. DeleteNode(N);
  4001. continue;
  4002. }
  4003. if (LegalizedNodes.insert(N).second) {
  4004. AnyLegalized = true;
  4005. Legalizer.LegalizeOp(N);
  4006. if (N->use_empty() && N != getRoot().getNode()) {
  4007. ++NI;
  4008. DeleteNode(N);
  4009. }
  4010. }
  4011. }
  4012. if (!AnyLegalized)
  4013. break;
  4014. }
  4015. // Remove dead nodes now.
  4016. RemoveDeadNodes();
  4017. }
  4018. bool SelectionDAG::LegalizeOp(SDNode *N,
  4019. SmallSetVector<SDNode *, 16> &UpdatedNodes) {
  4020. SmallPtrSet<SDNode *, 16> LegalizedNodes;
  4021. SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
  4022. // Directly insert the node in question, and legalize it. This will recurse
  4023. // as needed through operands.
  4024. LegalizedNodes.insert(N);
  4025. Legalizer.LegalizeOp(N);
  4026. return LegalizedNodes.count(N);
  4027. }