LegalizeDAG.cpp 179 KB

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