LegalizeDAG.cpp 199 KB

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