X86FastISel.cpp 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019
  1. //===-- X86FastISel.cpp - X86 FastISel implementation ---------------------===//
  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 defines the X86-specific support for the FastISel class. Much
  10. // of the target-specific code is generated by tablegen in the file
  11. // X86GenFastISel.inc, which is #included here.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "X86.h"
  15. #include "X86CallingConv.h"
  16. #include "X86InstrBuilder.h"
  17. #include "X86InstrInfo.h"
  18. #include "X86MachineFunctionInfo.h"
  19. #include "X86RegisterInfo.h"
  20. #include "X86Subtarget.h"
  21. #include "X86TargetMachine.h"
  22. #include "llvm/Analysis/BranchProbabilityInfo.h"
  23. #include "llvm/CodeGen/FastISel.h"
  24. #include "llvm/CodeGen/FunctionLoweringInfo.h"
  25. #include "llvm/CodeGen/MachineConstantPool.h"
  26. #include "llvm/CodeGen/MachineFrameInfo.h"
  27. #include "llvm/CodeGen/MachineRegisterInfo.h"
  28. #include "llvm/IR/CallingConv.h"
  29. #include "llvm/IR/DebugInfo.h"
  30. #include "llvm/IR/DerivedTypes.h"
  31. #include "llvm/IR/GetElementPtrTypeIterator.h"
  32. #include "llvm/IR/GlobalAlias.h"
  33. #include "llvm/IR/GlobalVariable.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/IntrinsicsX86.h"
  37. #include "llvm/IR/Operator.h"
  38. #include "llvm/MC/MCAsmInfo.h"
  39. #include "llvm/MC/MCSymbol.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include "llvm/Target/TargetOptions.h"
  42. using namespace llvm;
  43. namespace {
  44. class X86FastISel final : public FastISel {
  45. /// Subtarget - Keep a pointer to the X86Subtarget around so that we can
  46. /// make the right decision when generating code for different targets.
  47. const X86Subtarget *Subtarget;
  48. /// X86ScalarSSEf32, X86ScalarSSEf64 - Select between SSE or x87
  49. /// floating point ops.
  50. /// When SSE is available, use it for f32 operations.
  51. /// When SSE2 is available, use it for f64 operations.
  52. bool X86ScalarSSEf64;
  53. bool X86ScalarSSEf32;
  54. bool X86ScalarSSEf16;
  55. public:
  56. explicit X86FastISel(FunctionLoweringInfo &funcInfo,
  57. const TargetLibraryInfo *libInfo)
  58. : FastISel(funcInfo, libInfo) {
  59. Subtarget = &funcInfo.MF->getSubtarget<X86Subtarget>();
  60. X86ScalarSSEf64 = Subtarget->hasSSE2();
  61. X86ScalarSSEf32 = Subtarget->hasSSE1();
  62. X86ScalarSSEf16 = Subtarget->hasFP16();
  63. }
  64. bool fastSelectInstruction(const Instruction *I) override;
  65. /// The specified machine instr operand is a vreg, and that
  66. /// vreg is being provided by the specified load instruction. If possible,
  67. /// try to fold the load as an operand to the instruction, returning true if
  68. /// possible.
  69. bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
  70. const LoadInst *LI) override;
  71. bool fastLowerArguments() override;
  72. bool fastLowerCall(CallLoweringInfo &CLI) override;
  73. bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
  74. #include "X86GenFastISel.inc"
  75. private:
  76. bool X86FastEmitCompare(const Value *LHS, const Value *RHS, EVT VT,
  77. const DebugLoc &DL);
  78. bool X86FastEmitLoad(MVT VT, X86AddressMode &AM, MachineMemOperand *MMO,
  79. unsigned &ResultReg, unsigned Alignment = 1);
  80. bool X86FastEmitStore(EVT VT, const Value *Val, X86AddressMode &AM,
  81. MachineMemOperand *MMO = nullptr, bool Aligned = false);
  82. bool X86FastEmitStore(EVT VT, unsigned ValReg, X86AddressMode &AM,
  83. MachineMemOperand *MMO = nullptr, bool Aligned = false);
  84. bool X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src, EVT SrcVT,
  85. unsigned &ResultReg);
  86. bool X86SelectAddress(const Value *V, X86AddressMode &AM);
  87. bool X86SelectCallAddress(const Value *V, X86AddressMode &AM);
  88. bool X86SelectLoad(const Instruction *I);
  89. bool X86SelectStore(const Instruction *I);
  90. bool X86SelectRet(const Instruction *I);
  91. bool X86SelectCmp(const Instruction *I);
  92. bool X86SelectZExt(const Instruction *I);
  93. bool X86SelectSExt(const Instruction *I);
  94. bool X86SelectBranch(const Instruction *I);
  95. bool X86SelectShift(const Instruction *I);
  96. bool X86SelectDivRem(const Instruction *I);
  97. bool X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I);
  98. bool X86FastEmitSSESelect(MVT RetVT, const Instruction *I);
  99. bool X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I);
  100. bool X86SelectSelect(const Instruction *I);
  101. bool X86SelectTrunc(const Instruction *I);
  102. bool X86SelectFPExtOrFPTrunc(const Instruction *I, unsigned Opc,
  103. const TargetRegisterClass *RC);
  104. bool X86SelectFPExt(const Instruction *I);
  105. bool X86SelectFPTrunc(const Instruction *I);
  106. bool X86SelectSIToFP(const Instruction *I);
  107. bool X86SelectUIToFP(const Instruction *I);
  108. bool X86SelectIntToFP(const Instruction *I, bool IsSigned);
  109. const X86InstrInfo *getInstrInfo() const {
  110. return Subtarget->getInstrInfo();
  111. }
  112. const X86TargetMachine *getTargetMachine() const {
  113. return static_cast<const X86TargetMachine *>(&TM);
  114. }
  115. bool handleConstantAddresses(const Value *V, X86AddressMode &AM);
  116. unsigned X86MaterializeInt(const ConstantInt *CI, MVT VT);
  117. unsigned X86MaterializeFP(const ConstantFP *CFP, MVT VT);
  118. unsigned X86MaterializeGV(const GlobalValue *GV, MVT VT);
  119. unsigned fastMaterializeConstant(const Constant *C) override;
  120. unsigned fastMaterializeAlloca(const AllocaInst *C) override;
  121. unsigned fastMaterializeFloatZero(const ConstantFP *CF) override;
  122. /// isScalarFPTypeInSSEReg - Return true if the specified scalar FP type is
  123. /// computed in an SSE register, not on the X87 floating point stack.
  124. bool isScalarFPTypeInSSEReg(EVT VT) const {
  125. return (VT == MVT::f64 && X86ScalarSSEf64) || // f64 is when SSE2
  126. (VT == MVT::f32 && X86ScalarSSEf32) || // f32 is when SSE1
  127. (VT == MVT::f16 && X86ScalarSSEf16); // f16 is when AVX512FP16
  128. }
  129. bool isTypeLegal(Type *Ty, MVT &VT, bool AllowI1 = false);
  130. bool IsMemcpySmall(uint64_t Len);
  131. bool TryEmitSmallMemcpy(X86AddressMode DestAM,
  132. X86AddressMode SrcAM, uint64_t Len);
  133. bool foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
  134. const Value *Cond);
  135. const MachineInstrBuilder &addFullAddress(const MachineInstrBuilder &MIB,
  136. X86AddressMode &AM);
  137. unsigned fastEmitInst_rrrr(unsigned MachineInstOpcode,
  138. const TargetRegisterClass *RC, unsigned Op0,
  139. unsigned Op1, unsigned Op2, unsigned Op3);
  140. };
  141. } // end anonymous namespace.
  142. static std::pair<unsigned, bool>
  143. getX86SSEConditionCode(CmpInst::Predicate Predicate) {
  144. unsigned CC;
  145. bool NeedSwap = false;
  146. // SSE Condition code mapping:
  147. // 0 - EQ
  148. // 1 - LT
  149. // 2 - LE
  150. // 3 - UNORD
  151. // 4 - NEQ
  152. // 5 - NLT
  153. // 6 - NLE
  154. // 7 - ORD
  155. switch (Predicate) {
  156. default: llvm_unreachable("Unexpected predicate");
  157. case CmpInst::FCMP_OEQ: CC = 0; break;
  158. case CmpInst::FCMP_OGT: NeedSwap = true; LLVM_FALLTHROUGH;
  159. case CmpInst::FCMP_OLT: CC = 1; break;
  160. case CmpInst::FCMP_OGE: NeedSwap = true; LLVM_FALLTHROUGH;
  161. case CmpInst::FCMP_OLE: CC = 2; break;
  162. case CmpInst::FCMP_UNO: CC = 3; break;
  163. case CmpInst::FCMP_UNE: CC = 4; break;
  164. case CmpInst::FCMP_ULE: NeedSwap = true; LLVM_FALLTHROUGH;
  165. case CmpInst::FCMP_UGE: CC = 5; break;
  166. case CmpInst::FCMP_ULT: NeedSwap = true; LLVM_FALLTHROUGH;
  167. case CmpInst::FCMP_UGT: CC = 6; break;
  168. case CmpInst::FCMP_ORD: CC = 7; break;
  169. case CmpInst::FCMP_UEQ: CC = 8; break;
  170. case CmpInst::FCMP_ONE: CC = 12; break;
  171. }
  172. return std::make_pair(CC, NeedSwap);
  173. }
  174. /// Adds a complex addressing mode to the given machine instr builder.
  175. /// Note, this will constrain the index register. If its not possible to
  176. /// constrain the given index register, then a new one will be created. The
  177. /// IndexReg field of the addressing mode will be updated to match in this case.
  178. const MachineInstrBuilder &
  179. X86FastISel::addFullAddress(const MachineInstrBuilder &MIB,
  180. X86AddressMode &AM) {
  181. // First constrain the index register. It needs to be a GR64_NOSP.
  182. AM.IndexReg = constrainOperandRegClass(MIB->getDesc(), AM.IndexReg,
  183. MIB->getNumOperands() +
  184. X86::AddrIndexReg);
  185. return ::addFullAddress(MIB, AM);
  186. }
  187. /// Check if it is possible to fold the condition from the XALU intrinsic
  188. /// into the user. The condition code will only be updated on success.
  189. bool X86FastISel::foldX86XALUIntrinsic(X86::CondCode &CC, const Instruction *I,
  190. const Value *Cond) {
  191. if (!isa<ExtractValueInst>(Cond))
  192. return false;
  193. const auto *EV = cast<ExtractValueInst>(Cond);
  194. if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
  195. return false;
  196. const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
  197. MVT RetVT;
  198. const Function *Callee = II->getCalledFunction();
  199. Type *RetTy =
  200. cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
  201. if (!isTypeLegal(RetTy, RetVT))
  202. return false;
  203. if (RetVT != MVT::i32 && RetVT != MVT::i64)
  204. return false;
  205. X86::CondCode TmpCC;
  206. switch (II->getIntrinsicID()) {
  207. default: return false;
  208. case Intrinsic::sadd_with_overflow:
  209. case Intrinsic::ssub_with_overflow:
  210. case Intrinsic::smul_with_overflow:
  211. case Intrinsic::umul_with_overflow: TmpCC = X86::COND_O; break;
  212. case Intrinsic::uadd_with_overflow:
  213. case Intrinsic::usub_with_overflow: TmpCC = X86::COND_B; break;
  214. }
  215. // Check if both instructions are in the same basic block.
  216. if (II->getParent() != I->getParent())
  217. return false;
  218. // Make sure nothing is in the way
  219. BasicBlock::const_iterator Start(I);
  220. BasicBlock::const_iterator End(II);
  221. for (auto Itr = std::prev(Start); Itr != End; --Itr) {
  222. // We only expect extractvalue instructions between the intrinsic and the
  223. // instruction to be selected.
  224. if (!isa<ExtractValueInst>(Itr))
  225. return false;
  226. // Check that the extractvalue operand comes from the intrinsic.
  227. const auto *EVI = cast<ExtractValueInst>(Itr);
  228. if (EVI->getAggregateOperand() != II)
  229. return false;
  230. }
  231. // Make sure no potentially eflags clobbering phi moves can be inserted in
  232. // between.
  233. auto HasPhis = [](const BasicBlock *Succ) {
  234. return !llvm::empty(Succ->phis());
  235. };
  236. if (I->isTerminator() && llvm::any_of(successors(I), HasPhis))
  237. return false;
  238. CC = TmpCC;
  239. return true;
  240. }
  241. bool X86FastISel::isTypeLegal(Type *Ty, MVT &VT, bool AllowI1) {
  242. EVT evt = TLI.getValueType(DL, Ty, /*AllowUnknown=*/true);
  243. if (evt == MVT::Other || !evt.isSimple())
  244. // Unhandled type. Halt "fast" selection and bail.
  245. return false;
  246. VT = evt.getSimpleVT();
  247. // For now, require SSE/SSE2 for performing floating-point operations,
  248. // since x87 requires additional work.
  249. if (VT == MVT::f64 && !X86ScalarSSEf64)
  250. return false;
  251. if (VT == MVT::f32 && !X86ScalarSSEf32)
  252. return false;
  253. // Similarly, no f80 support yet.
  254. if (VT == MVT::f80)
  255. return false;
  256. // We only handle legal types. For example, on x86-32 the instruction
  257. // selector contains all of the 64-bit instructions from x86-64,
  258. // under the assumption that i64 won't be used if the target doesn't
  259. // support it.
  260. return (AllowI1 && VT == MVT::i1) || TLI.isTypeLegal(VT);
  261. }
  262. /// X86FastEmitLoad - Emit a machine instruction to load a value of type VT.
  263. /// The address is either pre-computed, i.e. Ptr, or a GlobalAddress, i.e. GV.
  264. /// Return true and the result register by reference if it is possible.
  265. bool X86FastISel::X86FastEmitLoad(MVT VT, X86AddressMode &AM,
  266. MachineMemOperand *MMO, unsigned &ResultReg,
  267. unsigned Alignment) {
  268. bool HasSSE41 = Subtarget->hasSSE41();
  269. bool HasAVX = Subtarget->hasAVX();
  270. bool HasAVX2 = Subtarget->hasAVX2();
  271. bool HasAVX512 = Subtarget->hasAVX512();
  272. bool HasVLX = Subtarget->hasVLX();
  273. bool IsNonTemporal = MMO && MMO->isNonTemporal();
  274. // Treat i1 loads the same as i8 loads. Masking will be done when storing.
  275. if (VT == MVT::i1)
  276. VT = MVT::i8;
  277. // Get opcode and regclass of the output for the given load instruction.
  278. unsigned Opc = 0;
  279. switch (VT.SimpleTy) {
  280. default: return false;
  281. case MVT::i8:
  282. Opc = X86::MOV8rm;
  283. break;
  284. case MVT::i16:
  285. Opc = X86::MOV16rm;
  286. break;
  287. case MVT::i32:
  288. Opc = X86::MOV32rm;
  289. break;
  290. case MVT::i64:
  291. // Must be in x86-64 mode.
  292. Opc = X86::MOV64rm;
  293. break;
  294. case MVT::f32:
  295. if (X86ScalarSSEf32)
  296. Opc = HasAVX512 ? X86::VMOVSSZrm_alt :
  297. HasAVX ? X86::VMOVSSrm_alt :
  298. X86::MOVSSrm_alt;
  299. else
  300. Opc = X86::LD_Fp32m;
  301. break;
  302. case MVT::f64:
  303. if (X86ScalarSSEf64)
  304. Opc = HasAVX512 ? X86::VMOVSDZrm_alt :
  305. HasAVX ? X86::VMOVSDrm_alt :
  306. X86::MOVSDrm_alt;
  307. else
  308. Opc = X86::LD_Fp64m;
  309. break;
  310. case MVT::f80:
  311. // No f80 support yet.
  312. return false;
  313. case MVT::v4f32:
  314. if (IsNonTemporal && Alignment >= 16 && HasSSE41)
  315. Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
  316. HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
  317. else if (Alignment >= 16)
  318. Opc = HasVLX ? X86::VMOVAPSZ128rm :
  319. HasAVX ? X86::VMOVAPSrm : X86::MOVAPSrm;
  320. else
  321. Opc = HasVLX ? X86::VMOVUPSZ128rm :
  322. HasAVX ? X86::VMOVUPSrm : X86::MOVUPSrm;
  323. break;
  324. case MVT::v2f64:
  325. if (IsNonTemporal && Alignment >= 16 && HasSSE41)
  326. Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
  327. HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
  328. else if (Alignment >= 16)
  329. Opc = HasVLX ? X86::VMOVAPDZ128rm :
  330. HasAVX ? X86::VMOVAPDrm : X86::MOVAPDrm;
  331. else
  332. Opc = HasVLX ? X86::VMOVUPDZ128rm :
  333. HasAVX ? X86::VMOVUPDrm : X86::MOVUPDrm;
  334. break;
  335. case MVT::v4i32:
  336. case MVT::v2i64:
  337. case MVT::v8i16:
  338. case MVT::v16i8:
  339. if (IsNonTemporal && Alignment >= 16 && HasSSE41)
  340. Opc = HasVLX ? X86::VMOVNTDQAZ128rm :
  341. HasAVX ? X86::VMOVNTDQArm : X86::MOVNTDQArm;
  342. else if (Alignment >= 16)
  343. Opc = HasVLX ? X86::VMOVDQA64Z128rm :
  344. HasAVX ? X86::VMOVDQArm : X86::MOVDQArm;
  345. else
  346. Opc = HasVLX ? X86::VMOVDQU64Z128rm :
  347. HasAVX ? X86::VMOVDQUrm : X86::MOVDQUrm;
  348. break;
  349. case MVT::v8f32:
  350. assert(HasAVX);
  351. if (IsNonTemporal && Alignment >= 32 && HasAVX2)
  352. Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
  353. else if (IsNonTemporal && Alignment >= 16)
  354. return false; // Force split for X86::VMOVNTDQArm
  355. else if (Alignment >= 32)
  356. Opc = HasVLX ? X86::VMOVAPSZ256rm : X86::VMOVAPSYrm;
  357. else
  358. Opc = HasVLX ? X86::VMOVUPSZ256rm : X86::VMOVUPSYrm;
  359. break;
  360. case MVT::v4f64:
  361. assert(HasAVX);
  362. if (IsNonTemporal && Alignment >= 32 && HasAVX2)
  363. Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
  364. else if (IsNonTemporal && Alignment >= 16)
  365. return false; // Force split for X86::VMOVNTDQArm
  366. else if (Alignment >= 32)
  367. Opc = HasVLX ? X86::VMOVAPDZ256rm : X86::VMOVAPDYrm;
  368. else
  369. Opc = HasVLX ? X86::VMOVUPDZ256rm : X86::VMOVUPDYrm;
  370. break;
  371. case MVT::v8i32:
  372. case MVT::v4i64:
  373. case MVT::v16i16:
  374. case MVT::v32i8:
  375. assert(HasAVX);
  376. if (IsNonTemporal && Alignment >= 32 && HasAVX2)
  377. Opc = HasVLX ? X86::VMOVNTDQAZ256rm : X86::VMOVNTDQAYrm;
  378. else if (IsNonTemporal && Alignment >= 16)
  379. return false; // Force split for X86::VMOVNTDQArm
  380. else if (Alignment >= 32)
  381. Opc = HasVLX ? X86::VMOVDQA64Z256rm : X86::VMOVDQAYrm;
  382. else
  383. Opc = HasVLX ? X86::VMOVDQU64Z256rm : X86::VMOVDQUYrm;
  384. break;
  385. case MVT::v16f32:
  386. assert(HasAVX512);
  387. if (IsNonTemporal && Alignment >= 64)
  388. Opc = X86::VMOVNTDQAZrm;
  389. else
  390. Opc = (Alignment >= 64) ? X86::VMOVAPSZrm : X86::VMOVUPSZrm;
  391. break;
  392. case MVT::v8f64:
  393. assert(HasAVX512);
  394. if (IsNonTemporal && Alignment >= 64)
  395. Opc = X86::VMOVNTDQAZrm;
  396. else
  397. Opc = (Alignment >= 64) ? X86::VMOVAPDZrm : X86::VMOVUPDZrm;
  398. break;
  399. case MVT::v8i64:
  400. case MVT::v16i32:
  401. case MVT::v32i16:
  402. case MVT::v64i8:
  403. assert(HasAVX512);
  404. // Note: There are a lot more choices based on type with AVX-512, but
  405. // there's really no advantage when the load isn't masked.
  406. if (IsNonTemporal && Alignment >= 64)
  407. Opc = X86::VMOVNTDQAZrm;
  408. else
  409. Opc = (Alignment >= 64) ? X86::VMOVDQA64Zrm : X86::VMOVDQU64Zrm;
  410. break;
  411. }
  412. const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
  413. ResultReg = createResultReg(RC);
  414. MachineInstrBuilder MIB =
  415. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
  416. addFullAddress(MIB, AM);
  417. if (MMO)
  418. MIB->addMemOperand(*FuncInfo.MF, MMO);
  419. return true;
  420. }
  421. /// X86FastEmitStore - Emit a machine instruction to store a value Val of
  422. /// type VT. The address is either pre-computed, consisted of a base ptr, Ptr
  423. /// and a displacement offset, or a GlobalAddress,
  424. /// i.e. V. Return true if it is possible.
  425. bool X86FastISel::X86FastEmitStore(EVT VT, unsigned ValReg, X86AddressMode &AM,
  426. MachineMemOperand *MMO, bool Aligned) {
  427. bool HasSSE1 = Subtarget->hasSSE1();
  428. bool HasSSE2 = Subtarget->hasSSE2();
  429. bool HasSSE4A = Subtarget->hasSSE4A();
  430. bool HasAVX = Subtarget->hasAVX();
  431. bool HasAVX512 = Subtarget->hasAVX512();
  432. bool HasVLX = Subtarget->hasVLX();
  433. bool IsNonTemporal = MMO && MMO->isNonTemporal();
  434. // Get opcode and regclass of the output for the given store instruction.
  435. unsigned Opc = 0;
  436. switch (VT.getSimpleVT().SimpleTy) {
  437. case MVT::f80: // No f80 support yet.
  438. default: return false;
  439. case MVT::i1: {
  440. // Mask out all but lowest bit.
  441. Register AndResult = createResultReg(&X86::GR8RegClass);
  442. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  443. TII.get(X86::AND8ri), AndResult)
  444. .addReg(ValReg).addImm(1);
  445. ValReg = AndResult;
  446. LLVM_FALLTHROUGH; // handle i1 as i8.
  447. }
  448. case MVT::i8: Opc = X86::MOV8mr; break;
  449. case MVT::i16: Opc = X86::MOV16mr; break;
  450. case MVT::i32:
  451. Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTImr : X86::MOV32mr;
  452. break;
  453. case MVT::i64:
  454. // Must be in x86-64 mode.
  455. Opc = (IsNonTemporal && HasSSE2) ? X86::MOVNTI_64mr : X86::MOV64mr;
  456. break;
  457. case MVT::f32:
  458. if (X86ScalarSSEf32) {
  459. if (IsNonTemporal && HasSSE4A)
  460. Opc = X86::MOVNTSS;
  461. else
  462. Opc = HasAVX512 ? X86::VMOVSSZmr :
  463. HasAVX ? X86::VMOVSSmr : X86::MOVSSmr;
  464. } else
  465. Opc = X86::ST_Fp32m;
  466. break;
  467. case MVT::f64:
  468. if (X86ScalarSSEf32) {
  469. if (IsNonTemporal && HasSSE4A)
  470. Opc = X86::MOVNTSD;
  471. else
  472. Opc = HasAVX512 ? X86::VMOVSDZmr :
  473. HasAVX ? X86::VMOVSDmr : X86::MOVSDmr;
  474. } else
  475. Opc = X86::ST_Fp64m;
  476. break;
  477. case MVT::x86mmx:
  478. Opc = (IsNonTemporal && HasSSE1) ? X86::MMX_MOVNTQmr : X86::MMX_MOVQ64mr;
  479. break;
  480. case MVT::v4f32:
  481. if (Aligned) {
  482. if (IsNonTemporal)
  483. Opc = HasVLX ? X86::VMOVNTPSZ128mr :
  484. HasAVX ? X86::VMOVNTPSmr : X86::MOVNTPSmr;
  485. else
  486. Opc = HasVLX ? X86::VMOVAPSZ128mr :
  487. HasAVX ? X86::VMOVAPSmr : X86::MOVAPSmr;
  488. } else
  489. Opc = HasVLX ? X86::VMOVUPSZ128mr :
  490. HasAVX ? X86::VMOVUPSmr : X86::MOVUPSmr;
  491. break;
  492. case MVT::v2f64:
  493. if (Aligned) {
  494. if (IsNonTemporal)
  495. Opc = HasVLX ? X86::VMOVNTPDZ128mr :
  496. HasAVX ? X86::VMOVNTPDmr : X86::MOVNTPDmr;
  497. else
  498. Opc = HasVLX ? X86::VMOVAPDZ128mr :
  499. HasAVX ? X86::VMOVAPDmr : X86::MOVAPDmr;
  500. } else
  501. Opc = HasVLX ? X86::VMOVUPDZ128mr :
  502. HasAVX ? X86::VMOVUPDmr : X86::MOVUPDmr;
  503. break;
  504. case MVT::v4i32:
  505. case MVT::v2i64:
  506. case MVT::v8i16:
  507. case MVT::v16i8:
  508. if (Aligned) {
  509. if (IsNonTemporal)
  510. Opc = HasVLX ? X86::VMOVNTDQZ128mr :
  511. HasAVX ? X86::VMOVNTDQmr : X86::MOVNTDQmr;
  512. else
  513. Opc = HasVLX ? X86::VMOVDQA64Z128mr :
  514. HasAVX ? X86::VMOVDQAmr : X86::MOVDQAmr;
  515. } else
  516. Opc = HasVLX ? X86::VMOVDQU64Z128mr :
  517. HasAVX ? X86::VMOVDQUmr : X86::MOVDQUmr;
  518. break;
  519. case MVT::v8f32:
  520. assert(HasAVX);
  521. if (Aligned) {
  522. if (IsNonTemporal)
  523. Opc = HasVLX ? X86::VMOVNTPSZ256mr : X86::VMOVNTPSYmr;
  524. else
  525. Opc = HasVLX ? X86::VMOVAPSZ256mr : X86::VMOVAPSYmr;
  526. } else
  527. Opc = HasVLX ? X86::VMOVUPSZ256mr : X86::VMOVUPSYmr;
  528. break;
  529. case MVT::v4f64:
  530. assert(HasAVX);
  531. if (Aligned) {
  532. if (IsNonTemporal)
  533. Opc = HasVLX ? X86::VMOVNTPDZ256mr : X86::VMOVNTPDYmr;
  534. else
  535. Opc = HasVLX ? X86::VMOVAPDZ256mr : X86::VMOVAPDYmr;
  536. } else
  537. Opc = HasVLX ? X86::VMOVUPDZ256mr : X86::VMOVUPDYmr;
  538. break;
  539. case MVT::v8i32:
  540. case MVT::v4i64:
  541. case MVT::v16i16:
  542. case MVT::v32i8:
  543. assert(HasAVX);
  544. if (Aligned) {
  545. if (IsNonTemporal)
  546. Opc = HasVLX ? X86::VMOVNTDQZ256mr : X86::VMOVNTDQYmr;
  547. else
  548. Opc = HasVLX ? X86::VMOVDQA64Z256mr : X86::VMOVDQAYmr;
  549. } else
  550. Opc = HasVLX ? X86::VMOVDQU64Z256mr : X86::VMOVDQUYmr;
  551. break;
  552. case MVT::v16f32:
  553. assert(HasAVX512);
  554. if (Aligned)
  555. Opc = IsNonTemporal ? X86::VMOVNTPSZmr : X86::VMOVAPSZmr;
  556. else
  557. Opc = X86::VMOVUPSZmr;
  558. break;
  559. case MVT::v8f64:
  560. assert(HasAVX512);
  561. if (Aligned) {
  562. Opc = IsNonTemporal ? X86::VMOVNTPDZmr : X86::VMOVAPDZmr;
  563. } else
  564. Opc = X86::VMOVUPDZmr;
  565. break;
  566. case MVT::v8i64:
  567. case MVT::v16i32:
  568. case MVT::v32i16:
  569. case MVT::v64i8:
  570. assert(HasAVX512);
  571. // Note: There are a lot more choices based on type with AVX-512, but
  572. // there's really no advantage when the store isn't masked.
  573. if (Aligned)
  574. Opc = IsNonTemporal ? X86::VMOVNTDQZmr : X86::VMOVDQA64Zmr;
  575. else
  576. Opc = X86::VMOVDQU64Zmr;
  577. break;
  578. }
  579. const MCInstrDesc &Desc = TII.get(Opc);
  580. // Some of the instructions in the previous switch use FR128 instead
  581. // of FR32 for ValReg. Make sure the register we feed the instruction
  582. // matches its register class constraints.
  583. // Note: This is fine to do a copy from FR32 to FR128, this is the
  584. // same registers behind the scene and actually why it did not trigger
  585. // any bugs before.
  586. ValReg = constrainOperandRegClass(Desc, ValReg, Desc.getNumOperands() - 1);
  587. MachineInstrBuilder MIB =
  588. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, Desc);
  589. addFullAddress(MIB, AM).addReg(ValReg);
  590. if (MMO)
  591. MIB->addMemOperand(*FuncInfo.MF, MMO);
  592. return true;
  593. }
  594. bool X86FastISel::X86FastEmitStore(EVT VT, const Value *Val,
  595. X86AddressMode &AM,
  596. MachineMemOperand *MMO, bool Aligned) {
  597. // Handle 'null' like i32/i64 0.
  598. if (isa<ConstantPointerNull>(Val))
  599. Val = Constant::getNullValue(DL.getIntPtrType(Val->getContext()));
  600. // If this is a store of a simple constant, fold the constant into the store.
  601. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
  602. unsigned Opc = 0;
  603. bool Signed = true;
  604. switch (VT.getSimpleVT().SimpleTy) {
  605. default: break;
  606. case MVT::i1:
  607. Signed = false;
  608. LLVM_FALLTHROUGH; // Handle as i8.
  609. case MVT::i8: Opc = X86::MOV8mi; break;
  610. case MVT::i16: Opc = X86::MOV16mi; break;
  611. case MVT::i32: Opc = X86::MOV32mi; break;
  612. case MVT::i64:
  613. // Must be a 32-bit sign extended value.
  614. if (isInt<32>(CI->getSExtValue()))
  615. Opc = X86::MOV64mi32;
  616. break;
  617. }
  618. if (Opc) {
  619. MachineInstrBuilder MIB =
  620. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc));
  621. addFullAddress(MIB, AM).addImm(Signed ? (uint64_t) CI->getSExtValue()
  622. : CI->getZExtValue());
  623. if (MMO)
  624. MIB->addMemOperand(*FuncInfo.MF, MMO);
  625. return true;
  626. }
  627. }
  628. Register ValReg = getRegForValue(Val);
  629. if (ValReg == 0)
  630. return false;
  631. return X86FastEmitStore(VT, ValReg, AM, MMO, Aligned);
  632. }
  633. /// X86FastEmitExtend - Emit a machine instruction to extend a value Src of
  634. /// type SrcVT to type DstVT using the specified extension opcode Opc (e.g.
  635. /// ISD::SIGN_EXTEND).
  636. bool X86FastISel::X86FastEmitExtend(ISD::NodeType Opc, EVT DstVT,
  637. unsigned Src, EVT SrcVT,
  638. unsigned &ResultReg) {
  639. unsigned RR = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc, Src);
  640. if (RR == 0)
  641. return false;
  642. ResultReg = RR;
  643. return true;
  644. }
  645. bool X86FastISel::handleConstantAddresses(const Value *V, X86AddressMode &AM) {
  646. // Handle constant address.
  647. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  648. // Can't handle alternate code models yet.
  649. if (TM.getCodeModel() != CodeModel::Small)
  650. return false;
  651. // Can't handle TLS yet.
  652. if (GV->isThreadLocal())
  653. return false;
  654. // Can't handle !absolute_symbol references yet.
  655. if (GV->isAbsoluteSymbolRef())
  656. return false;
  657. // RIP-relative addresses can't have additional register operands, so if
  658. // we've already folded stuff into the addressing mode, just force the
  659. // global value into its own register, which we can use as the basereg.
  660. if (!Subtarget->isPICStyleRIPRel() ||
  661. (AM.Base.Reg == 0 && AM.IndexReg == 0)) {
  662. // Okay, we've committed to selecting this global. Set up the address.
  663. AM.GV = GV;
  664. // Allow the subtarget to classify the global.
  665. unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
  666. // If this reference is relative to the pic base, set it now.
  667. if (isGlobalRelativeToPICBase(GVFlags)) {
  668. // FIXME: How do we know Base.Reg is free??
  669. AM.Base.Reg = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
  670. }
  671. // Unless the ABI requires an extra load, return a direct reference to
  672. // the global.
  673. if (!isGlobalStubReference(GVFlags)) {
  674. if (Subtarget->isPICStyleRIPRel()) {
  675. // Use rip-relative addressing if we can. Above we verified that the
  676. // base and index registers are unused.
  677. assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
  678. AM.Base.Reg = X86::RIP;
  679. }
  680. AM.GVOpFlags = GVFlags;
  681. return true;
  682. }
  683. // Ok, we need to do a load from a stub. If we've already loaded from
  684. // this stub, reuse the loaded pointer, otherwise emit the load now.
  685. DenseMap<const Value *, Register>::iterator I = LocalValueMap.find(V);
  686. Register LoadReg;
  687. if (I != LocalValueMap.end() && I->second) {
  688. LoadReg = I->second;
  689. } else {
  690. // Issue load from stub.
  691. unsigned Opc = 0;
  692. const TargetRegisterClass *RC = nullptr;
  693. X86AddressMode StubAM;
  694. StubAM.Base.Reg = AM.Base.Reg;
  695. StubAM.GV = GV;
  696. StubAM.GVOpFlags = GVFlags;
  697. // Prepare for inserting code in the local-value area.
  698. SavePoint SaveInsertPt = enterLocalValueArea();
  699. if (TLI.getPointerTy(DL) == MVT::i64) {
  700. Opc = X86::MOV64rm;
  701. RC = &X86::GR64RegClass;
  702. } else {
  703. Opc = X86::MOV32rm;
  704. RC = &X86::GR32RegClass;
  705. }
  706. if (Subtarget->isPICStyleRIPRel() || GVFlags == X86II::MO_GOTPCREL ||
  707. GVFlags == X86II::MO_GOTPCREL_NORELAX)
  708. StubAM.Base.Reg = X86::RIP;
  709. LoadReg = createResultReg(RC);
  710. MachineInstrBuilder LoadMI =
  711. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), LoadReg);
  712. addFullAddress(LoadMI, StubAM);
  713. // Ok, back to normal mode.
  714. leaveLocalValueArea(SaveInsertPt);
  715. // Prevent loading GV stub multiple times in same MBB.
  716. LocalValueMap[V] = LoadReg;
  717. }
  718. // Now construct the final address. Note that the Disp, Scale,
  719. // and Index values may already be set here.
  720. AM.Base.Reg = LoadReg;
  721. AM.GV = nullptr;
  722. return true;
  723. }
  724. }
  725. // If all else fails, try to materialize the value in a register.
  726. if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
  727. if (AM.Base.Reg == 0) {
  728. AM.Base.Reg = getRegForValue(V);
  729. return AM.Base.Reg != 0;
  730. }
  731. if (AM.IndexReg == 0) {
  732. assert(AM.Scale == 1 && "Scale with no index!");
  733. AM.IndexReg = getRegForValue(V);
  734. return AM.IndexReg != 0;
  735. }
  736. }
  737. return false;
  738. }
  739. /// X86SelectAddress - Attempt to fill in an address from the given value.
  740. ///
  741. bool X86FastISel::X86SelectAddress(const Value *V, X86AddressMode &AM) {
  742. SmallVector<const Value *, 32> GEPs;
  743. redo_gep:
  744. const User *U = nullptr;
  745. unsigned Opcode = Instruction::UserOp1;
  746. if (const Instruction *I = dyn_cast<Instruction>(V)) {
  747. // Don't walk into other basic blocks; it's possible we haven't
  748. // visited them yet, so the instructions may not yet be assigned
  749. // virtual registers.
  750. if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(V)) ||
  751. FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
  752. Opcode = I->getOpcode();
  753. U = I;
  754. }
  755. } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
  756. Opcode = C->getOpcode();
  757. U = C;
  758. }
  759. if (PointerType *Ty = dyn_cast<PointerType>(V->getType()))
  760. if (Ty->getAddressSpace() > 255)
  761. // Fast instruction selection doesn't support the special
  762. // address spaces.
  763. return false;
  764. switch (Opcode) {
  765. default: break;
  766. case Instruction::BitCast:
  767. // Look past bitcasts.
  768. return X86SelectAddress(U->getOperand(0), AM);
  769. case Instruction::IntToPtr:
  770. // Look past no-op inttoptrs.
  771. if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
  772. TLI.getPointerTy(DL))
  773. return X86SelectAddress(U->getOperand(0), AM);
  774. break;
  775. case Instruction::PtrToInt:
  776. // Look past no-op ptrtoints.
  777. if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
  778. return X86SelectAddress(U->getOperand(0), AM);
  779. break;
  780. case Instruction::Alloca: {
  781. // Do static allocas.
  782. const AllocaInst *A = cast<AllocaInst>(V);
  783. DenseMap<const AllocaInst *, int>::iterator SI =
  784. FuncInfo.StaticAllocaMap.find(A);
  785. if (SI != FuncInfo.StaticAllocaMap.end()) {
  786. AM.BaseType = X86AddressMode::FrameIndexBase;
  787. AM.Base.FrameIndex = SI->second;
  788. return true;
  789. }
  790. break;
  791. }
  792. case Instruction::Add: {
  793. // Adds of constants are common and easy enough.
  794. if (const ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
  795. uint64_t Disp = (int32_t)AM.Disp + (uint64_t)CI->getSExtValue();
  796. // They have to fit in the 32-bit signed displacement field though.
  797. if (isInt<32>(Disp)) {
  798. AM.Disp = (uint32_t)Disp;
  799. return X86SelectAddress(U->getOperand(0), AM);
  800. }
  801. }
  802. break;
  803. }
  804. case Instruction::GetElementPtr: {
  805. X86AddressMode SavedAM = AM;
  806. // Pattern-match simple GEPs.
  807. uint64_t Disp = (int32_t)AM.Disp;
  808. unsigned IndexReg = AM.IndexReg;
  809. unsigned Scale = AM.Scale;
  810. gep_type_iterator GTI = gep_type_begin(U);
  811. // Iterate through the indices, folding what we can. Constants can be
  812. // folded, and one dynamic index can be handled, if the scale is supported.
  813. for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
  814. i != e; ++i, ++GTI) {
  815. const Value *Op = *i;
  816. if (StructType *STy = GTI.getStructTypeOrNull()) {
  817. const StructLayout *SL = DL.getStructLayout(STy);
  818. Disp += SL->getElementOffset(cast<ConstantInt>(Op)->getZExtValue());
  819. continue;
  820. }
  821. // A array/variable index is always of the form i*S where S is the
  822. // constant scale size. See if we can push the scale into immediates.
  823. uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
  824. for (;;) {
  825. if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
  826. // Constant-offset addressing.
  827. Disp += CI->getSExtValue() * S;
  828. break;
  829. }
  830. if (canFoldAddIntoGEP(U, Op)) {
  831. // A compatible add with a constant operand. Fold the constant.
  832. ConstantInt *CI =
  833. cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
  834. Disp += CI->getSExtValue() * S;
  835. // Iterate on the other operand.
  836. Op = cast<AddOperator>(Op)->getOperand(0);
  837. continue;
  838. }
  839. if (IndexReg == 0 &&
  840. (!AM.GV || !Subtarget->isPICStyleRIPRel()) &&
  841. (S == 1 || S == 2 || S == 4 || S == 8)) {
  842. // Scaled-index addressing.
  843. Scale = S;
  844. IndexReg = getRegForGEPIndex(Op);
  845. if (IndexReg == 0)
  846. return false;
  847. break;
  848. }
  849. // Unsupported.
  850. goto unsupported_gep;
  851. }
  852. }
  853. // Check for displacement overflow.
  854. if (!isInt<32>(Disp))
  855. break;
  856. AM.IndexReg = IndexReg;
  857. AM.Scale = Scale;
  858. AM.Disp = (uint32_t)Disp;
  859. GEPs.push_back(V);
  860. if (const GetElementPtrInst *GEP =
  861. dyn_cast<GetElementPtrInst>(U->getOperand(0))) {
  862. // Ok, the GEP indices were covered by constant-offset and scaled-index
  863. // addressing. Update the address state and move on to examining the base.
  864. V = GEP;
  865. goto redo_gep;
  866. } else if (X86SelectAddress(U->getOperand(0), AM)) {
  867. return true;
  868. }
  869. // If we couldn't merge the gep value into this addr mode, revert back to
  870. // our address and just match the value instead of completely failing.
  871. AM = SavedAM;
  872. for (const Value *I : reverse(GEPs))
  873. if (handleConstantAddresses(I, AM))
  874. return true;
  875. return false;
  876. unsupported_gep:
  877. // Ok, the GEP indices weren't all covered.
  878. break;
  879. }
  880. }
  881. return handleConstantAddresses(V, AM);
  882. }
  883. /// X86SelectCallAddress - Attempt to fill in an address from the given value.
  884. ///
  885. bool X86FastISel::X86SelectCallAddress(const Value *V, X86AddressMode &AM) {
  886. const User *U = nullptr;
  887. unsigned Opcode = Instruction::UserOp1;
  888. const Instruction *I = dyn_cast<Instruction>(V);
  889. // Record if the value is defined in the same basic block.
  890. //
  891. // This information is crucial to know whether or not folding an
  892. // operand is valid.
  893. // Indeed, FastISel generates or reuses a virtual register for all
  894. // operands of all instructions it selects. Obviously, the definition and
  895. // its uses must use the same virtual register otherwise the produced
  896. // code is incorrect.
  897. // Before instruction selection, FunctionLoweringInfo::set sets the virtual
  898. // registers for values that are alive across basic blocks. This ensures
  899. // that the values are consistently set between across basic block, even
  900. // if different instruction selection mechanisms are used (e.g., a mix of
  901. // SDISel and FastISel).
  902. // For values local to a basic block, the instruction selection process
  903. // generates these virtual registers with whatever method is appropriate
  904. // for its needs. In particular, FastISel and SDISel do not share the way
  905. // local virtual registers are set.
  906. // Therefore, this is impossible (or at least unsafe) to share values
  907. // between basic blocks unless they use the same instruction selection
  908. // method, which is not guarantee for X86.
  909. // Moreover, things like hasOneUse could not be used accurately, if we
  910. // allow to reference values across basic blocks whereas they are not
  911. // alive across basic blocks initially.
  912. bool InMBB = true;
  913. if (I) {
  914. Opcode = I->getOpcode();
  915. U = I;
  916. InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
  917. } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(V)) {
  918. Opcode = C->getOpcode();
  919. U = C;
  920. }
  921. switch (Opcode) {
  922. default: break;
  923. case Instruction::BitCast:
  924. // Look past bitcasts if its operand is in the same BB.
  925. if (InMBB)
  926. return X86SelectCallAddress(U->getOperand(0), AM);
  927. break;
  928. case Instruction::IntToPtr:
  929. // Look past no-op inttoptrs if its operand is in the same BB.
  930. if (InMBB &&
  931. TLI.getValueType(DL, U->getOperand(0)->getType()) ==
  932. TLI.getPointerTy(DL))
  933. return X86SelectCallAddress(U->getOperand(0), AM);
  934. break;
  935. case Instruction::PtrToInt:
  936. // Look past no-op ptrtoints if its operand is in the same BB.
  937. if (InMBB && TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
  938. return X86SelectCallAddress(U->getOperand(0), AM);
  939. break;
  940. }
  941. // Handle constant address.
  942. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  943. // Can't handle alternate code models yet.
  944. if (TM.getCodeModel() != CodeModel::Small)
  945. return false;
  946. // RIP-relative addresses can't have additional register operands.
  947. if (Subtarget->isPICStyleRIPRel() &&
  948. (AM.Base.Reg != 0 || AM.IndexReg != 0))
  949. return false;
  950. // Can't handle TLS.
  951. if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
  952. if (GVar->isThreadLocal())
  953. return false;
  954. // Okay, we've committed to selecting this global. Set up the basic address.
  955. AM.GV = GV;
  956. // Return a direct reference to the global. Fastisel can handle calls to
  957. // functions that require loads, such as dllimport and nonlazybind
  958. // functions.
  959. if (Subtarget->isPICStyleRIPRel()) {
  960. // Use rip-relative addressing if we can. Above we verified that the
  961. // base and index registers are unused.
  962. assert(AM.Base.Reg == 0 && AM.IndexReg == 0);
  963. AM.Base.Reg = X86::RIP;
  964. } else {
  965. AM.GVOpFlags = Subtarget->classifyLocalReference(nullptr);
  966. }
  967. return true;
  968. }
  969. // If all else fails, try to materialize the value in a register.
  970. if (!AM.GV || !Subtarget->isPICStyleRIPRel()) {
  971. auto GetCallRegForValue = [this](const Value *V) {
  972. Register Reg = getRegForValue(V);
  973. // In 64-bit mode, we need a 64-bit register even if pointers are 32 bits.
  974. if (Reg && Subtarget->isTarget64BitILP32()) {
  975. Register CopyReg = createResultReg(&X86::GR32RegClass);
  976. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32rr),
  977. CopyReg)
  978. .addReg(Reg);
  979. Register ExtReg = createResultReg(&X86::GR64RegClass);
  980. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  981. TII.get(TargetOpcode::SUBREG_TO_REG), ExtReg)
  982. .addImm(0)
  983. .addReg(CopyReg)
  984. .addImm(X86::sub_32bit);
  985. Reg = ExtReg;
  986. }
  987. return Reg;
  988. };
  989. if (AM.Base.Reg == 0) {
  990. AM.Base.Reg = GetCallRegForValue(V);
  991. return AM.Base.Reg != 0;
  992. }
  993. if (AM.IndexReg == 0) {
  994. assert(AM.Scale == 1 && "Scale with no index!");
  995. AM.IndexReg = GetCallRegForValue(V);
  996. return AM.IndexReg != 0;
  997. }
  998. }
  999. return false;
  1000. }
  1001. /// X86SelectStore - Select and emit code to implement store instructions.
  1002. bool X86FastISel::X86SelectStore(const Instruction *I) {
  1003. // Atomic stores need special handling.
  1004. const StoreInst *S = cast<StoreInst>(I);
  1005. if (S->isAtomic())
  1006. return false;
  1007. const Value *PtrV = I->getOperand(1);
  1008. if (TLI.supportSwiftError()) {
  1009. // Swifterror values can come from either a function parameter with
  1010. // swifterror attribute or an alloca with swifterror attribute.
  1011. if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
  1012. if (Arg->hasSwiftErrorAttr())
  1013. return false;
  1014. }
  1015. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
  1016. if (Alloca->isSwiftError())
  1017. return false;
  1018. }
  1019. }
  1020. const Value *Val = S->getValueOperand();
  1021. const Value *Ptr = S->getPointerOperand();
  1022. MVT VT;
  1023. if (!isTypeLegal(Val->getType(), VT, /*AllowI1=*/true))
  1024. return false;
  1025. Align Alignment = S->getAlign();
  1026. Align ABIAlignment = DL.getABITypeAlign(Val->getType());
  1027. bool Aligned = Alignment >= ABIAlignment;
  1028. X86AddressMode AM;
  1029. if (!X86SelectAddress(Ptr, AM))
  1030. return false;
  1031. return X86FastEmitStore(VT, Val, AM, createMachineMemOperandFor(I), Aligned);
  1032. }
  1033. /// X86SelectRet - Select and emit code to implement ret instructions.
  1034. bool X86FastISel::X86SelectRet(const Instruction *I) {
  1035. const ReturnInst *Ret = cast<ReturnInst>(I);
  1036. const Function &F = *I->getParent()->getParent();
  1037. const X86MachineFunctionInfo *X86MFInfo =
  1038. FuncInfo.MF->getInfo<X86MachineFunctionInfo>();
  1039. if (!FuncInfo.CanLowerReturn)
  1040. return false;
  1041. if (TLI.supportSwiftError() &&
  1042. F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
  1043. return false;
  1044. if (TLI.supportSplitCSR(FuncInfo.MF))
  1045. return false;
  1046. CallingConv::ID CC = F.getCallingConv();
  1047. if (CC != CallingConv::C &&
  1048. CC != CallingConv::Fast &&
  1049. CC != CallingConv::Tail &&
  1050. CC != CallingConv::SwiftTail &&
  1051. CC != CallingConv::X86_FastCall &&
  1052. CC != CallingConv::X86_StdCall &&
  1053. CC != CallingConv::X86_ThisCall &&
  1054. CC != CallingConv::X86_64_SysV &&
  1055. CC != CallingConv::Win64)
  1056. return false;
  1057. // Don't handle popping bytes if they don't fit the ret's immediate.
  1058. if (!isUInt<16>(X86MFInfo->getBytesToPopOnReturn()))
  1059. return false;
  1060. // fastcc with -tailcallopt is intended to provide a guaranteed
  1061. // tail call optimization. Fastisel doesn't know how to do that.
  1062. if ((CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) ||
  1063. CC == CallingConv::Tail || CC == CallingConv::SwiftTail)
  1064. return false;
  1065. // Let SDISel handle vararg functions.
  1066. if (F.isVarArg())
  1067. return false;
  1068. // Build a list of return value registers.
  1069. SmallVector<unsigned, 4> RetRegs;
  1070. if (Ret->getNumOperands() > 0) {
  1071. SmallVector<ISD::OutputArg, 4> Outs;
  1072. GetReturnInfo(CC, F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
  1073. // Analyze operands of the call, assigning locations to each operand.
  1074. SmallVector<CCValAssign, 16> ValLocs;
  1075. CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
  1076. CCInfo.AnalyzeReturn(Outs, RetCC_X86);
  1077. const Value *RV = Ret->getOperand(0);
  1078. Register Reg = getRegForValue(RV);
  1079. if (Reg == 0)
  1080. return false;
  1081. // Only handle a single return value for now.
  1082. if (ValLocs.size() != 1)
  1083. return false;
  1084. CCValAssign &VA = ValLocs[0];
  1085. // Don't bother handling odd stuff for now.
  1086. if (VA.getLocInfo() != CCValAssign::Full)
  1087. return false;
  1088. // Only handle register returns for now.
  1089. if (!VA.isRegLoc())
  1090. return false;
  1091. // The calling-convention tables for x87 returns don't tell
  1092. // the whole story.
  1093. if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
  1094. return false;
  1095. unsigned SrcReg = Reg + VA.getValNo();
  1096. EVT SrcVT = TLI.getValueType(DL, RV->getType());
  1097. EVT DstVT = VA.getValVT();
  1098. // Special handling for extended integers.
  1099. if (SrcVT != DstVT) {
  1100. if (SrcVT != MVT::i1 && SrcVT != MVT::i8 && SrcVT != MVT::i16)
  1101. return false;
  1102. if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
  1103. return false;
  1104. assert(DstVT == MVT::i32 && "X86 should always ext to i32");
  1105. if (SrcVT == MVT::i1) {
  1106. if (Outs[0].Flags.isSExt())
  1107. return false;
  1108. // TODO
  1109. SrcReg = fastEmitZExtFromI1(MVT::i8, SrcReg);
  1110. SrcVT = MVT::i8;
  1111. }
  1112. unsigned Op = Outs[0].Flags.isZExt() ? ISD::ZERO_EXTEND :
  1113. ISD::SIGN_EXTEND;
  1114. // TODO
  1115. SrcReg = fastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Op, SrcReg);
  1116. }
  1117. // Make the copy.
  1118. Register DstReg = VA.getLocReg();
  1119. const TargetRegisterClass *SrcRC = MRI.getRegClass(SrcReg);
  1120. // Avoid a cross-class copy. This is very unlikely.
  1121. if (!SrcRC->contains(DstReg))
  1122. return false;
  1123. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1124. TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
  1125. // Add register to return instruction.
  1126. RetRegs.push_back(VA.getLocReg());
  1127. }
  1128. // Swift calling convention does not require we copy the sret argument
  1129. // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
  1130. // All x86 ABIs require that for returning structs by value we copy
  1131. // the sret argument into %rax/%eax (depending on ABI) for the return.
  1132. // We saved the argument into a virtual register in the entry block,
  1133. // so now we copy the value out and into %rax/%eax.
  1134. if (F.hasStructRetAttr() && CC != CallingConv::Swift &&
  1135. CC != CallingConv::SwiftTail) {
  1136. Register Reg = X86MFInfo->getSRetReturnReg();
  1137. assert(Reg &&
  1138. "SRetReturnReg should have been set in LowerFormalArguments()!");
  1139. unsigned RetReg = Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX;
  1140. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1141. TII.get(TargetOpcode::COPY), RetReg).addReg(Reg);
  1142. RetRegs.push_back(RetReg);
  1143. }
  1144. // Now emit the RET.
  1145. MachineInstrBuilder MIB;
  1146. if (X86MFInfo->getBytesToPopOnReturn()) {
  1147. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1148. TII.get(Subtarget->is64Bit() ? X86::RETI64 : X86::RETI32))
  1149. .addImm(X86MFInfo->getBytesToPopOnReturn());
  1150. } else {
  1151. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1152. TII.get(Subtarget->is64Bit() ? X86::RET64 : X86::RET32));
  1153. }
  1154. for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
  1155. MIB.addReg(RetRegs[i], RegState::Implicit);
  1156. return true;
  1157. }
  1158. /// X86SelectLoad - Select and emit code to implement load instructions.
  1159. ///
  1160. bool X86FastISel::X86SelectLoad(const Instruction *I) {
  1161. const LoadInst *LI = cast<LoadInst>(I);
  1162. // Atomic loads need special handling.
  1163. if (LI->isAtomic())
  1164. return false;
  1165. const Value *SV = I->getOperand(0);
  1166. if (TLI.supportSwiftError()) {
  1167. // Swifterror values can come from either a function parameter with
  1168. // swifterror attribute or an alloca with swifterror attribute.
  1169. if (const Argument *Arg = dyn_cast<Argument>(SV)) {
  1170. if (Arg->hasSwiftErrorAttr())
  1171. return false;
  1172. }
  1173. if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
  1174. if (Alloca->isSwiftError())
  1175. return false;
  1176. }
  1177. }
  1178. MVT VT;
  1179. if (!isTypeLegal(LI->getType(), VT, /*AllowI1=*/true))
  1180. return false;
  1181. const Value *Ptr = LI->getPointerOperand();
  1182. X86AddressMode AM;
  1183. if (!X86SelectAddress(Ptr, AM))
  1184. return false;
  1185. unsigned ResultReg = 0;
  1186. if (!X86FastEmitLoad(VT, AM, createMachineMemOperandFor(LI), ResultReg,
  1187. LI->getAlign().value()))
  1188. return false;
  1189. updateValueMap(I, ResultReg);
  1190. return true;
  1191. }
  1192. static unsigned X86ChooseCmpOpcode(EVT VT, const X86Subtarget *Subtarget) {
  1193. bool HasAVX512 = Subtarget->hasAVX512();
  1194. bool HasAVX = Subtarget->hasAVX();
  1195. bool X86ScalarSSEf32 = Subtarget->hasSSE1();
  1196. bool X86ScalarSSEf64 = Subtarget->hasSSE2();
  1197. switch (VT.getSimpleVT().SimpleTy) {
  1198. default: return 0;
  1199. case MVT::i8: return X86::CMP8rr;
  1200. case MVT::i16: return X86::CMP16rr;
  1201. case MVT::i32: return X86::CMP32rr;
  1202. case MVT::i64: return X86::CMP64rr;
  1203. case MVT::f32:
  1204. return X86ScalarSSEf32
  1205. ? (HasAVX512 ? X86::VUCOMISSZrr
  1206. : HasAVX ? X86::VUCOMISSrr : X86::UCOMISSrr)
  1207. : 0;
  1208. case MVT::f64:
  1209. return X86ScalarSSEf64
  1210. ? (HasAVX512 ? X86::VUCOMISDZrr
  1211. : HasAVX ? X86::VUCOMISDrr : X86::UCOMISDrr)
  1212. : 0;
  1213. }
  1214. }
  1215. /// If we have a comparison with RHS as the RHS of the comparison, return an
  1216. /// opcode that works for the compare (e.g. CMP32ri) otherwise return 0.
  1217. static unsigned X86ChooseCmpImmediateOpcode(EVT VT, const ConstantInt *RHSC) {
  1218. int64_t Val = RHSC->getSExtValue();
  1219. switch (VT.getSimpleVT().SimpleTy) {
  1220. // Otherwise, we can't fold the immediate into this comparison.
  1221. default:
  1222. return 0;
  1223. case MVT::i8:
  1224. return X86::CMP8ri;
  1225. case MVT::i16:
  1226. if (isInt<8>(Val))
  1227. return X86::CMP16ri8;
  1228. return X86::CMP16ri;
  1229. case MVT::i32:
  1230. if (isInt<8>(Val))
  1231. return X86::CMP32ri8;
  1232. return X86::CMP32ri;
  1233. case MVT::i64:
  1234. if (isInt<8>(Val))
  1235. return X86::CMP64ri8;
  1236. // 64-bit comparisons are only valid if the immediate fits in a 32-bit sext
  1237. // field.
  1238. if (isInt<32>(Val))
  1239. return X86::CMP64ri32;
  1240. return 0;
  1241. }
  1242. }
  1243. bool X86FastISel::X86FastEmitCompare(const Value *Op0, const Value *Op1, EVT VT,
  1244. const DebugLoc &CurDbgLoc) {
  1245. Register Op0Reg = getRegForValue(Op0);
  1246. if (Op0Reg == 0) return false;
  1247. // Handle 'null' like i32/i64 0.
  1248. if (isa<ConstantPointerNull>(Op1))
  1249. Op1 = Constant::getNullValue(DL.getIntPtrType(Op0->getContext()));
  1250. // We have two options: compare with register or immediate. If the RHS of
  1251. // the compare is an immediate that we can fold into this compare, use
  1252. // CMPri, otherwise use CMPrr.
  1253. if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
  1254. if (unsigned CompareImmOpc = X86ChooseCmpImmediateOpcode(VT, Op1C)) {
  1255. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareImmOpc))
  1256. .addReg(Op0Reg)
  1257. .addImm(Op1C->getSExtValue());
  1258. return true;
  1259. }
  1260. }
  1261. unsigned CompareOpc = X86ChooseCmpOpcode(VT, Subtarget);
  1262. if (CompareOpc == 0) return false;
  1263. Register Op1Reg = getRegForValue(Op1);
  1264. if (Op1Reg == 0) return false;
  1265. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, CurDbgLoc, TII.get(CompareOpc))
  1266. .addReg(Op0Reg)
  1267. .addReg(Op1Reg);
  1268. return true;
  1269. }
  1270. bool X86FastISel::X86SelectCmp(const Instruction *I) {
  1271. const CmpInst *CI = cast<CmpInst>(I);
  1272. MVT VT;
  1273. if (!isTypeLegal(I->getOperand(0)->getType(), VT))
  1274. return false;
  1275. // Below code only works for scalars.
  1276. if (VT.isVector())
  1277. return false;
  1278. // Try to optimize or fold the cmp.
  1279. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  1280. unsigned ResultReg = 0;
  1281. switch (Predicate) {
  1282. default: break;
  1283. case CmpInst::FCMP_FALSE: {
  1284. ResultReg = createResultReg(&X86::GR32RegClass);
  1285. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV32r0),
  1286. ResultReg);
  1287. ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultReg, X86::sub_8bit);
  1288. if (!ResultReg)
  1289. return false;
  1290. break;
  1291. }
  1292. case CmpInst::FCMP_TRUE: {
  1293. ResultReg = createResultReg(&X86::GR8RegClass);
  1294. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
  1295. ResultReg).addImm(1);
  1296. break;
  1297. }
  1298. }
  1299. if (ResultReg) {
  1300. updateValueMap(I, ResultReg);
  1301. return true;
  1302. }
  1303. const Value *LHS = CI->getOperand(0);
  1304. const Value *RHS = CI->getOperand(1);
  1305. // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
  1306. // We don't have to materialize a zero constant for this case and can just use
  1307. // %x again on the RHS.
  1308. if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
  1309. const auto *RHSC = dyn_cast<ConstantFP>(RHS);
  1310. if (RHSC && RHSC->isNullValue())
  1311. RHS = LHS;
  1312. }
  1313. // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
  1314. static const uint16_t SETFOpcTable[2][3] = {
  1315. { X86::COND_E, X86::COND_NP, X86::AND8rr },
  1316. { X86::COND_NE, X86::COND_P, X86::OR8rr }
  1317. };
  1318. const uint16_t *SETFOpc = nullptr;
  1319. switch (Predicate) {
  1320. default: break;
  1321. case CmpInst::FCMP_OEQ: SETFOpc = &SETFOpcTable[0][0]; break;
  1322. case CmpInst::FCMP_UNE: SETFOpc = &SETFOpcTable[1][0]; break;
  1323. }
  1324. ResultReg = createResultReg(&X86::GR8RegClass);
  1325. if (SETFOpc) {
  1326. if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
  1327. return false;
  1328. Register FlagReg1 = createResultReg(&X86::GR8RegClass);
  1329. Register FlagReg2 = createResultReg(&X86::GR8RegClass);
  1330. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr),
  1331. FlagReg1).addImm(SETFOpc[0]);
  1332. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr),
  1333. FlagReg2).addImm(SETFOpc[1]);
  1334. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(SETFOpc[2]),
  1335. ResultReg).addReg(FlagReg1).addReg(FlagReg2);
  1336. updateValueMap(I, ResultReg);
  1337. return true;
  1338. }
  1339. X86::CondCode CC;
  1340. bool SwapArgs;
  1341. std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
  1342. assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
  1343. if (SwapArgs)
  1344. std::swap(LHS, RHS);
  1345. // Emit a compare of LHS/RHS.
  1346. if (!X86FastEmitCompare(LHS, RHS, VT, I->getDebugLoc()))
  1347. return false;
  1348. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr),
  1349. ResultReg).addImm(CC);
  1350. updateValueMap(I, ResultReg);
  1351. return true;
  1352. }
  1353. bool X86FastISel::X86SelectZExt(const Instruction *I) {
  1354. EVT DstVT = TLI.getValueType(DL, I->getType());
  1355. if (!TLI.isTypeLegal(DstVT))
  1356. return false;
  1357. Register ResultReg = getRegForValue(I->getOperand(0));
  1358. if (ResultReg == 0)
  1359. return false;
  1360. // Handle zero-extension from i1 to i8, which is common.
  1361. MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
  1362. if (SrcVT == MVT::i1) {
  1363. // Set the high bits to zero.
  1364. ResultReg = fastEmitZExtFromI1(MVT::i8, ResultReg);
  1365. SrcVT = MVT::i8;
  1366. if (ResultReg == 0)
  1367. return false;
  1368. }
  1369. if (DstVT == MVT::i64) {
  1370. // Handle extension to 64-bits via sub-register shenanigans.
  1371. unsigned MovInst;
  1372. switch (SrcVT.SimpleTy) {
  1373. case MVT::i8: MovInst = X86::MOVZX32rr8; break;
  1374. case MVT::i16: MovInst = X86::MOVZX32rr16; break;
  1375. case MVT::i32: MovInst = X86::MOV32rr; break;
  1376. default: llvm_unreachable("Unexpected zext to i64 source type");
  1377. }
  1378. Register Result32 = createResultReg(&X86::GR32RegClass);
  1379. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovInst), Result32)
  1380. .addReg(ResultReg);
  1381. ResultReg = createResultReg(&X86::GR64RegClass);
  1382. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::SUBREG_TO_REG),
  1383. ResultReg)
  1384. .addImm(0).addReg(Result32).addImm(X86::sub_32bit);
  1385. } else if (DstVT == MVT::i16) {
  1386. // i8->i16 doesn't exist in the autogenerated isel table. Need to zero
  1387. // extend to 32-bits and then extract down to 16-bits.
  1388. Register Result32 = createResultReg(&X86::GR32RegClass);
  1389. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOVZX32rr8),
  1390. Result32).addReg(ResultReg);
  1391. ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, X86::sub_16bit);
  1392. } else if (DstVT != MVT::i8) {
  1393. ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::ZERO_EXTEND,
  1394. ResultReg);
  1395. if (ResultReg == 0)
  1396. return false;
  1397. }
  1398. updateValueMap(I, ResultReg);
  1399. return true;
  1400. }
  1401. bool X86FastISel::X86SelectSExt(const Instruction *I) {
  1402. EVT DstVT = TLI.getValueType(DL, I->getType());
  1403. if (!TLI.isTypeLegal(DstVT))
  1404. return false;
  1405. Register ResultReg = getRegForValue(I->getOperand(0));
  1406. if (ResultReg == 0)
  1407. return false;
  1408. // Handle sign-extension from i1 to i8.
  1409. MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
  1410. if (SrcVT == MVT::i1) {
  1411. // Set the high bits to zero.
  1412. Register ZExtReg = fastEmitZExtFromI1(MVT::i8, ResultReg);
  1413. if (ZExtReg == 0)
  1414. return false;
  1415. // Negate the result to make an 8-bit sign extended value.
  1416. ResultReg = createResultReg(&X86::GR8RegClass);
  1417. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::NEG8r),
  1418. ResultReg).addReg(ZExtReg);
  1419. SrcVT = MVT::i8;
  1420. }
  1421. if (DstVT == MVT::i16) {
  1422. // i8->i16 doesn't exist in the autogenerated isel table. Need to sign
  1423. // extend to 32-bits and then extract down to 16-bits.
  1424. Register Result32 = createResultReg(&X86::GR32RegClass);
  1425. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOVSX32rr8),
  1426. Result32).addReg(ResultReg);
  1427. ResultReg = fastEmitInst_extractsubreg(MVT::i16, Result32, X86::sub_16bit);
  1428. } else if (DstVT != MVT::i8) {
  1429. ResultReg = fastEmit_r(MVT::i8, DstVT.getSimpleVT(), ISD::SIGN_EXTEND,
  1430. ResultReg);
  1431. if (ResultReg == 0)
  1432. return false;
  1433. }
  1434. updateValueMap(I, ResultReg);
  1435. return true;
  1436. }
  1437. bool X86FastISel::X86SelectBranch(const Instruction *I) {
  1438. // Unconditional branches are selected by tablegen-generated code.
  1439. // Handle a conditional branch.
  1440. const BranchInst *BI = cast<BranchInst>(I);
  1441. MachineBasicBlock *TrueMBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
  1442. MachineBasicBlock *FalseMBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
  1443. // Fold the common case of a conditional branch with a comparison
  1444. // in the same block (values defined on other blocks may not have
  1445. // initialized registers).
  1446. X86::CondCode CC;
  1447. if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
  1448. if (CI->hasOneUse() && CI->getParent() == I->getParent()) {
  1449. EVT VT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  1450. // Try to optimize or fold the cmp.
  1451. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  1452. switch (Predicate) {
  1453. default: break;
  1454. case CmpInst::FCMP_FALSE: fastEmitBranch(FalseMBB, DbgLoc); return true;
  1455. case CmpInst::FCMP_TRUE: fastEmitBranch(TrueMBB, DbgLoc); return true;
  1456. }
  1457. const Value *CmpLHS = CI->getOperand(0);
  1458. const Value *CmpRHS = CI->getOperand(1);
  1459. // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x,
  1460. // 0.0.
  1461. // We don't have to materialize a zero constant for this case and can just
  1462. // use %x again on the RHS.
  1463. if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
  1464. const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
  1465. if (CmpRHSC && CmpRHSC->isNullValue())
  1466. CmpRHS = CmpLHS;
  1467. }
  1468. // Try to take advantage of fallthrough opportunities.
  1469. if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
  1470. std::swap(TrueMBB, FalseMBB);
  1471. Predicate = CmpInst::getInversePredicate(Predicate);
  1472. }
  1473. // FCMP_OEQ and FCMP_UNE cannot be expressed with a single flag/condition
  1474. // code check. Instead two branch instructions are required to check all
  1475. // the flags. First we change the predicate to a supported condition code,
  1476. // which will be the first branch. Later one we will emit the second
  1477. // branch.
  1478. bool NeedExtraBranch = false;
  1479. switch (Predicate) {
  1480. default: break;
  1481. case CmpInst::FCMP_OEQ:
  1482. std::swap(TrueMBB, FalseMBB);
  1483. LLVM_FALLTHROUGH;
  1484. case CmpInst::FCMP_UNE:
  1485. NeedExtraBranch = true;
  1486. Predicate = CmpInst::FCMP_ONE;
  1487. break;
  1488. }
  1489. bool SwapArgs;
  1490. std::tie(CC, SwapArgs) = X86::getX86ConditionCode(Predicate);
  1491. assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
  1492. if (SwapArgs)
  1493. std::swap(CmpLHS, CmpRHS);
  1494. // Emit a compare of the LHS and RHS, setting the flags.
  1495. if (!X86FastEmitCompare(CmpLHS, CmpRHS, VT, CI->getDebugLoc()))
  1496. return false;
  1497. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1))
  1498. .addMBB(TrueMBB).addImm(CC);
  1499. // X86 requires a second branch to handle UNE (and OEQ, which is mapped
  1500. // to UNE above).
  1501. if (NeedExtraBranch) {
  1502. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1))
  1503. .addMBB(TrueMBB).addImm(X86::COND_P);
  1504. }
  1505. finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
  1506. return true;
  1507. }
  1508. } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
  1509. // Handle things like "%cond = trunc i32 %X to i1 / br i1 %cond", which
  1510. // typically happen for _Bool and C++ bools.
  1511. MVT SourceVT;
  1512. if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
  1513. isTypeLegal(TI->getOperand(0)->getType(), SourceVT)) {
  1514. unsigned TestOpc = 0;
  1515. switch (SourceVT.SimpleTy) {
  1516. default: break;
  1517. case MVT::i8: TestOpc = X86::TEST8ri; break;
  1518. case MVT::i16: TestOpc = X86::TEST16ri; break;
  1519. case MVT::i32: TestOpc = X86::TEST32ri; break;
  1520. case MVT::i64: TestOpc = X86::TEST64ri32; break;
  1521. }
  1522. if (TestOpc) {
  1523. Register OpReg = getRegForValue(TI->getOperand(0));
  1524. if (OpReg == 0) return false;
  1525. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TestOpc))
  1526. .addReg(OpReg).addImm(1);
  1527. unsigned JmpCond = X86::COND_NE;
  1528. if (FuncInfo.MBB->isLayoutSuccessor(TrueMBB)) {
  1529. std::swap(TrueMBB, FalseMBB);
  1530. JmpCond = X86::COND_E;
  1531. }
  1532. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1))
  1533. .addMBB(TrueMBB).addImm(JmpCond);
  1534. finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
  1535. return true;
  1536. }
  1537. }
  1538. } else if (foldX86XALUIntrinsic(CC, BI, BI->getCondition())) {
  1539. // Fake request the condition, otherwise the intrinsic might be completely
  1540. // optimized away.
  1541. Register TmpReg = getRegForValue(BI->getCondition());
  1542. if (TmpReg == 0)
  1543. return false;
  1544. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1))
  1545. .addMBB(TrueMBB).addImm(CC);
  1546. finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
  1547. return true;
  1548. }
  1549. // Otherwise do a clumsy setcc and re-test it.
  1550. // Note that i1 essentially gets ANY_EXTEND'ed to i8 where it isn't used
  1551. // in an explicit cast, so make sure to handle that correctly.
  1552. Register OpReg = getRegForValue(BI->getCondition());
  1553. if (OpReg == 0) return false;
  1554. // In case OpReg is a K register, COPY to a GPR
  1555. if (MRI.getRegClass(OpReg) == &X86::VK1RegClass) {
  1556. unsigned KOpReg = OpReg;
  1557. OpReg = createResultReg(&X86::GR32RegClass);
  1558. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1559. TII.get(TargetOpcode::COPY), OpReg)
  1560. .addReg(KOpReg);
  1561. OpReg = fastEmitInst_extractsubreg(MVT::i8, OpReg, X86::sub_8bit);
  1562. }
  1563. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
  1564. .addReg(OpReg)
  1565. .addImm(1);
  1566. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::JCC_1))
  1567. .addMBB(TrueMBB).addImm(X86::COND_NE);
  1568. finishCondBranch(BI->getParent(), TrueMBB, FalseMBB);
  1569. return true;
  1570. }
  1571. bool X86FastISel::X86SelectShift(const Instruction *I) {
  1572. unsigned CReg = 0, OpReg = 0;
  1573. const TargetRegisterClass *RC = nullptr;
  1574. if (I->getType()->isIntegerTy(8)) {
  1575. CReg = X86::CL;
  1576. RC = &X86::GR8RegClass;
  1577. switch (I->getOpcode()) {
  1578. case Instruction::LShr: OpReg = X86::SHR8rCL; break;
  1579. case Instruction::AShr: OpReg = X86::SAR8rCL; break;
  1580. case Instruction::Shl: OpReg = X86::SHL8rCL; break;
  1581. default: return false;
  1582. }
  1583. } else if (I->getType()->isIntegerTy(16)) {
  1584. CReg = X86::CX;
  1585. RC = &X86::GR16RegClass;
  1586. switch (I->getOpcode()) {
  1587. default: llvm_unreachable("Unexpected shift opcode");
  1588. case Instruction::LShr: OpReg = X86::SHR16rCL; break;
  1589. case Instruction::AShr: OpReg = X86::SAR16rCL; break;
  1590. case Instruction::Shl: OpReg = X86::SHL16rCL; break;
  1591. }
  1592. } else if (I->getType()->isIntegerTy(32)) {
  1593. CReg = X86::ECX;
  1594. RC = &X86::GR32RegClass;
  1595. switch (I->getOpcode()) {
  1596. default: llvm_unreachable("Unexpected shift opcode");
  1597. case Instruction::LShr: OpReg = X86::SHR32rCL; break;
  1598. case Instruction::AShr: OpReg = X86::SAR32rCL; break;
  1599. case Instruction::Shl: OpReg = X86::SHL32rCL; break;
  1600. }
  1601. } else if (I->getType()->isIntegerTy(64)) {
  1602. CReg = X86::RCX;
  1603. RC = &X86::GR64RegClass;
  1604. switch (I->getOpcode()) {
  1605. default: llvm_unreachable("Unexpected shift opcode");
  1606. case Instruction::LShr: OpReg = X86::SHR64rCL; break;
  1607. case Instruction::AShr: OpReg = X86::SAR64rCL; break;
  1608. case Instruction::Shl: OpReg = X86::SHL64rCL; break;
  1609. }
  1610. } else {
  1611. return false;
  1612. }
  1613. MVT VT;
  1614. if (!isTypeLegal(I->getType(), VT))
  1615. return false;
  1616. Register Op0Reg = getRegForValue(I->getOperand(0));
  1617. if (Op0Reg == 0) return false;
  1618. Register Op1Reg = getRegForValue(I->getOperand(1));
  1619. if (Op1Reg == 0) return false;
  1620. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
  1621. CReg).addReg(Op1Reg);
  1622. // The shift instruction uses X86::CL. If we defined a super-register
  1623. // of X86::CL, emit a subreg KILL to precisely describe what we're doing here.
  1624. if (CReg != X86::CL)
  1625. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1626. TII.get(TargetOpcode::KILL), X86::CL)
  1627. .addReg(CReg, RegState::Kill);
  1628. Register ResultReg = createResultReg(RC);
  1629. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(OpReg), ResultReg)
  1630. .addReg(Op0Reg);
  1631. updateValueMap(I, ResultReg);
  1632. return true;
  1633. }
  1634. bool X86FastISel::X86SelectDivRem(const Instruction *I) {
  1635. const static unsigned NumTypes = 4; // i8, i16, i32, i64
  1636. const static unsigned NumOps = 4; // SDiv, SRem, UDiv, URem
  1637. const static bool S = true; // IsSigned
  1638. const static bool U = false; // !IsSigned
  1639. const static unsigned Copy = TargetOpcode::COPY;
  1640. // For the X86 DIV/IDIV instruction, in most cases the dividend
  1641. // (numerator) must be in a specific register pair highreg:lowreg,
  1642. // producing the quotient in lowreg and the remainder in highreg.
  1643. // For most data types, to set up the instruction, the dividend is
  1644. // copied into lowreg, and lowreg is sign-extended or zero-extended
  1645. // into highreg. The exception is i8, where the dividend is defined
  1646. // as a single register rather than a register pair, and we
  1647. // therefore directly sign-extend or zero-extend the dividend into
  1648. // lowreg, instead of copying, and ignore the highreg.
  1649. const static struct DivRemEntry {
  1650. // The following portion depends only on the data type.
  1651. const TargetRegisterClass *RC;
  1652. unsigned LowInReg; // low part of the register pair
  1653. unsigned HighInReg; // high part of the register pair
  1654. // The following portion depends on both the data type and the operation.
  1655. struct DivRemResult {
  1656. unsigned OpDivRem; // The specific DIV/IDIV opcode to use.
  1657. unsigned OpSignExtend; // Opcode for sign-extending lowreg into
  1658. // highreg, or copying a zero into highreg.
  1659. unsigned OpCopy; // Opcode for copying dividend into lowreg, or
  1660. // zero/sign-extending into lowreg for i8.
  1661. unsigned DivRemResultReg; // Register containing the desired result.
  1662. bool IsOpSigned; // Whether to use signed or unsigned form.
  1663. } ResultTable[NumOps];
  1664. } OpTable[NumTypes] = {
  1665. { &X86::GR8RegClass, X86::AX, 0, {
  1666. { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AL, S }, // SDiv
  1667. { X86::IDIV8r, 0, X86::MOVSX16rr8, X86::AH, S }, // SRem
  1668. { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AL, U }, // UDiv
  1669. { X86::DIV8r, 0, X86::MOVZX16rr8, X86::AH, U }, // URem
  1670. }
  1671. }, // i8
  1672. { &X86::GR16RegClass, X86::AX, X86::DX, {
  1673. { X86::IDIV16r, X86::CWD, Copy, X86::AX, S }, // SDiv
  1674. { X86::IDIV16r, X86::CWD, Copy, X86::DX, S }, // SRem
  1675. { X86::DIV16r, X86::MOV32r0, Copy, X86::AX, U }, // UDiv
  1676. { X86::DIV16r, X86::MOV32r0, Copy, X86::DX, U }, // URem
  1677. }
  1678. }, // i16
  1679. { &X86::GR32RegClass, X86::EAX, X86::EDX, {
  1680. { X86::IDIV32r, X86::CDQ, Copy, X86::EAX, S }, // SDiv
  1681. { X86::IDIV32r, X86::CDQ, Copy, X86::EDX, S }, // SRem
  1682. { X86::DIV32r, X86::MOV32r0, Copy, X86::EAX, U }, // UDiv
  1683. { X86::DIV32r, X86::MOV32r0, Copy, X86::EDX, U }, // URem
  1684. }
  1685. }, // i32
  1686. { &X86::GR64RegClass, X86::RAX, X86::RDX, {
  1687. { X86::IDIV64r, X86::CQO, Copy, X86::RAX, S }, // SDiv
  1688. { X86::IDIV64r, X86::CQO, Copy, X86::RDX, S }, // SRem
  1689. { X86::DIV64r, X86::MOV32r0, Copy, X86::RAX, U }, // UDiv
  1690. { X86::DIV64r, X86::MOV32r0, Copy, X86::RDX, U }, // URem
  1691. }
  1692. }, // i64
  1693. };
  1694. MVT VT;
  1695. if (!isTypeLegal(I->getType(), VT))
  1696. return false;
  1697. unsigned TypeIndex, OpIndex;
  1698. switch (VT.SimpleTy) {
  1699. default: return false;
  1700. case MVT::i8: TypeIndex = 0; break;
  1701. case MVT::i16: TypeIndex = 1; break;
  1702. case MVT::i32: TypeIndex = 2; break;
  1703. case MVT::i64: TypeIndex = 3;
  1704. if (!Subtarget->is64Bit())
  1705. return false;
  1706. break;
  1707. }
  1708. switch (I->getOpcode()) {
  1709. default: llvm_unreachable("Unexpected div/rem opcode");
  1710. case Instruction::SDiv: OpIndex = 0; break;
  1711. case Instruction::SRem: OpIndex = 1; break;
  1712. case Instruction::UDiv: OpIndex = 2; break;
  1713. case Instruction::URem: OpIndex = 3; break;
  1714. }
  1715. const DivRemEntry &TypeEntry = OpTable[TypeIndex];
  1716. const DivRemEntry::DivRemResult &OpEntry = TypeEntry.ResultTable[OpIndex];
  1717. Register Op0Reg = getRegForValue(I->getOperand(0));
  1718. if (Op0Reg == 0)
  1719. return false;
  1720. Register Op1Reg = getRegForValue(I->getOperand(1));
  1721. if (Op1Reg == 0)
  1722. return false;
  1723. // Move op0 into low-order input register.
  1724. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1725. TII.get(OpEntry.OpCopy), TypeEntry.LowInReg).addReg(Op0Reg);
  1726. // Zero-extend or sign-extend into high-order input register.
  1727. if (OpEntry.OpSignExtend) {
  1728. if (OpEntry.IsOpSigned)
  1729. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1730. TII.get(OpEntry.OpSignExtend));
  1731. else {
  1732. Register Zero32 = createResultReg(&X86::GR32RegClass);
  1733. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1734. TII.get(X86::MOV32r0), Zero32);
  1735. // Copy the zero into the appropriate sub/super/identical physical
  1736. // register. Unfortunately the operations needed are not uniform enough
  1737. // to fit neatly into the table above.
  1738. if (VT == MVT::i16) {
  1739. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1740. TII.get(Copy), TypeEntry.HighInReg)
  1741. .addReg(Zero32, 0, X86::sub_16bit);
  1742. } else if (VT == MVT::i32) {
  1743. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1744. TII.get(Copy), TypeEntry.HighInReg)
  1745. .addReg(Zero32);
  1746. } else if (VT == MVT::i64) {
  1747. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1748. TII.get(TargetOpcode::SUBREG_TO_REG), TypeEntry.HighInReg)
  1749. .addImm(0).addReg(Zero32).addImm(X86::sub_32bit);
  1750. }
  1751. }
  1752. }
  1753. // Generate the DIV/IDIV instruction.
  1754. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1755. TII.get(OpEntry.OpDivRem)).addReg(Op1Reg);
  1756. // For i8 remainder, we can't reference ah directly, as we'll end
  1757. // up with bogus copies like %r9b = COPY %ah. Reference ax
  1758. // instead to prevent ah references in a rex instruction.
  1759. //
  1760. // The current assumption of the fast register allocator is that isel
  1761. // won't generate explicit references to the GR8_NOREX registers. If
  1762. // the allocator and/or the backend get enhanced to be more robust in
  1763. // that regard, this can be, and should be, removed.
  1764. unsigned ResultReg = 0;
  1765. if ((I->getOpcode() == Instruction::SRem ||
  1766. I->getOpcode() == Instruction::URem) &&
  1767. OpEntry.DivRemResultReg == X86::AH && Subtarget->is64Bit()) {
  1768. Register SourceSuperReg = createResultReg(&X86::GR16RegClass);
  1769. Register ResultSuperReg = createResultReg(&X86::GR16RegClass);
  1770. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1771. TII.get(Copy), SourceSuperReg).addReg(X86::AX);
  1772. // Shift AX right by 8 bits instead of using AH.
  1773. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SHR16ri),
  1774. ResultSuperReg).addReg(SourceSuperReg).addImm(8);
  1775. // Now reference the 8-bit subreg of the result.
  1776. ResultReg = fastEmitInst_extractsubreg(MVT::i8, ResultSuperReg,
  1777. X86::sub_8bit);
  1778. }
  1779. // Copy the result out of the physreg if we haven't already.
  1780. if (!ResultReg) {
  1781. ResultReg = createResultReg(TypeEntry.RC);
  1782. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Copy), ResultReg)
  1783. .addReg(OpEntry.DivRemResultReg);
  1784. }
  1785. updateValueMap(I, ResultReg);
  1786. return true;
  1787. }
  1788. /// Emit a conditional move instruction (if the are supported) to lower
  1789. /// the select.
  1790. bool X86FastISel::X86FastEmitCMoveSelect(MVT RetVT, const Instruction *I) {
  1791. // Check if the subtarget supports these instructions.
  1792. if (!Subtarget->hasCMov())
  1793. return false;
  1794. // FIXME: Add support for i8.
  1795. if (RetVT < MVT::i16 || RetVT > MVT::i64)
  1796. return false;
  1797. const Value *Cond = I->getOperand(0);
  1798. const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
  1799. bool NeedTest = true;
  1800. X86::CondCode CC = X86::COND_NE;
  1801. // Optimize conditions coming from a compare if both instructions are in the
  1802. // same basic block (values defined in other basic blocks may not have
  1803. // initialized registers).
  1804. const auto *CI = dyn_cast<CmpInst>(Cond);
  1805. if (CI && (CI->getParent() == I->getParent())) {
  1806. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  1807. // FCMP_OEQ and FCMP_UNE cannot be checked with a single instruction.
  1808. static const uint16_t SETFOpcTable[2][3] = {
  1809. { X86::COND_NP, X86::COND_E, X86::TEST8rr },
  1810. { X86::COND_P, X86::COND_NE, X86::OR8rr }
  1811. };
  1812. const uint16_t *SETFOpc = nullptr;
  1813. switch (Predicate) {
  1814. default: break;
  1815. case CmpInst::FCMP_OEQ:
  1816. SETFOpc = &SETFOpcTable[0][0];
  1817. Predicate = CmpInst::ICMP_NE;
  1818. break;
  1819. case CmpInst::FCMP_UNE:
  1820. SETFOpc = &SETFOpcTable[1][0];
  1821. Predicate = CmpInst::ICMP_NE;
  1822. break;
  1823. }
  1824. bool NeedSwap;
  1825. std::tie(CC, NeedSwap) = X86::getX86ConditionCode(Predicate);
  1826. assert(CC <= X86::LAST_VALID_COND && "Unexpected condition code.");
  1827. const Value *CmpLHS = CI->getOperand(0);
  1828. const Value *CmpRHS = CI->getOperand(1);
  1829. if (NeedSwap)
  1830. std::swap(CmpLHS, CmpRHS);
  1831. EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
  1832. // Emit a compare of the LHS and RHS, setting the flags.
  1833. if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
  1834. return false;
  1835. if (SETFOpc) {
  1836. Register FlagReg1 = createResultReg(&X86::GR8RegClass);
  1837. Register FlagReg2 = createResultReg(&X86::GR8RegClass);
  1838. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr),
  1839. FlagReg1).addImm(SETFOpc[0]);
  1840. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr),
  1841. FlagReg2).addImm(SETFOpc[1]);
  1842. auto const &II = TII.get(SETFOpc[2]);
  1843. if (II.getNumDefs()) {
  1844. Register TmpReg = createResultReg(&X86::GR8RegClass);
  1845. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, TmpReg)
  1846. .addReg(FlagReg2).addReg(FlagReg1);
  1847. } else {
  1848. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  1849. .addReg(FlagReg2).addReg(FlagReg1);
  1850. }
  1851. }
  1852. NeedTest = false;
  1853. } else if (foldX86XALUIntrinsic(CC, I, Cond)) {
  1854. // Fake request the condition, otherwise the intrinsic might be completely
  1855. // optimized away.
  1856. Register TmpReg = getRegForValue(Cond);
  1857. if (TmpReg == 0)
  1858. return false;
  1859. NeedTest = false;
  1860. }
  1861. if (NeedTest) {
  1862. // Selects operate on i1, however, CondReg is 8 bits width and may contain
  1863. // garbage. Indeed, only the less significant bit is supposed to be
  1864. // accurate. If we read more than the lsb, we may see non-zero values
  1865. // whereas lsb is zero. Therefore, we have to truncate Op0Reg to i1 for
  1866. // the select. This is achieved by performing TEST against 1.
  1867. Register CondReg = getRegForValue(Cond);
  1868. if (CondReg == 0)
  1869. return false;
  1870. // In case OpReg is a K register, COPY to a GPR
  1871. if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
  1872. unsigned KCondReg = CondReg;
  1873. CondReg = createResultReg(&X86::GR32RegClass);
  1874. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1875. TII.get(TargetOpcode::COPY), CondReg)
  1876. .addReg(KCondReg);
  1877. CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, X86::sub_8bit);
  1878. }
  1879. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
  1880. .addReg(CondReg)
  1881. .addImm(1);
  1882. }
  1883. const Value *LHS = I->getOperand(1);
  1884. const Value *RHS = I->getOperand(2);
  1885. Register RHSReg = getRegForValue(RHS);
  1886. Register LHSReg = getRegForValue(LHS);
  1887. if (!LHSReg || !RHSReg)
  1888. return false;
  1889. const TargetRegisterInfo &TRI = *Subtarget->getRegisterInfo();
  1890. unsigned Opc = X86::getCMovOpcode(TRI.getRegSizeInBits(*RC)/8);
  1891. Register ResultReg = fastEmitInst_rri(Opc, RC, RHSReg, LHSReg, CC);
  1892. updateValueMap(I, ResultReg);
  1893. return true;
  1894. }
  1895. /// Emit SSE or AVX instructions to lower the select.
  1896. ///
  1897. /// Try to use SSE1/SSE2 instructions to simulate a select without branches.
  1898. /// This lowers fp selects into a CMP/AND/ANDN/OR sequence when the necessary
  1899. /// SSE instructions are available. If AVX is available, try to use a VBLENDV.
  1900. bool X86FastISel::X86FastEmitSSESelect(MVT RetVT, const Instruction *I) {
  1901. // Optimize conditions coming from a compare if both instructions are in the
  1902. // same basic block (values defined in other basic blocks may not have
  1903. // initialized registers).
  1904. const auto *CI = dyn_cast<FCmpInst>(I->getOperand(0));
  1905. if (!CI || (CI->getParent() != I->getParent()))
  1906. return false;
  1907. if (I->getType() != CI->getOperand(0)->getType() ||
  1908. !((Subtarget->hasSSE1() && RetVT == MVT::f32) ||
  1909. (Subtarget->hasSSE2() && RetVT == MVT::f64)))
  1910. return false;
  1911. const Value *CmpLHS = CI->getOperand(0);
  1912. const Value *CmpRHS = CI->getOperand(1);
  1913. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  1914. // The optimizer might have replaced fcmp oeq %x, %x with fcmp ord %x, 0.0.
  1915. // We don't have to materialize a zero constant for this case and can just use
  1916. // %x again on the RHS.
  1917. if (Predicate == CmpInst::FCMP_ORD || Predicate == CmpInst::FCMP_UNO) {
  1918. const auto *CmpRHSC = dyn_cast<ConstantFP>(CmpRHS);
  1919. if (CmpRHSC && CmpRHSC->isNullValue())
  1920. CmpRHS = CmpLHS;
  1921. }
  1922. unsigned CC;
  1923. bool NeedSwap;
  1924. std::tie(CC, NeedSwap) = getX86SSEConditionCode(Predicate);
  1925. if (CC > 7 && !Subtarget->hasAVX())
  1926. return false;
  1927. if (NeedSwap)
  1928. std::swap(CmpLHS, CmpRHS);
  1929. const Value *LHS = I->getOperand(1);
  1930. const Value *RHS = I->getOperand(2);
  1931. Register LHSReg = getRegForValue(LHS);
  1932. Register RHSReg = getRegForValue(RHS);
  1933. Register CmpLHSReg = getRegForValue(CmpLHS);
  1934. Register CmpRHSReg = getRegForValue(CmpRHS);
  1935. if (!LHSReg || !RHSReg || !CmpLHSReg || !CmpRHSReg)
  1936. return false;
  1937. const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
  1938. unsigned ResultReg;
  1939. if (Subtarget->hasAVX512()) {
  1940. // If we have AVX512 we can use a mask compare and masked movss/sd.
  1941. const TargetRegisterClass *VR128X = &X86::VR128XRegClass;
  1942. const TargetRegisterClass *VK1 = &X86::VK1RegClass;
  1943. unsigned CmpOpcode =
  1944. (RetVT == MVT::f32) ? X86::VCMPSSZrr : X86::VCMPSDZrr;
  1945. Register CmpReg = fastEmitInst_rri(CmpOpcode, VK1, CmpLHSReg, CmpRHSReg,
  1946. CC);
  1947. // Need an IMPLICIT_DEF for the input that is used to generate the upper
  1948. // bits of the result register since its not based on any of the inputs.
  1949. Register ImplicitDefReg = createResultReg(VR128X);
  1950. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1951. TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
  1952. // Place RHSReg is the passthru of the masked movss/sd operation and put
  1953. // LHS in the input. The mask input comes from the compare.
  1954. unsigned MovOpcode =
  1955. (RetVT == MVT::f32) ? X86::VMOVSSZrrk : X86::VMOVSDZrrk;
  1956. unsigned MovReg = fastEmitInst_rrrr(MovOpcode, VR128X, RHSReg, CmpReg,
  1957. ImplicitDefReg, LHSReg);
  1958. ResultReg = createResultReg(RC);
  1959. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1960. TII.get(TargetOpcode::COPY), ResultReg).addReg(MovReg);
  1961. } else if (Subtarget->hasAVX()) {
  1962. const TargetRegisterClass *VR128 = &X86::VR128RegClass;
  1963. // If we have AVX, create 1 blendv instead of 3 logic instructions.
  1964. // Blendv was introduced with SSE 4.1, but the 2 register form implicitly
  1965. // uses XMM0 as the selection register. That may need just as many
  1966. // instructions as the AND/ANDN/OR sequence due to register moves, so
  1967. // don't bother.
  1968. unsigned CmpOpcode =
  1969. (RetVT == MVT::f32) ? X86::VCMPSSrr : X86::VCMPSDrr;
  1970. unsigned BlendOpcode =
  1971. (RetVT == MVT::f32) ? X86::VBLENDVPSrr : X86::VBLENDVPDrr;
  1972. Register CmpReg = fastEmitInst_rri(CmpOpcode, RC, CmpLHSReg, CmpRHSReg,
  1973. CC);
  1974. Register VBlendReg = fastEmitInst_rrr(BlendOpcode, VR128, RHSReg, LHSReg,
  1975. CmpReg);
  1976. ResultReg = createResultReg(RC);
  1977. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1978. TII.get(TargetOpcode::COPY), ResultReg).addReg(VBlendReg);
  1979. } else {
  1980. // Choose the SSE instruction sequence based on data type (float or double).
  1981. static const uint16_t OpcTable[2][4] = {
  1982. { X86::CMPSSrr, X86::ANDPSrr, X86::ANDNPSrr, X86::ORPSrr },
  1983. { X86::CMPSDrr, X86::ANDPDrr, X86::ANDNPDrr, X86::ORPDrr }
  1984. };
  1985. const uint16_t *Opc = nullptr;
  1986. switch (RetVT.SimpleTy) {
  1987. default: return false;
  1988. case MVT::f32: Opc = &OpcTable[0][0]; break;
  1989. case MVT::f64: Opc = &OpcTable[1][0]; break;
  1990. }
  1991. const TargetRegisterClass *VR128 = &X86::VR128RegClass;
  1992. Register CmpReg = fastEmitInst_rri(Opc[0], RC, CmpLHSReg, CmpRHSReg, CC);
  1993. Register AndReg = fastEmitInst_rr(Opc[1], VR128, CmpReg, LHSReg);
  1994. Register AndNReg = fastEmitInst_rr(Opc[2], VR128, CmpReg, RHSReg);
  1995. Register OrReg = fastEmitInst_rr(Opc[3], VR128, AndNReg, AndReg);
  1996. ResultReg = createResultReg(RC);
  1997. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  1998. TII.get(TargetOpcode::COPY), ResultReg).addReg(OrReg);
  1999. }
  2000. updateValueMap(I, ResultReg);
  2001. return true;
  2002. }
  2003. bool X86FastISel::X86FastEmitPseudoSelect(MVT RetVT, const Instruction *I) {
  2004. // These are pseudo CMOV instructions and will be later expanded into control-
  2005. // flow.
  2006. unsigned Opc;
  2007. switch (RetVT.SimpleTy) {
  2008. default: return false;
  2009. case MVT::i8: Opc = X86::CMOV_GR8; break;
  2010. case MVT::i16: Opc = X86::CMOV_GR16; break;
  2011. case MVT::f16: Opc = X86::CMOV_FR16X; break;
  2012. case MVT::i32: Opc = X86::CMOV_GR32; break;
  2013. case MVT::f32: Opc = Subtarget->hasAVX512() ? X86::CMOV_FR32X
  2014. : X86::CMOV_FR32; break;
  2015. case MVT::f64: Opc = Subtarget->hasAVX512() ? X86::CMOV_FR64X
  2016. : X86::CMOV_FR64; break;
  2017. }
  2018. const Value *Cond = I->getOperand(0);
  2019. X86::CondCode CC = X86::COND_NE;
  2020. // Optimize conditions coming from a compare if both instructions are in the
  2021. // same basic block (values defined in other basic blocks may not have
  2022. // initialized registers).
  2023. const auto *CI = dyn_cast<CmpInst>(Cond);
  2024. if (CI && (CI->getParent() == I->getParent())) {
  2025. bool NeedSwap;
  2026. std::tie(CC, NeedSwap) = X86::getX86ConditionCode(CI->getPredicate());
  2027. if (CC > X86::LAST_VALID_COND)
  2028. return false;
  2029. const Value *CmpLHS = CI->getOperand(0);
  2030. const Value *CmpRHS = CI->getOperand(1);
  2031. if (NeedSwap)
  2032. std::swap(CmpLHS, CmpRHS);
  2033. EVT CmpVT = TLI.getValueType(DL, CmpLHS->getType());
  2034. if (!X86FastEmitCompare(CmpLHS, CmpRHS, CmpVT, CI->getDebugLoc()))
  2035. return false;
  2036. } else {
  2037. Register CondReg = getRegForValue(Cond);
  2038. if (CondReg == 0)
  2039. return false;
  2040. // In case OpReg is a K register, COPY to a GPR
  2041. if (MRI.getRegClass(CondReg) == &X86::VK1RegClass) {
  2042. unsigned KCondReg = CondReg;
  2043. CondReg = createResultReg(&X86::GR32RegClass);
  2044. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2045. TII.get(TargetOpcode::COPY), CondReg)
  2046. .addReg(KCondReg);
  2047. CondReg = fastEmitInst_extractsubreg(MVT::i8, CondReg, X86::sub_8bit);
  2048. }
  2049. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TEST8ri))
  2050. .addReg(CondReg)
  2051. .addImm(1);
  2052. }
  2053. const Value *LHS = I->getOperand(1);
  2054. const Value *RHS = I->getOperand(2);
  2055. Register LHSReg = getRegForValue(LHS);
  2056. Register RHSReg = getRegForValue(RHS);
  2057. if (!LHSReg || !RHSReg)
  2058. return false;
  2059. const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
  2060. Register ResultReg =
  2061. fastEmitInst_rri(Opc, RC, RHSReg, LHSReg, CC);
  2062. updateValueMap(I, ResultReg);
  2063. return true;
  2064. }
  2065. bool X86FastISel::X86SelectSelect(const Instruction *I) {
  2066. MVT RetVT;
  2067. if (!isTypeLegal(I->getType(), RetVT))
  2068. return false;
  2069. // Check if we can fold the select.
  2070. if (const auto *CI = dyn_cast<CmpInst>(I->getOperand(0))) {
  2071. CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
  2072. const Value *Opnd = nullptr;
  2073. switch (Predicate) {
  2074. default: break;
  2075. case CmpInst::FCMP_FALSE: Opnd = I->getOperand(2); break;
  2076. case CmpInst::FCMP_TRUE: Opnd = I->getOperand(1); break;
  2077. }
  2078. // No need for a select anymore - this is an unconditional move.
  2079. if (Opnd) {
  2080. Register OpReg = getRegForValue(Opnd);
  2081. if (OpReg == 0)
  2082. return false;
  2083. const TargetRegisterClass *RC = TLI.getRegClassFor(RetVT);
  2084. Register ResultReg = createResultReg(RC);
  2085. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2086. TII.get(TargetOpcode::COPY), ResultReg)
  2087. .addReg(OpReg);
  2088. updateValueMap(I, ResultReg);
  2089. return true;
  2090. }
  2091. }
  2092. // First try to use real conditional move instructions.
  2093. if (X86FastEmitCMoveSelect(RetVT, I))
  2094. return true;
  2095. // Try to use a sequence of SSE instructions to simulate a conditional move.
  2096. if (X86FastEmitSSESelect(RetVT, I))
  2097. return true;
  2098. // Fall-back to pseudo conditional move instructions, which will be later
  2099. // converted to control-flow.
  2100. if (X86FastEmitPseudoSelect(RetVT, I))
  2101. return true;
  2102. return false;
  2103. }
  2104. // Common code for X86SelectSIToFP and X86SelectUIToFP.
  2105. bool X86FastISel::X86SelectIntToFP(const Instruction *I, bool IsSigned) {
  2106. // The target-independent selection algorithm in FastISel already knows how
  2107. // to select a SINT_TO_FP if the target is SSE but not AVX.
  2108. // Early exit if the subtarget doesn't have AVX.
  2109. // Unsigned conversion requires avx512.
  2110. bool HasAVX512 = Subtarget->hasAVX512();
  2111. if (!Subtarget->hasAVX() || (!IsSigned && !HasAVX512))
  2112. return false;
  2113. // TODO: We could sign extend narrower types.
  2114. MVT SrcVT = TLI.getSimpleValueType(DL, I->getOperand(0)->getType());
  2115. if (SrcVT != MVT::i32 && SrcVT != MVT::i64)
  2116. return false;
  2117. // Select integer to float/double conversion.
  2118. Register OpReg = getRegForValue(I->getOperand(0));
  2119. if (OpReg == 0)
  2120. return false;
  2121. unsigned Opcode;
  2122. static const uint16_t SCvtOpc[2][2][2] = {
  2123. { { X86::VCVTSI2SSrr, X86::VCVTSI642SSrr },
  2124. { X86::VCVTSI2SDrr, X86::VCVTSI642SDrr } },
  2125. { { X86::VCVTSI2SSZrr, X86::VCVTSI642SSZrr },
  2126. { X86::VCVTSI2SDZrr, X86::VCVTSI642SDZrr } },
  2127. };
  2128. static const uint16_t UCvtOpc[2][2] = {
  2129. { X86::VCVTUSI2SSZrr, X86::VCVTUSI642SSZrr },
  2130. { X86::VCVTUSI2SDZrr, X86::VCVTUSI642SDZrr },
  2131. };
  2132. bool Is64Bit = SrcVT == MVT::i64;
  2133. if (I->getType()->isDoubleTy()) {
  2134. // s/uitofp int -> double
  2135. Opcode = IsSigned ? SCvtOpc[HasAVX512][1][Is64Bit] : UCvtOpc[1][Is64Bit];
  2136. } else if (I->getType()->isFloatTy()) {
  2137. // s/uitofp int -> float
  2138. Opcode = IsSigned ? SCvtOpc[HasAVX512][0][Is64Bit] : UCvtOpc[0][Is64Bit];
  2139. } else
  2140. return false;
  2141. MVT DstVT = TLI.getValueType(DL, I->getType()).getSimpleVT();
  2142. const TargetRegisterClass *RC = TLI.getRegClassFor(DstVT);
  2143. Register ImplicitDefReg = createResultReg(RC);
  2144. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2145. TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
  2146. Register ResultReg = fastEmitInst_rr(Opcode, RC, ImplicitDefReg, OpReg);
  2147. updateValueMap(I, ResultReg);
  2148. return true;
  2149. }
  2150. bool X86FastISel::X86SelectSIToFP(const Instruction *I) {
  2151. return X86SelectIntToFP(I, /*IsSigned*/true);
  2152. }
  2153. bool X86FastISel::X86SelectUIToFP(const Instruction *I) {
  2154. return X86SelectIntToFP(I, /*IsSigned*/false);
  2155. }
  2156. // Helper method used by X86SelectFPExt and X86SelectFPTrunc.
  2157. bool X86FastISel::X86SelectFPExtOrFPTrunc(const Instruction *I,
  2158. unsigned TargetOpc,
  2159. const TargetRegisterClass *RC) {
  2160. assert((I->getOpcode() == Instruction::FPExt ||
  2161. I->getOpcode() == Instruction::FPTrunc) &&
  2162. "Instruction must be an FPExt or FPTrunc!");
  2163. bool HasAVX = Subtarget->hasAVX();
  2164. Register OpReg = getRegForValue(I->getOperand(0));
  2165. if (OpReg == 0)
  2166. return false;
  2167. unsigned ImplicitDefReg;
  2168. if (HasAVX) {
  2169. ImplicitDefReg = createResultReg(RC);
  2170. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2171. TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
  2172. }
  2173. Register ResultReg = createResultReg(RC);
  2174. MachineInstrBuilder MIB;
  2175. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpc),
  2176. ResultReg);
  2177. if (HasAVX)
  2178. MIB.addReg(ImplicitDefReg);
  2179. MIB.addReg(OpReg);
  2180. updateValueMap(I, ResultReg);
  2181. return true;
  2182. }
  2183. bool X86FastISel::X86SelectFPExt(const Instruction *I) {
  2184. if (X86ScalarSSEf64 && I->getType()->isDoubleTy() &&
  2185. I->getOperand(0)->getType()->isFloatTy()) {
  2186. bool HasAVX512 = Subtarget->hasAVX512();
  2187. // fpext from float to double.
  2188. unsigned Opc =
  2189. HasAVX512 ? X86::VCVTSS2SDZrr
  2190. : Subtarget->hasAVX() ? X86::VCVTSS2SDrr : X86::CVTSS2SDrr;
  2191. return X86SelectFPExtOrFPTrunc(I, Opc, TLI.getRegClassFor(MVT::f64));
  2192. }
  2193. return false;
  2194. }
  2195. bool X86FastISel::X86SelectFPTrunc(const Instruction *I) {
  2196. if (X86ScalarSSEf64 && I->getType()->isFloatTy() &&
  2197. I->getOperand(0)->getType()->isDoubleTy()) {
  2198. bool HasAVX512 = Subtarget->hasAVX512();
  2199. // fptrunc from double to float.
  2200. unsigned Opc =
  2201. HasAVX512 ? X86::VCVTSD2SSZrr
  2202. : Subtarget->hasAVX() ? X86::VCVTSD2SSrr : X86::CVTSD2SSrr;
  2203. return X86SelectFPExtOrFPTrunc(I, Opc, TLI.getRegClassFor(MVT::f32));
  2204. }
  2205. return false;
  2206. }
  2207. bool X86FastISel::X86SelectTrunc(const Instruction *I) {
  2208. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  2209. EVT DstVT = TLI.getValueType(DL, I->getType());
  2210. // This code only handles truncation to byte.
  2211. if (DstVT != MVT::i8 && DstVT != MVT::i1)
  2212. return false;
  2213. if (!TLI.isTypeLegal(SrcVT))
  2214. return false;
  2215. Register InputReg = getRegForValue(I->getOperand(0));
  2216. if (!InputReg)
  2217. // Unhandled operand. Halt "fast" selection and bail.
  2218. return false;
  2219. if (SrcVT == MVT::i8) {
  2220. // Truncate from i8 to i1; no code needed.
  2221. updateValueMap(I, InputReg);
  2222. return true;
  2223. }
  2224. // Issue an extract_subreg.
  2225. Register ResultReg = fastEmitInst_extractsubreg(MVT::i8, InputReg,
  2226. X86::sub_8bit);
  2227. if (!ResultReg)
  2228. return false;
  2229. updateValueMap(I, ResultReg);
  2230. return true;
  2231. }
  2232. bool X86FastISel::IsMemcpySmall(uint64_t Len) {
  2233. return Len <= (Subtarget->is64Bit() ? 32 : 16);
  2234. }
  2235. bool X86FastISel::TryEmitSmallMemcpy(X86AddressMode DestAM,
  2236. X86AddressMode SrcAM, uint64_t Len) {
  2237. // Make sure we don't bloat code by inlining very large memcpy's.
  2238. if (!IsMemcpySmall(Len))
  2239. return false;
  2240. bool i64Legal = Subtarget->is64Bit();
  2241. // We don't care about alignment here since we just emit integer accesses.
  2242. while (Len) {
  2243. MVT VT;
  2244. if (Len >= 8 && i64Legal)
  2245. VT = MVT::i64;
  2246. else if (Len >= 4)
  2247. VT = MVT::i32;
  2248. else if (Len >= 2)
  2249. VT = MVT::i16;
  2250. else
  2251. VT = MVT::i8;
  2252. unsigned Reg;
  2253. bool RV = X86FastEmitLoad(VT, SrcAM, nullptr, Reg);
  2254. RV &= X86FastEmitStore(VT, Reg, DestAM);
  2255. assert(RV && "Failed to emit load or store??");
  2256. (void)RV;
  2257. unsigned Size = VT.getSizeInBits()/8;
  2258. Len -= Size;
  2259. DestAM.Disp += Size;
  2260. SrcAM.Disp += Size;
  2261. }
  2262. return true;
  2263. }
  2264. bool X86FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
  2265. // FIXME: Handle more intrinsics.
  2266. switch (II->getIntrinsicID()) {
  2267. default: return false;
  2268. case Intrinsic::convert_from_fp16:
  2269. case Intrinsic::convert_to_fp16: {
  2270. if (Subtarget->useSoftFloat() || !Subtarget->hasF16C())
  2271. return false;
  2272. const Value *Op = II->getArgOperand(0);
  2273. Register InputReg = getRegForValue(Op);
  2274. if (InputReg == 0)
  2275. return false;
  2276. // F16C only allows converting from float to half and from half to float.
  2277. bool IsFloatToHalf = II->getIntrinsicID() == Intrinsic::convert_to_fp16;
  2278. if (IsFloatToHalf) {
  2279. if (!Op->getType()->isFloatTy())
  2280. return false;
  2281. } else {
  2282. if (!II->getType()->isFloatTy())
  2283. return false;
  2284. }
  2285. unsigned ResultReg = 0;
  2286. const TargetRegisterClass *RC = TLI.getRegClassFor(MVT::v8i16);
  2287. if (IsFloatToHalf) {
  2288. // 'InputReg' is implicitly promoted from register class FR32 to
  2289. // register class VR128 by method 'constrainOperandRegClass' which is
  2290. // directly called by 'fastEmitInst_ri'.
  2291. // Instruction VCVTPS2PHrr takes an extra immediate operand which is
  2292. // used to provide rounding control: use MXCSR.RC, encoded as 0b100.
  2293. // It's consistent with the other FP instructions, which are usually
  2294. // controlled by MXCSR.
  2295. unsigned Opc = Subtarget->hasVLX() ? X86::VCVTPS2PHZ128rr
  2296. : X86::VCVTPS2PHrr;
  2297. InputReg = fastEmitInst_ri(Opc, RC, InputReg, 4);
  2298. // Move the lower 32-bits of ResultReg to another register of class GR32.
  2299. Opc = Subtarget->hasAVX512() ? X86::VMOVPDI2DIZrr
  2300. : X86::VMOVPDI2DIrr;
  2301. ResultReg = createResultReg(&X86::GR32RegClass);
  2302. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
  2303. .addReg(InputReg, RegState::Kill);
  2304. // The result value is in the lower 16-bits of ResultReg.
  2305. unsigned RegIdx = X86::sub_16bit;
  2306. ResultReg = fastEmitInst_extractsubreg(MVT::i16, ResultReg, RegIdx);
  2307. } else {
  2308. assert(Op->getType()->isIntegerTy(16) && "Expected a 16-bit integer!");
  2309. // Explicitly zero-extend the input to 32-bit.
  2310. InputReg = fastEmit_r(MVT::i16, MVT::i32, ISD::ZERO_EXTEND, InputReg);
  2311. // The following SCALAR_TO_VECTOR will be expanded into a VMOVDI2PDIrr.
  2312. InputReg = fastEmit_r(MVT::i32, MVT::v4i32, ISD::SCALAR_TO_VECTOR,
  2313. InputReg);
  2314. unsigned Opc = Subtarget->hasVLX() ? X86::VCVTPH2PSZ128rr
  2315. : X86::VCVTPH2PSrr;
  2316. InputReg = fastEmitInst_r(Opc, RC, InputReg);
  2317. // The result value is in the lower 32-bits of ResultReg.
  2318. // Emit an explicit copy from register class VR128 to register class FR32.
  2319. ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
  2320. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2321. TII.get(TargetOpcode::COPY), ResultReg)
  2322. .addReg(InputReg, RegState::Kill);
  2323. }
  2324. updateValueMap(II, ResultReg);
  2325. return true;
  2326. }
  2327. case Intrinsic::frameaddress: {
  2328. MachineFunction *MF = FuncInfo.MF;
  2329. if (MF->getTarget().getMCAsmInfo()->usesWindowsCFI())
  2330. return false;
  2331. Type *RetTy = II->getCalledFunction()->getReturnType();
  2332. MVT VT;
  2333. if (!isTypeLegal(RetTy, VT))
  2334. return false;
  2335. unsigned Opc;
  2336. const TargetRegisterClass *RC = nullptr;
  2337. switch (VT.SimpleTy) {
  2338. default: llvm_unreachable("Invalid result type for frameaddress.");
  2339. case MVT::i32: Opc = X86::MOV32rm; RC = &X86::GR32RegClass; break;
  2340. case MVT::i64: Opc = X86::MOV64rm; RC = &X86::GR64RegClass; break;
  2341. }
  2342. // This needs to be set before we call getPtrSizedFrameRegister, otherwise
  2343. // we get the wrong frame register.
  2344. MachineFrameInfo &MFI = MF->getFrameInfo();
  2345. MFI.setFrameAddressIsTaken(true);
  2346. const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
  2347. unsigned FrameReg = RegInfo->getPtrSizedFrameRegister(*MF);
  2348. assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
  2349. (FrameReg == X86::EBP && VT == MVT::i32)) &&
  2350. "Invalid Frame Register!");
  2351. // Always make a copy of the frame register to a vreg first, so that we
  2352. // never directly reference the frame register (the TwoAddressInstruction-
  2353. // Pass doesn't like that).
  2354. Register SrcReg = createResultReg(RC);
  2355. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2356. TII.get(TargetOpcode::COPY), SrcReg).addReg(FrameReg);
  2357. // Now recursively load from the frame address.
  2358. // movq (%rbp), %rax
  2359. // movq (%rax), %rax
  2360. // movq (%rax), %rax
  2361. // ...
  2362. unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
  2363. while (Depth--) {
  2364. Register DestReg = createResultReg(RC);
  2365. addDirectMem(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2366. TII.get(Opc), DestReg), SrcReg);
  2367. SrcReg = DestReg;
  2368. }
  2369. updateValueMap(II, SrcReg);
  2370. return true;
  2371. }
  2372. case Intrinsic::memcpy: {
  2373. const MemCpyInst *MCI = cast<MemCpyInst>(II);
  2374. // Don't handle volatile or variable length memcpys.
  2375. if (MCI->isVolatile())
  2376. return false;
  2377. if (isa<ConstantInt>(MCI->getLength())) {
  2378. // Small memcpy's are common enough that we want to do them
  2379. // without a call if possible.
  2380. uint64_t Len = cast<ConstantInt>(MCI->getLength())->getZExtValue();
  2381. if (IsMemcpySmall(Len)) {
  2382. X86AddressMode DestAM, SrcAM;
  2383. if (!X86SelectAddress(MCI->getRawDest(), DestAM) ||
  2384. !X86SelectAddress(MCI->getRawSource(), SrcAM))
  2385. return false;
  2386. TryEmitSmallMemcpy(DestAM, SrcAM, Len);
  2387. return true;
  2388. }
  2389. }
  2390. unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
  2391. if (!MCI->getLength()->getType()->isIntegerTy(SizeWidth))
  2392. return false;
  2393. if (MCI->getSourceAddressSpace() > 255 || MCI->getDestAddressSpace() > 255)
  2394. return false;
  2395. return lowerCallTo(II, "memcpy", II->arg_size() - 1);
  2396. }
  2397. case Intrinsic::memset: {
  2398. const MemSetInst *MSI = cast<MemSetInst>(II);
  2399. if (MSI->isVolatile())
  2400. return false;
  2401. unsigned SizeWidth = Subtarget->is64Bit() ? 64 : 32;
  2402. if (!MSI->getLength()->getType()->isIntegerTy(SizeWidth))
  2403. return false;
  2404. if (MSI->getDestAddressSpace() > 255)
  2405. return false;
  2406. return lowerCallTo(II, "memset", II->arg_size() - 1);
  2407. }
  2408. case Intrinsic::stackprotector: {
  2409. // Emit code to store the stack guard onto the stack.
  2410. EVT PtrTy = TLI.getPointerTy(DL);
  2411. const Value *Op1 = II->getArgOperand(0); // The guard's value.
  2412. const AllocaInst *Slot = cast<AllocaInst>(II->getArgOperand(1));
  2413. MFI.setStackProtectorIndex(FuncInfo.StaticAllocaMap[Slot]);
  2414. // Grab the frame index.
  2415. X86AddressMode AM;
  2416. if (!X86SelectAddress(Slot, AM)) return false;
  2417. if (!X86FastEmitStore(PtrTy, Op1, AM)) return false;
  2418. return true;
  2419. }
  2420. case Intrinsic::dbg_declare: {
  2421. const DbgDeclareInst *DI = cast<DbgDeclareInst>(II);
  2422. X86AddressMode AM;
  2423. assert(DI->getAddress() && "Null address should be checked earlier!");
  2424. if (!X86SelectAddress(DI->getAddress(), AM))
  2425. return false;
  2426. const MCInstrDesc &II = TII.get(TargetOpcode::DBG_VALUE);
  2427. assert(DI->getVariable()->isValidLocationForIntrinsic(DbgLoc) &&
  2428. "Expected inlined-at fields to agree");
  2429. addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II), AM)
  2430. .addImm(0)
  2431. .addMetadata(DI->getVariable())
  2432. .addMetadata(DI->getExpression());
  2433. return true;
  2434. }
  2435. case Intrinsic::trap: {
  2436. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::TRAP));
  2437. return true;
  2438. }
  2439. case Intrinsic::sqrt: {
  2440. if (!Subtarget->hasSSE1())
  2441. return false;
  2442. Type *RetTy = II->getCalledFunction()->getReturnType();
  2443. MVT VT;
  2444. if (!isTypeLegal(RetTy, VT))
  2445. return false;
  2446. // Unfortunately we can't use fastEmit_r, because the AVX version of FSQRT
  2447. // is not generated by FastISel yet.
  2448. // FIXME: Update this code once tablegen can handle it.
  2449. static const uint16_t SqrtOpc[3][2] = {
  2450. { X86::SQRTSSr, X86::SQRTSDr },
  2451. { X86::VSQRTSSr, X86::VSQRTSDr },
  2452. { X86::VSQRTSSZr, X86::VSQRTSDZr },
  2453. };
  2454. unsigned AVXLevel = Subtarget->hasAVX512() ? 2 :
  2455. Subtarget->hasAVX() ? 1 :
  2456. 0;
  2457. unsigned Opc;
  2458. switch (VT.SimpleTy) {
  2459. default: return false;
  2460. case MVT::f32: Opc = SqrtOpc[AVXLevel][0]; break;
  2461. case MVT::f64: Opc = SqrtOpc[AVXLevel][1]; break;
  2462. }
  2463. const Value *SrcVal = II->getArgOperand(0);
  2464. Register SrcReg = getRegForValue(SrcVal);
  2465. if (SrcReg == 0)
  2466. return false;
  2467. const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
  2468. unsigned ImplicitDefReg = 0;
  2469. if (AVXLevel > 0) {
  2470. ImplicitDefReg = createResultReg(RC);
  2471. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2472. TII.get(TargetOpcode::IMPLICIT_DEF), ImplicitDefReg);
  2473. }
  2474. Register ResultReg = createResultReg(RC);
  2475. MachineInstrBuilder MIB;
  2476. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
  2477. ResultReg);
  2478. if (ImplicitDefReg)
  2479. MIB.addReg(ImplicitDefReg);
  2480. MIB.addReg(SrcReg);
  2481. updateValueMap(II, ResultReg);
  2482. return true;
  2483. }
  2484. case Intrinsic::sadd_with_overflow:
  2485. case Intrinsic::uadd_with_overflow:
  2486. case Intrinsic::ssub_with_overflow:
  2487. case Intrinsic::usub_with_overflow:
  2488. case Intrinsic::smul_with_overflow:
  2489. case Intrinsic::umul_with_overflow: {
  2490. // This implements the basic lowering of the xalu with overflow intrinsics
  2491. // into add/sub/mul followed by either seto or setb.
  2492. const Function *Callee = II->getCalledFunction();
  2493. auto *Ty = cast<StructType>(Callee->getReturnType());
  2494. Type *RetTy = Ty->getTypeAtIndex(0U);
  2495. assert(Ty->getTypeAtIndex(1)->isIntegerTy() &&
  2496. Ty->getTypeAtIndex(1)->getScalarSizeInBits() == 1 &&
  2497. "Overflow value expected to be an i1");
  2498. MVT VT;
  2499. if (!isTypeLegal(RetTy, VT))
  2500. return false;
  2501. if (VT < MVT::i8 || VT > MVT::i64)
  2502. return false;
  2503. const Value *LHS = II->getArgOperand(0);
  2504. const Value *RHS = II->getArgOperand(1);
  2505. // Canonicalize immediate to the RHS.
  2506. if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) && II->isCommutative())
  2507. std::swap(LHS, RHS);
  2508. unsigned BaseOpc, CondCode;
  2509. switch (II->getIntrinsicID()) {
  2510. default: llvm_unreachable("Unexpected intrinsic!");
  2511. case Intrinsic::sadd_with_overflow:
  2512. BaseOpc = ISD::ADD; CondCode = X86::COND_O; break;
  2513. case Intrinsic::uadd_with_overflow:
  2514. BaseOpc = ISD::ADD; CondCode = X86::COND_B; break;
  2515. case Intrinsic::ssub_with_overflow:
  2516. BaseOpc = ISD::SUB; CondCode = X86::COND_O; break;
  2517. case Intrinsic::usub_with_overflow:
  2518. BaseOpc = ISD::SUB; CondCode = X86::COND_B; break;
  2519. case Intrinsic::smul_with_overflow:
  2520. BaseOpc = X86ISD::SMUL; CondCode = X86::COND_O; break;
  2521. case Intrinsic::umul_with_overflow:
  2522. BaseOpc = X86ISD::UMUL; CondCode = X86::COND_O; break;
  2523. }
  2524. Register LHSReg = getRegForValue(LHS);
  2525. if (LHSReg == 0)
  2526. return false;
  2527. unsigned ResultReg = 0;
  2528. // Check if we have an immediate version.
  2529. if (const auto *CI = dyn_cast<ConstantInt>(RHS)) {
  2530. static const uint16_t Opc[2][4] = {
  2531. { X86::INC8r, X86::INC16r, X86::INC32r, X86::INC64r },
  2532. { X86::DEC8r, X86::DEC16r, X86::DEC32r, X86::DEC64r }
  2533. };
  2534. if (CI->isOne() && (BaseOpc == ISD::ADD || BaseOpc == ISD::SUB) &&
  2535. CondCode == X86::COND_O) {
  2536. // We can use INC/DEC.
  2537. ResultReg = createResultReg(TLI.getRegClassFor(VT));
  2538. bool IsDec = BaseOpc == ISD::SUB;
  2539. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2540. TII.get(Opc[IsDec][VT.SimpleTy-MVT::i8]), ResultReg)
  2541. .addReg(LHSReg);
  2542. } else
  2543. ResultReg = fastEmit_ri(VT, VT, BaseOpc, LHSReg, CI->getZExtValue());
  2544. }
  2545. unsigned RHSReg;
  2546. if (!ResultReg) {
  2547. RHSReg = getRegForValue(RHS);
  2548. if (RHSReg == 0)
  2549. return false;
  2550. ResultReg = fastEmit_rr(VT, VT, BaseOpc, LHSReg, RHSReg);
  2551. }
  2552. // FastISel doesn't have a pattern for all X86::MUL*r and X86::IMUL*r. Emit
  2553. // it manually.
  2554. if (BaseOpc == X86ISD::UMUL && !ResultReg) {
  2555. static const uint16_t MULOpc[] =
  2556. { X86::MUL8r, X86::MUL16r, X86::MUL32r, X86::MUL64r };
  2557. static const MCPhysReg Reg[] = { X86::AL, X86::AX, X86::EAX, X86::RAX };
  2558. // First copy the first operand into RAX, which is an implicit input to
  2559. // the X86::MUL*r instruction.
  2560. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2561. TII.get(TargetOpcode::COPY), Reg[VT.SimpleTy-MVT::i8])
  2562. .addReg(LHSReg);
  2563. ResultReg = fastEmitInst_r(MULOpc[VT.SimpleTy-MVT::i8],
  2564. TLI.getRegClassFor(VT), RHSReg);
  2565. } else if (BaseOpc == X86ISD::SMUL && !ResultReg) {
  2566. static const uint16_t MULOpc[] =
  2567. { X86::IMUL8r, X86::IMUL16rr, X86::IMUL32rr, X86::IMUL64rr };
  2568. if (VT == MVT::i8) {
  2569. // Copy the first operand into AL, which is an implicit input to the
  2570. // X86::IMUL8r instruction.
  2571. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2572. TII.get(TargetOpcode::COPY), X86::AL)
  2573. .addReg(LHSReg);
  2574. ResultReg = fastEmitInst_r(MULOpc[0], TLI.getRegClassFor(VT), RHSReg);
  2575. } else
  2576. ResultReg = fastEmitInst_rr(MULOpc[VT.SimpleTy-MVT::i8],
  2577. TLI.getRegClassFor(VT), LHSReg, RHSReg);
  2578. }
  2579. if (!ResultReg)
  2580. return false;
  2581. // Assign to a GPR since the overflow return value is lowered to a SETcc.
  2582. Register ResultReg2 = createResultReg(&X86::GR8RegClass);
  2583. assert((ResultReg+1) == ResultReg2 && "Nonconsecutive result registers.");
  2584. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::SETCCr),
  2585. ResultReg2).addImm(CondCode);
  2586. updateValueMap(II, ResultReg, 2);
  2587. return true;
  2588. }
  2589. case Intrinsic::x86_sse_cvttss2si:
  2590. case Intrinsic::x86_sse_cvttss2si64:
  2591. case Intrinsic::x86_sse2_cvttsd2si:
  2592. case Intrinsic::x86_sse2_cvttsd2si64: {
  2593. bool IsInputDouble;
  2594. switch (II->getIntrinsicID()) {
  2595. default: llvm_unreachable("Unexpected intrinsic.");
  2596. case Intrinsic::x86_sse_cvttss2si:
  2597. case Intrinsic::x86_sse_cvttss2si64:
  2598. if (!Subtarget->hasSSE1())
  2599. return false;
  2600. IsInputDouble = false;
  2601. break;
  2602. case Intrinsic::x86_sse2_cvttsd2si:
  2603. case Intrinsic::x86_sse2_cvttsd2si64:
  2604. if (!Subtarget->hasSSE2())
  2605. return false;
  2606. IsInputDouble = true;
  2607. break;
  2608. }
  2609. Type *RetTy = II->getCalledFunction()->getReturnType();
  2610. MVT VT;
  2611. if (!isTypeLegal(RetTy, VT))
  2612. return false;
  2613. static const uint16_t CvtOpc[3][2][2] = {
  2614. { { X86::CVTTSS2SIrr, X86::CVTTSS2SI64rr },
  2615. { X86::CVTTSD2SIrr, X86::CVTTSD2SI64rr } },
  2616. { { X86::VCVTTSS2SIrr, X86::VCVTTSS2SI64rr },
  2617. { X86::VCVTTSD2SIrr, X86::VCVTTSD2SI64rr } },
  2618. { { X86::VCVTTSS2SIZrr, X86::VCVTTSS2SI64Zrr },
  2619. { X86::VCVTTSD2SIZrr, X86::VCVTTSD2SI64Zrr } },
  2620. };
  2621. unsigned AVXLevel = Subtarget->hasAVX512() ? 2 :
  2622. Subtarget->hasAVX() ? 1 :
  2623. 0;
  2624. unsigned Opc;
  2625. switch (VT.SimpleTy) {
  2626. default: llvm_unreachable("Unexpected result type.");
  2627. case MVT::i32: Opc = CvtOpc[AVXLevel][IsInputDouble][0]; break;
  2628. case MVT::i64: Opc = CvtOpc[AVXLevel][IsInputDouble][1]; break;
  2629. }
  2630. // Check if we can fold insertelement instructions into the convert.
  2631. const Value *Op = II->getArgOperand(0);
  2632. while (auto *IE = dyn_cast<InsertElementInst>(Op)) {
  2633. const Value *Index = IE->getOperand(2);
  2634. if (!isa<ConstantInt>(Index))
  2635. break;
  2636. unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
  2637. if (Idx == 0) {
  2638. Op = IE->getOperand(1);
  2639. break;
  2640. }
  2641. Op = IE->getOperand(0);
  2642. }
  2643. Register Reg = getRegForValue(Op);
  2644. if (Reg == 0)
  2645. return false;
  2646. Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
  2647. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
  2648. .addReg(Reg);
  2649. updateValueMap(II, ResultReg);
  2650. return true;
  2651. }
  2652. }
  2653. }
  2654. bool X86FastISel::fastLowerArguments() {
  2655. if (!FuncInfo.CanLowerReturn)
  2656. return false;
  2657. const Function *F = FuncInfo.Fn;
  2658. if (F->isVarArg())
  2659. return false;
  2660. CallingConv::ID CC = F->getCallingConv();
  2661. if (CC != CallingConv::C)
  2662. return false;
  2663. if (Subtarget->isCallingConvWin64(CC))
  2664. return false;
  2665. if (!Subtarget->is64Bit())
  2666. return false;
  2667. if (Subtarget->useSoftFloat())
  2668. return false;
  2669. // Only handle simple cases. i.e. Up to 6 i32/i64 scalar arguments.
  2670. unsigned GPRCnt = 0;
  2671. unsigned FPRCnt = 0;
  2672. for (auto const &Arg : F->args()) {
  2673. if (Arg.hasAttribute(Attribute::ByVal) ||
  2674. Arg.hasAttribute(Attribute::InReg) ||
  2675. Arg.hasAttribute(Attribute::StructRet) ||
  2676. Arg.hasAttribute(Attribute::SwiftSelf) ||
  2677. Arg.hasAttribute(Attribute::SwiftAsync) ||
  2678. Arg.hasAttribute(Attribute::SwiftError) ||
  2679. Arg.hasAttribute(Attribute::Nest))
  2680. return false;
  2681. Type *ArgTy = Arg.getType();
  2682. if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
  2683. return false;
  2684. EVT ArgVT = TLI.getValueType(DL, ArgTy);
  2685. if (!ArgVT.isSimple()) return false;
  2686. switch (ArgVT.getSimpleVT().SimpleTy) {
  2687. default: return false;
  2688. case MVT::i32:
  2689. case MVT::i64:
  2690. ++GPRCnt;
  2691. break;
  2692. case MVT::f32:
  2693. case MVT::f64:
  2694. if (!Subtarget->hasSSE1())
  2695. return false;
  2696. ++FPRCnt;
  2697. break;
  2698. }
  2699. if (GPRCnt > 6)
  2700. return false;
  2701. if (FPRCnt > 8)
  2702. return false;
  2703. }
  2704. static const MCPhysReg GPR32ArgRegs[] = {
  2705. X86::EDI, X86::ESI, X86::EDX, X86::ECX, X86::R8D, X86::R9D
  2706. };
  2707. static const MCPhysReg GPR64ArgRegs[] = {
  2708. X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8 , X86::R9
  2709. };
  2710. static const MCPhysReg XMMArgRegs[] = {
  2711. X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
  2712. X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
  2713. };
  2714. unsigned GPRIdx = 0;
  2715. unsigned FPRIdx = 0;
  2716. for (auto const &Arg : F->args()) {
  2717. MVT VT = TLI.getSimpleValueType(DL, Arg.getType());
  2718. const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
  2719. unsigned SrcReg;
  2720. switch (VT.SimpleTy) {
  2721. default: llvm_unreachable("Unexpected value type.");
  2722. case MVT::i32: SrcReg = GPR32ArgRegs[GPRIdx++]; break;
  2723. case MVT::i64: SrcReg = GPR64ArgRegs[GPRIdx++]; break;
  2724. case MVT::f32: LLVM_FALLTHROUGH;
  2725. case MVT::f64: SrcReg = XMMArgRegs[FPRIdx++]; break;
  2726. }
  2727. Register DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
  2728. // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
  2729. // Without this, EmitLiveInCopies may eliminate the livein if its only
  2730. // use is a bitcast (which isn't turned into an instruction).
  2731. Register ResultReg = createResultReg(RC);
  2732. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2733. TII.get(TargetOpcode::COPY), ResultReg)
  2734. .addReg(DstReg, getKillRegState(true));
  2735. updateValueMap(&Arg, ResultReg);
  2736. }
  2737. return true;
  2738. }
  2739. static unsigned computeBytesPoppedByCalleeForSRet(const X86Subtarget *Subtarget,
  2740. CallingConv::ID CC,
  2741. const CallBase *CB) {
  2742. if (Subtarget->is64Bit())
  2743. return 0;
  2744. if (Subtarget->getTargetTriple().isOSMSVCRT())
  2745. return 0;
  2746. if (CC == CallingConv::Fast || CC == CallingConv::GHC ||
  2747. CC == CallingConv::HiPE || CC == CallingConv::Tail ||
  2748. CC == CallingConv::SwiftTail)
  2749. return 0;
  2750. if (CB)
  2751. if (CB->arg_empty() || !CB->paramHasAttr(0, Attribute::StructRet) ||
  2752. CB->paramHasAttr(0, Attribute::InReg) || Subtarget->isTargetMCU())
  2753. return 0;
  2754. return 4;
  2755. }
  2756. bool X86FastISel::fastLowerCall(CallLoweringInfo &CLI) {
  2757. auto &OutVals = CLI.OutVals;
  2758. auto &OutFlags = CLI.OutFlags;
  2759. auto &OutRegs = CLI.OutRegs;
  2760. auto &Ins = CLI.Ins;
  2761. auto &InRegs = CLI.InRegs;
  2762. CallingConv::ID CC = CLI.CallConv;
  2763. bool &IsTailCall = CLI.IsTailCall;
  2764. bool IsVarArg = CLI.IsVarArg;
  2765. const Value *Callee = CLI.Callee;
  2766. MCSymbol *Symbol = CLI.Symbol;
  2767. const auto *CB = CLI.CB;
  2768. bool Is64Bit = Subtarget->is64Bit();
  2769. bool IsWin64 = Subtarget->isCallingConvWin64(CC);
  2770. // Call / invoke instructions with NoCfCheck attribute require special
  2771. // handling.
  2772. if (CB && CB->doesNoCfCheck())
  2773. return false;
  2774. // Functions with no_caller_saved_registers that need special handling.
  2775. if ((CB && isa<CallInst>(CB) && CB->hasFnAttr("no_caller_saved_registers")))
  2776. return false;
  2777. // Functions with no_callee_saved_registers that need special handling.
  2778. if ((CB && CB->hasFnAttr("no_callee_saved_registers")))
  2779. return false;
  2780. // Functions using thunks for indirect calls need to use SDISel.
  2781. if (Subtarget->useIndirectThunkCalls())
  2782. return false;
  2783. // Handle only C, fastcc, and webkit_js calling conventions for now.
  2784. switch (CC) {
  2785. default: return false;
  2786. case CallingConv::C:
  2787. case CallingConv::Fast:
  2788. case CallingConv::Tail:
  2789. case CallingConv::WebKit_JS:
  2790. case CallingConv::Swift:
  2791. case CallingConv::SwiftTail:
  2792. case CallingConv::X86_FastCall:
  2793. case CallingConv::X86_StdCall:
  2794. case CallingConv::X86_ThisCall:
  2795. case CallingConv::Win64:
  2796. case CallingConv::X86_64_SysV:
  2797. case CallingConv::CFGuard_Check:
  2798. break;
  2799. }
  2800. // Allow SelectionDAG isel to handle tail calls.
  2801. if (IsTailCall)
  2802. return false;
  2803. // fastcc with -tailcallopt is intended to provide a guaranteed
  2804. // tail call optimization. Fastisel doesn't know how to do that.
  2805. if ((CC == CallingConv::Fast && TM.Options.GuaranteedTailCallOpt) ||
  2806. CC == CallingConv::Tail || CC == CallingConv::SwiftTail)
  2807. return false;
  2808. // Don't know how to handle Win64 varargs yet. Nothing special needed for
  2809. // x86-32. Special handling for x86-64 is implemented.
  2810. if (IsVarArg && IsWin64)
  2811. return false;
  2812. // Don't know about inalloca yet.
  2813. if (CLI.CB && CLI.CB->hasInAllocaArgument())
  2814. return false;
  2815. for (auto Flag : CLI.OutFlags)
  2816. if (Flag.isSwiftError() || Flag.isPreallocated())
  2817. return false;
  2818. SmallVector<MVT, 16> OutVTs;
  2819. SmallVector<unsigned, 16> ArgRegs;
  2820. // If this is a constant i1/i8/i16 argument, promote to i32 to avoid an extra
  2821. // instruction. This is safe because it is common to all FastISel supported
  2822. // calling conventions on x86.
  2823. for (int i = 0, e = OutVals.size(); i != e; ++i) {
  2824. Value *&Val = OutVals[i];
  2825. ISD::ArgFlagsTy Flags = OutFlags[i];
  2826. if (auto *CI = dyn_cast<ConstantInt>(Val)) {
  2827. if (CI->getBitWidth() < 32) {
  2828. if (Flags.isSExt())
  2829. Val = ConstantExpr::getSExt(CI, Type::getInt32Ty(CI->getContext()));
  2830. else
  2831. Val = ConstantExpr::getZExt(CI, Type::getInt32Ty(CI->getContext()));
  2832. }
  2833. }
  2834. // Passing bools around ends up doing a trunc to i1 and passing it.
  2835. // Codegen this as an argument + "and 1".
  2836. MVT VT;
  2837. auto *TI = dyn_cast<TruncInst>(Val);
  2838. unsigned ResultReg;
  2839. if (TI && TI->getType()->isIntegerTy(1) && CLI.CB &&
  2840. (TI->getParent() == CLI.CB->getParent()) && TI->hasOneUse()) {
  2841. Value *PrevVal = TI->getOperand(0);
  2842. ResultReg = getRegForValue(PrevVal);
  2843. if (!ResultReg)
  2844. return false;
  2845. if (!isTypeLegal(PrevVal->getType(), VT))
  2846. return false;
  2847. ResultReg = fastEmit_ri(VT, VT, ISD::AND, ResultReg, 1);
  2848. } else {
  2849. if (!isTypeLegal(Val->getType(), VT) ||
  2850. (VT.isVector() && VT.getVectorElementType() == MVT::i1))
  2851. return false;
  2852. ResultReg = getRegForValue(Val);
  2853. }
  2854. if (!ResultReg)
  2855. return false;
  2856. ArgRegs.push_back(ResultReg);
  2857. OutVTs.push_back(VT);
  2858. }
  2859. // Analyze operands of the call, assigning locations to each operand.
  2860. SmallVector<CCValAssign, 16> ArgLocs;
  2861. CCState CCInfo(CC, IsVarArg, *FuncInfo.MF, ArgLocs, CLI.RetTy->getContext());
  2862. // Allocate shadow area for Win64
  2863. if (IsWin64)
  2864. CCInfo.AllocateStack(32, Align(8));
  2865. CCInfo.AnalyzeCallOperands(OutVTs, OutFlags, CC_X86);
  2866. // Get a count of how many bytes are to be pushed on the stack.
  2867. unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
  2868. // Issue CALLSEQ_START
  2869. unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
  2870. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
  2871. .addImm(NumBytes).addImm(0).addImm(0);
  2872. // Walk the register/memloc assignments, inserting copies/loads.
  2873. const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
  2874. for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
  2875. CCValAssign const &VA = ArgLocs[i];
  2876. const Value *ArgVal = OutVals[VA.getValNo()];
  2877. MVT ArgVT = OutVTs[VA.getValNo()];
  2878. if (ArgVT == MVT::x86mmx)
  2879. return false;
  2880. unsigned ArgReg = ArgRegs[VA.getValNo()];
  2881. // Promote the value if needed.
  2882. switch (VA.getLocInfo()) {
  2883. case CCValAssign::Full: break;
  2884. case CCValAssign::SExt: {
  2885. assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
  2886. "Unexpected extend");
  2887. if (ArgVT == MVT::i1)
  2888. return false;
  2889. bool Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
  2890. ArgVT, ArgReg);
  2891. assert(Emitted && "Failed to emit a sext!"); (void)Emitted;
  2892. ArgVT = VA.getLocVT();
  2893. break;
  2894. }
  2895. case CCValAssign::ZExt: {
  2896. assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
  2897. "Unexpected extend");
  2898. // Handle zero-extension from i1 to i8, which is common.
  2899. if (ArgVT == MVT::i1) {
  2900. // Set the high bits to zero.
  2901. ArgReg = fastEmitZExtFromI1(MVT::i8, ArgReg);
  2902. ArgVT = MVT::i8;
  2903. if (ArgReg == 0)
  2904. return false;
  2905. }
  2906. bool Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
  2907. ArgVT, ArgReg);
  2908. assert(Emitted && "Failed to emit a zext!"); (void)Emitted;
  2909. ArgVT = VA.getLocVT();
  2910. break;
  2911. }
  2912. case CCValAssign::AExt: {
  2913. assert(VA.getLocVT().isInteger() && !VA.getLocVT().isVector() &&
  2914. "Unexpected extend");
  2915. bool Emitted = X86FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(), ArgReg,
  2916. ArgVT, ArgReg);
  2917. if (!Emitted)
  2918. Emitted = X86FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(), ArgReg,
  2919. ArgVT, ArgReg);
  2920. if (!Emitted)
  2921. Emitted = X86FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(), ArgReg,
  2922. ArgVT, ArgReg);
  2923. assert(Emitted && "Failed to emit a aext!"); (void)Emitted;
  2924. ArgVT = VA.getLocVT();
  2925. break;
  2926. }
  2927. case CCValAssign::BCvt: {
  2928. ArgReg = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, ArgReg);
  2929. assert(ArgReg && "Failed to emit a bitcast!");
  2930. ArgVT = VA.getLocVT();
  2931. break;
  2932. }
  2933. case CCValAssign::VExt:
  2934. // VExt has not been implemented, so this should be impossible to reach
  2935. // for now. However, fallback to Selection DAG isel once implemented.
  2936. return false;
  2937. case CCValAssign::AExtUpper:
  2938. case CCValAssign::SExtUpper:
  2939. case CCValAssign::ZExtUpper:
  2940. case CCValAssign::FPExt:
  2941. case CCValAssign::Trunc:
  2942. llvm_unreachable("Unexpected loc info!");
  2943. case CCValAssign::Indirect:
  2944. // FIXME: Indirect doesn't need extending, but fast-isel doesn't fully
  2945. // support this.
  2946. return false;
  2947. }
  2948. if (VA.isRegLoc()) {
  2949. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2950. TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
  2951. OutRegs.push_back(VA.getLocReg());
  2952. } else {
  2953. assert(VA.isMemLoc() && "Unknown value location!");
  2954. // Don't emit stores for undef values.
  2955. if (isa<UndefValue>(ArgVal))
  2956. continue;
  2957. unsigned LocMemOffset = VA.getLocMemOffset();
  2958. X86AddressMode AM;
  2959. AM.Base.Reg = RegInfo->getStackRegister();
  2960. AM.Disp = LocMemOffset;
  2961. ISD::ArgFlagsTy Flags = OutFlags[VA.getValNo()];
  2962. Align Alignment = DL.getABITypeAlign(ArgVal->getType());
  2963. MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
  2964. MachinePointerInfo::getStack(*FuncInfo.MF, LocMemOffset),
  2965. MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
  2966. if (Flags.isByVal()) {
  2967. X86AddressMode SrcAM;
  2968. SrcAM.Base.Reg = ArgReg;
  2969. if (!TryEmitSmallMemcpy(AM, SrcAM, Flags.getByValSize()))
  2970. return false;
  2971. } else if (isa<ConstantInt>(ArgVal) || isa<ConstantPointerNull>(ArgVal)) {
  2972. // If this is a really simple value, emit this with the Value* version
  2973. // of X86FastEmitStore. If it isn't simple, we don't want to do this,
  2974. // as it can cause us to reevaluate the argument.
  2975. if (!X86FastEmitStore(ArgVT, ArgVal, AM, MMO))
  2976. return false;
  2977. } else {
  2978. if (!X86FastEmitStore(ArgVT, ArgReg, AM, MMO))
  2979. return false;
  2980. }
  2981. }
  2982. }
  2983. // ELF / PIC requires GOT in the EBX register before function calls via PLT
  2984. // GOT pointer.
  2985. if (Subtarget->isPICStyleGOT()) {
  2986. unsigned Base = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
  2987. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  2988. TII.get(TargetOpcode::COPY), X86::EBX).addReg(Base);
  2989. }
  2990. if (Is64Bit && IsVarArg && !IsWin64) {
  2991. // From AMD64 ABI document:
  2992. // For calls that may call functions that use varargs or stdargs
  2993. // (prototype-less calls or calls to functions containing ellipsis (...) in
  2994. // the declaration) %al is used as hidden argument to specify the number
  2995. // of SSE registers used. The contents of %al do not need to match exactly
  2996. // the number of registers, but must be an ubound on the number of SSE
  2997. // registers used and is in the range 0 - 8 inclusive.
  2998. // Count the number of XMM registers allocated.
  2999. static const MCPhysReg XMMArgRegs[] = {
  3000. X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
  3001. X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
  3002. };
  3003. unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
  3004. assert((Subtarget->hasSSE1() || !NumXMMRegs)
  3005. && "SSE registers cannot be used when SSE is disabled");
  3006. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV8ri),
  3007. X86::AL).addImm(NumXMMRegs);
  3008. }
  3009. // Materialize callee address in a register. FIXME: GV address can be
  3010. // handled with a CALLpcrel32 instead.
  3011. X86AddressMode CalleeAM;
  3012. if (!X86SelectCallAddress(Callee, CalleeAM))
  3013. return false;
  3014. unsigned CalleeOp = 0;
  3015. const GlobalValue *GV = nullptr;
  3016. if (CalleeAM.GV != nullptr) {
  3017. GV = CalleeAM.GV;
  3018. } else if (CalleeAM.Base.Reg != 0) {
  3019. CalleeOp = CalleeAM.Base.Reg;
  3020. } else
  3021. return false;
  3022. // Issue the call.
  3023. MachineInstrBuilder MIB;
  3024. if (CalleeOp) {
  3025. // Register-indirect call.
  3026. unsigned CallOpc = Is64Bit ? X86::CALL64r : X86::CALL32r;
  3027. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc))
  3028. .addReg(CalleeOp);
  3029. } else {
  3030. // Direct call.
  3031. assert(GV && "Not a direct call");
  3032. // See if we need any target-specific flags on the GV operand.
  3033. unsigned char OpFlags = Subtarget->classifyGlobalFunctionReference(GV);
  3034. // This will be a direct call, or an indirect call through memory for
  3035. // NonLazyBind calls or dllimport calls.
  3036. bool NeedLoad = OpFlags == X86II::MO_DLLIMPORT ||
  3037. OpFlags == X86II::MO_GOTPCREL ||
  3038. OpFlags == X86II::MO_GOTPCREL_NORELAX ||
  3039. OpFlags == X86II::MO_COFFSTUB;
  3040. unsigned CallOpc = NeedLoad
  3041. ? (Is64Bit ? X86::CALL64m : X86::CALL32m)
  3042. : (Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32);
  3043. MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(CallOpc));
  3044. if (NeedLoad)
  3045. MIB.addReg(Is64Bit ? X86::RIP : 0).addImm(1).addReg(0);
  3046. if (Symbol)
  3047. MIB.addSym(Symbol, OpFlags);
  3048. else
  3049. MIB.addGlobalAddress(GV, 0, OpFlags);
  3050. if (NeedLoad)
  3051. MIB.addReg(0);
  3052. }
  3053. // Add a register mask operand representing the call-preserved registers.
  3054. // Proper defs for return values will be added by setPhysRegsDeadExcept().
  3055. MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
  3056. // Add an implicit use GOT pointer in EBX.
  3057. if (Subtarget->isPICStyleGOT())
  3058. MIB.addReg(X86::EBX, RegState::Implicit);
  3059. if (Is64Bit && IsVarArg && !IsWin64)
  3060. MIB.addReg(X86::AL, RegState::Implicit);
  3061. // Add implicit physical register uses to the call.
  3062. for (auto Reg : OutRegs)
  3063. MIB.addReg(Reg, RegState::Implicit);
  3064. // Issue CALLSEQ_END
  3065. unsigned NumBytesForCalleeToPop =
  3066. X86::isCalleePop(CC, Subtarget->is64Bit(), IsVarArg,
  3067. TM.Options.GuaranteedTailCallOpt)
  3068. ? NumBytes // Callee pops everything.
  3069. : computeBytesPoppedByCalleeForSRet(Subtarget, CC, CLI.CB);
  3070. unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
  3071. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
  3072. .addImm(NumBytes).addImm(NumBytesForCalleeToPop);
  3073. // Now handle call return values.
  3074. SmallVector<CCValAssign, 16> RVLocs;
  3075. CCState CCRetInfo(CC, IsVarArg, *FuncInfo.MF, RVLocs,
  3076. CLI.RetTy->getContext());
  3077. CCRetInfo.AnalyzeCallResult(Ins, RetCC_X86);
  3078. // Copy all of the result registers out of their specified physreg.
  3079. Register ResultReg = FuncInfo.CreateRegs(CLI.RetTy);
  3080. for (unsigned i = 0; i != RVLocs.size(); ++i) {
  3081. CCValAssign &VA = RVLocs[i];
  3082. EVT CopyVT = VA.getValVT();
  3083. unsigned CopyReg = ResultReg + i;
  3084. Register SrcReg = VA.getLocReg();
  3085. // If this is x86-64, and we disabled SSE, we can't return FP values
  3086. if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
  3087. ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
  3088. report_fatal_error("SSE register return with SSE disabled");
  3089. }
  3090. // If we prefer to use the value in xmm registers, copy it out as f80 and
  3091. // use a truncate to move it from fp stack reg to xmm reg.
  3092. if ((SrcReg == X86::FP0 || SrcReg == X86::FP1) &&
  3093. isScalarFPTypeInSSEReg(VA.getValVT())) {
  3094. CopyVT = MVT::f80;
  3095. CopyReg = createResultReg(&X86::RFP80RegClass);
  3096. }
  3097. // Copy out the result.
  3098. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3099. TII.get(TargetOpcode::COPY), CopyReg).addReg(SrcReg);
  3100. InRegs.push_back(VA.getLocReg());
  3101. // Round the f80 to the right size, which also moves it to the appropriate
  3102. // xmm register. This is accomplished by storing the f80 value in memory
  3103. // and then loading it back.
  3104. if (CopyVT != VA.getValVT()) {
  3105. EVT ResVT = VA.getValVT();
  3106. unsigned Opc = ResVT == MVT::f32 ? X86::ST_Fp80m32 : X86::ST_Fp80m64;
  3107. unsigned MemSize = ResVT.getSizeInBits()/8;
  3108. int FI = MFI.CreateStackObject(MemSize, Align(MemSize), false);
  3109. addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3110. TII.get(Opc)), FI)
  3111. .addReg(CopyReg);
  3112. Opc = ResVT == MVT::f32 ? X86::MOVSSrm_alt : X86::MOVSDrm_alt;
  3113. addFrameReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3114. TII.get(Opc), ResultReg + i), FI);
  3115. }
  3116. }
  3117. CLI.ResultReg = ResultReg;
  3118. CLI.NumResultRegs = RVLocs.size();
  3119. CLI.Call = MIB;
  3120. return true;
  3121. }
  3122. bool
  3123. X86FastISel::fastSelectInstruction(const Instruction *I) {
  3124. switch (I->getOpcode()) {
  3125. default: break;
  3126. case Instruction::Load:
  3127. return X86SelectLoad(I);
  3128. case Instruction::Store:
  3129. return X86SelectStore(I);
  3130. case Instruction::Ret:
  3131. return X86SelectRet(I);
  3132. case Instruction::ICmp:
  3133. case Instruction::FCmp:
  3134. return X86SelectCmp(I);
  3135. case Instruction::ZExt:
  3136. return X86SelectZExt(I);
  3137. case Instruction::SExt:
  3138. return X86SelectSExt(I);
  3139. case Instruction::Br:
  3140. return X86SelectBranch(I);
  3141. case Instruction::LShr:
  3142. case Instruction::AShr:
  3143. case Instruction::Shl:
  3144. return X86SelectShift(I);
  3145. case Instruction::SDiv:
  3146. case Instruction::UDiv:
  3147. case Instruction::SRem:
  3148. case Instruction::URem:
  3149. return X86SelectDivRem(I);
  3150. case Instruction::Select:
  3151. return X86SelectSelect(I);
  3152. case Instruction::Trunc:
  3153. return X86SelectTrunc(I);
  3154. case Instruction::FPExt:
  3155. return X86SelectFPExt(I);
  3156. case Instruction::FPTrunc:
  3157. return X86SelectFPTrunc(I);
  3158. case Instruction::SIToFP:
  3159. return X86SelectSIToFP(I);
  3160. case Instruction::UIToFP:
  3161. return X86SelectUIToFP(I);
  3162. case Instruction::IntToPtr: // Deliberate fall-through.
  3163. case Instruction::PtrToInt: {
  3164. EVT SrcVT = TLI.getValueType(DL, I->getOperand(0)->getType());
  3165. EVT DstVT = TLI.getValueType(DL, I->getType());
  3166. if (DstVT.bitsGT(SrcVT))
  3167. return X86SelectZExt(I);
  3168. if (DstVT.bitsLT(SrcVT))
  3169. return X86SelectTrunc(I);
  3170. Register Reg = getRegForValue(I->getOperand(0));
  3171. if (Reg == 0) return false;
  3172. updateValueMap(I, Reg);
  3173. return true;
  3174. }
  3175. case Instruction::BitCast: {
  3176. // Select SSE2/AVX bitcasts between 128/256/512 bit vector types.
  3177. if (!Subtarget->hasSSE2())
  3178. return false;
  3179. MVT SrcVT, DstVT;
  3180. if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT) ||
  3181. !isTypeLegal(I->getType(), DstVT))
  3182. return false;
  3183. // Only allow vectors that use xmm/ymm/zmm.
  3184. if (!SrcVT.isVector() || !DstVT.isVector() ||
  3185. SrcVT.getVectorElementType() == MVT::i1 ||
  3186. DstVT.getVectorElementType() == MVT::i1)
  3187. return false;
  3188. Register Reg = getRegForValue(I->getOperand(0));
  3189. if (!Reg)
  3190. return false;
  3191. // Emit a reg-reg copy so we don't propagate cached known bits information
  3192. // with the wrong VT if we fall out of fast isel after selecting this.
  3193. const TargetRegisterClass *DstClass = TLI.getRegClassFor(DstVT);
  3194. Register ResultReg = createResultReg(DstClass);
  3195. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3196. TII.get(TargetOpcode::COPY), ResultReg).addReg(Reg);
  3197. updateValueMap(I, ResultReg);
  3198. return true;
  3199. }
  3200. }
  3201. return false;
  3202. }
  3203. unsigned X86FastISel::X86MaterializeInt(const ConstantInt *CI, MVT VT) {
  3204. if (VT > MVT::i64)
  3205. return 0;
  3206. uint64_t Imm = CI->getZExtValue();
  3207. if (Imm == 0) {
  3208. Register SrcReg = fastEmitInst_(X86::MOV32r0, &X86::GR32RegClass);
  3209. switch (VT.SimpleTy) {
  3210. default: llvm_unreachable("Unexpected value type");
  3211. case MVT::i1:
  3212. case MVT::i8:
  3213. return fastEmitInst_extractsubreg(MVT::i8, SrcReg, X86::sub_8bit);
  3214. case MVT::i16:
  3215. return fastEmitInst_extractsubreg(MVT::i16, SrcReg, X86::sub_16bit);
  3216. case MVT::i32:
  3217. return SrcReg;
  3218. case MVT::i64: {
  3219. Register ResultReg = createResultReg(&X86::GR64RegClass);
  3220. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3221. TII.get(TargetOpcode::SUBREG_TO_REG), ResultReg)
  3222. .addImm(0).addReg(SrcReg).addImm(X86::sub_32bit);
  3223. return ResultReg;
  3224. }
  3225. }
  3226. }
  3227. unsigned Opc = 0;
  3228. switch (VT.SimpleTy) {
  3229. default: llvm_unreachable("Unexpected value type");
  3230. case MVT::i1:
  3231. VT = MVT::i8;
  3232. LLVM_FALLTHROUGH;
  3233. case MVT::i8: Opc = X86::MOV8ri; break;
  3234. case MVT::i16: Opc = X86::MOV16ri; break;
  3235. case MVT::i32: Opc = X86::MOV32ri; break;
  3236. case MVT::i64: {
  3237. if (isUInt<32>(Imm))
  3238. Opc = X86::MOV32ri64;
  3239. else if (isInt<32>(Imm))
  3240. Opc = X86::MOV64ri32;
  3241. else
  3242. Opc = X86::MOV64ri;
  3243. break;
  3244. }
  3245. }
  3246. return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
  3247. }
  3248. unsigned X86FastISel::X86MaterializeFP(const ConstantFP *CFP, MVT VT) {
  3249. if (CFP->isNullValue())
  3250. return fastMaterializeFloatZero(CFP);
  3251. // Can't handle alternate code models yet.
  3252. CodeModel::Model CM = TM.getCodeModel();
  3253. if (CM != CodeModel::Small && CM != CodeModel::Large)
  3254. return 0;
  3255. // Get opcode and regclass of the output for the given load instruction.
  3256. unsigned Opc = 0;
  3257. bool HasAVX = Subtarget->hasAVX();
  3258. bool HasAVX512 = Subtarget->hasAVX512();
  3259. switch (VT.SimpleTy) {
  3260. default: return 0;
  3261. case MVT::f32:
  3262. if (X86ScalarSSEf32)
  3263. Opc = HasAVX512 ? X86::VMOVSSZrm_alt :
  3264. HasAVX ? X86::VMOVSSrm_alt :
  3265. X86::MOVSSrm_alt;
  3266. else
  3267. Opc = X86::LD_Fp32m;
  3268. break;
  3269. case MVT::f64:
  3270. if (X86ScalarSSEf64)
  3271. Opc = HasAVX512 ? X86::VMOVSDZrm_alt :
  3272. HasAVX ? X86::VMOVSDrm_alt :
  3273. X86::MOVSDrm_alt;
  3274. else
  3275. Opc = X86::LD_Fp64m;
  3276. break;
  3277. case MVT::f80:
  3278. // No f80 support yet.
  3279. return 0;
  3280. }
  3281. // MachineConstantPool wants an explicit alignment.
  3282. Align Alignment = DL.getPrefTypeAlign(CFP->getType());
  3283. // x86-32 PIC requires a PIC base register for constant pools.
  3284. unsigned PICBase = 0;
  3285. unsigned char OpFlag = Subtarget->classifyLocalReference(nullptr);
  3286. if (OpFlag == X86II::MO_PIC_BASE_OFFSET)
  3287. PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
  3288. else if (OpFlag == X86II::MO_GOTOFF)
  3289. PICBase = getInstrInfo()->getGlobalBaseReg(FuncInfo.MF);
  3290. else if (Subtarget->is64Bit() && TM.getCodeModel() == CodeModel::Small)
  3291. PICBase = X86::RIP;
  3292. // Create the load from the constant pool.
  3293. unsigned CPI = MCP.getConstantPoolIndex(CFP, Alignment);
  3294. Register ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy));
  3295. // Large code model only applies to 64-bit mode.
  3296. if (Subtarget->is64Bit() && CM == CodeModel::Large) {
  3297. Register AddrReg = createResultReg(&X86::GR64RegClass);
  3298. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
  3299. AddrReg)
  3300. .addConstantPoolIndex(CPI, 0, OpFlag);
  3301. MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3302. TII.get(Opc), ResultReg);
  3303. addRegReg(MIB, AddrReg, false, PICBase, false);
  3304. MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
  3305. MachinePointerInfo::getConstantPool(*FuncInfo.MF),
  3306. MachineMemOperand::MOLoad, DL.getPointerSize(), Alignment);
  3307. MIB->addMemOperand(*FuncInfo.MF, MMO);
  3308. return ResultReg;
  3309. }
  3310. addConstantPoolReference(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3311. TII.get(Opc), ResultReg),
  3312. CPI, PICBase, OpFlag);
  3313. return ResultReg;
  3314. }
  3315. unsigned X86FastISel::X86MaterializeGV(const GlobalValue *GV, MVT VT) {
  3316. // Can't handle alternate code models yet.
  3317. if (TM.getCodeModel() != CodeModel::Small)
  3318. return 0;
  3319. // Materialize addresses with LEA/MOV instructions.
  3320. X86AddressMode AM;
  3321. if (X86SelectAddress(GV, AM)) {
  3322. // If the expression is just a basereg, then we're done, otherwise we need
  3323. // to emit an LEA.
  3324. if (AM.BaseType == X86AddressMode::RegBase &&
  3325. AM.IndexReg == 0 && AM.Disp == 0 && AM.GV == nullptr)
  3326. return AM.Base.Reg;
  3327. Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
  3328. if (TM.getRelocationModel() == Reloc::Static &&
  3329. TLI.getPointerTy(DL) == MVT::i64) {
  3330. // The displacement code could be more than 32 bits away so we need to use
  3331. // an instruction with a 64 bit immediate
  3332. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(X86::MOV64ri),
  3333. ResultReg)
  3334. .addGlobalAddress(GV);
  3335. } else {
  3336. unsigned Opc =
  3337. TLI.getPointerTy(DL) == MVT::i32
  3338. ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
  3339. : X86::LEA64r;
  3340. addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3341. TII.get(Opc), ResultReg), AM);
  3342. }
  3343. return ResultReg;
  3344. }
  3345. return 0;
  3346. }
  3347. unsigned X86FastISel::fastMaterializeConstant(const Constant *C) {
  3348. EVT CEVT = TLI.getValueType(DL, C->getType(), true);
  3349. // Only handle simple types.
  3350. if (!CEVT.isSimple())
  3351. return 0;
  3352. MVT VT = CEVT.getSimpleVT();
  3353. if (const auto *CI = dyn_cast<ConstantInt>(C))
  3354. return X86MaterializeInt(CI, VT);
  3355. if (const auto *CFP = dyn_cast<ConstantFP>(C))
  3356. return X86MaterializeFP(CFP, VT);
  3357. if (const auto *GV = dyn_cast<GlobalValue>(C))
  3358. return X86MaterializeGV(GV, VT);
  3359. if (isa<UndefValue>(C)) {
  3360. unsigned Opc = 0;
  3361. switch (VT.SimpleTy) {
  3362. default:
  3363. break;
  3364. case MVT::f32:
  3365. if (!X86ScalarSSEf32)
  3366. Opc = X86::LD_Fp032;
  3367. break;
  3368. case MVT::f64:
  3369. if (!X86ScalarSSEf64)
  3370. Opc = X86::LD_Fp064;
  3371. break;
  3372. case MVT::f80:
  3373. Opc = X86::LD_Fp080;
  3374. break;
  3375. }
  3376. if (Opc) {
  3377. Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
  3378. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
  3379. ResultReg);
  3380. return ResultReg;
  3381. }
  3382. }
  3383. return 0;
  3384. }
  3385. unsigned X86FastISel::fastMaterializeAlloca(const AllocaInst *C) {
  3386. // Fail on dynamic allocas. At this point, getRegForValue has already
  3387. // checked its CSE maps, so if we're here trying to handle a dynamic
  3388. // alloca, we're not going to succeed. X86SelectAddress has a
  3389. // check for dynamic allocas, because it's called directly from
  3390. // various places, but targetMaterializeAlloca also needs a check
  3391. // in order to avoid recursion between getRegForValue,
  3392. // X86SelectAddrss, and targetMaterializeAlloca.
  3393. if (!FuncInfo.StaticAllocaMap.count(C))
  3394. return 0;
  3395. assert(C->isStaticAlloca() && "dynamic alloca in the static alloca map?");
  3396. X86AddressMode AM;
  3397. if (!X86SelectAddress(C, AM))
  3398. return 0;
  3399. unsigned Opc =
  3400. TLI.getPointerTy(DL) == MVT::i32
  3401. ? (Subtarget->isTarget64BitILP32() ? X86::LEA64_32r : X86::LEA32r)
  3402. : X86::LEA64r;
  3403. const TargetRegisterClass *RC = TLI.getRegClassFor(TLI.getPointerTy(DL));
  3404. Register ResultReg = createResultReg(RC);
  3405. addFullAddress(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3406. TII.get(Opc), ResultReg), AM);
  3407. return ResultReg;
  3408. }
  3409. unsigned X86FastISel::fastMaterializeFloatZero(const ConstantFP *CF) {
  3410. MVT VT;
  3411. if (!isTypeLegal(CF->getType(), VT))
  3412. return 0;
  3413. // Get opcode and regclass for the given zero.
  3414. bool HasAVX512 = Subtarget->hasAVX512();
  3415. unsigned Opc = 0;
  3416. switch (VT.SimpleTy) {
  3417. default: return 0;
  3418. case MVT::f32:
  3419. if (X86ScalarSSEf32)
  3420. Opc = HasAVX512 ? X86::AVX512_FsFLD0SS : X86::FsFLD0SS;
  3421. else
  3422. Opc = X86::LD_Fp032;
  3423. break;
  3424. case MVT::f64:
  3425. if (X86ScalarSSEf64)
  3426. Opc = HasAVX512 ? X86::AVX512_FsFLD0SD : X86::FsFLD0SD;
  3427. else
  3428. Opc = X86::LD_Fp064;
  3429. break;
  3430. case MVT::f80:
  3431. // No f80 support yet.
  3432. return 0;
  3433. }
  3434. Register ResultReg = createResultReg(TLI.getRegClassFor(VT));
  3435. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg);
  3436. return ResultReg;
  3437. }
  3438. bool X86FastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
  3439. const LoadInst *LI) {
  3440. const Value *Ptr = LI->getPointerOperand();
  3441. X86AddressMode AM;
  3442. if (!X86SelectAddress(Ptr, AM))
  3443. return false;
  3444. const X86InstrInfo &XII = (const X86InstrInfo &)TII;
  3445. unsigned Size = DL.getTypeAllocSize(LI->getType());
  3446. SmallVector<MachineOperand, 8> AddrOps;
  3447. AM.getFullAddress(AddrOps);
  3448. MachineInstr *Result = XII.foldMemoryOperandImpl(
  3449. *FuncInfo.MF, *MI, OpNo, AddrOps, FuncInfo.InsertPt, Size, LI->getAlign(),
  3450. /*AllowCommute=*/true);
  3451. if (!Result)
  3452. return false;
  3453. // The index register could be in the wrong register class. Unfortunately,
  3454. // foldMemoryOperandImpl could have commuted the instruction so its not enough
  3455. // to just look at OpNo + the offset to the index reg. We actually need to
  3456. // scan the instruction to find the index reg and see if its the correct reg
  3457. // class.
  3458. unsigned OperandNo = 0;
  3459. for (MachineInstr::mop_iterator I = Result->operands_begin(),
  3460. E = Result->operands_end(); I != E; ++I, ++OperandNo) {
  3461. MachineOperand &MO = *I;
  3462. if (!MO.isReg() || MO.isDef() || MO.getReg() != AM.IndexReg)
  3463. continue;
  3464. // Found the index reg, now try to rewrite it.
  3465. Register IndexReg = constrainOperandRegClass(Result->getDesc(),
  3466. MO.getReg(), OperandNo);
  3467. if (IndexReg == MO.getReg())
  3468. continue;
  3469. MO.setReg(IndexReg);
  3470. }
  3471. Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
  3472. Result->cloneInstrSymbols(*FuncInfo.MF, *MI);
  3473. MachineBasicBlock::iterator I(MI);
  3474. removeDeadCode(I, std::next(I));
  3475. return true;
  3476. }
  3477. unsigned X86FastISel::fastEmitInst_rrrr(unsigned MachineInstOpcode,
  3478. const TargetRegisterClass *RC,
  3479. unsigned Op0, unsigned Op1,
  3480. unsigned Op2, unsigned Op3) {
  3481. const MCInstrDesc &II = TII.get(MachineInstOpcode);
  3482. Register ResultReg = createResultReg(RC);
  3483. Op0 = constrainOperandRegClass(II, Op0, II.getNumDefs());
  3484. Op1 = constrainOperandRegClass(II, Op1, II.getNumDefs() + 1);
  3485. Op2 = constrainOperandRegClass(II, Op2, II.getNumDefs() + 2);
  3486. Op3 = constrainOperandRegClass(II, Op3, II.getNumDefs() + 3);
  3487. if (II.getNumDefs() >= 1)
  3488. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
  3489. .addReg(Op0)
  3490. .addReg(Op1)
  3491. .addReg(Op2)
  3492. .addReg(Op3);
  3493. else {
  3494. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
  3495. .addReg(Op0)
  3496. .addReg(Op1)
  3497. .addReg(Op2)
  3498. .addReg(Op3);
  3499. BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
  3500. TII.get(TargetOpcode::COPY), ResultReg).addReg(II.ImplicitDefs[0]);
  3501. }
  3502. return ResultReg;
  3503. }
  3504. namespace llvm {
  3505. FastISel *X86::createFastISel(FunctionLoweringInfo &funcInfo,
  3506. const TargetLibraryInfo *libInfo) {
  3507. return new X86FastISel(funcInfo, libInfo);
  3508. }
  3509. }