1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86.h"
16 #include "X86MachineFunctionInfo.h"
17 #include "X86RegisterInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/ConstantRange.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/KnownBits.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include <stdint.h>
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "x86-isel"
41 
42 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
43 
44 static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),
45     cl::desc("Enable setting constant bits to reduce size of mask immediates"),
46     cl::Hidden);
47 
48 //===----------------------------------------------------------------------===//
49 //                      Pattern Matcher Implementation
50 //===----------------------------------------------------------------------===//
51 
52 namespace {
53   /// This corresponds to X86AddressMode, but uses SDValue's instead of register
54   /// numbers for the leaves of the matched tree.
55   struct X86ISelAddressMode {
56     enum {
57       RegBase,
58       FrameIndexBase
59     } BaseType;
60 
61     // This is really a union, discriminated by BaseType!
62     SDValue Base_Reg;
63     int Base_FrameIndex;
64 
65     unsigned Scale;
66     SDValue IndexReg;
67     int32_t Disp;
68     SDValue Segment;
69     const GlobalValue *GV;
70     const Constant *CP;
71     const BlockAddress *BlockAddr;
72     const char *ES;
73     MCSymbol *MCSym;
74     int JT;
75     unsigned Align;    // CP alignment.
76     unsigned char SymbolFlags;  // X86II::MO_*
77 
78     X86ISelAddressMode()
79         : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
80           Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
81           MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
82 
83     bool hasSymbolicDisplacement() const {
84       return GV != nullptr || CP != nullptr || ES != nullptr ||
85              MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
86     }
87 
88     bool hasBaseOrIndexReg() const {
89       return BaseType == FrameIndexBase ||
90              IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
91     }
92 
93     /// Return true if this addressing mode is already RIP-relative.
94     bool isRIPRelative() const {
95       if (BaseType != RegBase) return false;
96       if (RegisterSDNode *RegNode =
97             dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
98         return RegNode->getReg() == X86::RIP;
99       return false;
100     }
101 
102     void setBaseReg(SDValue Reg) {
103       BaseType = RegBase;
104       Base_Reg = Reg;
105     }
106 
107 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
108     void dump(SelectionDAG *DAG = nullptr) {
109       dbgs() << "X86ISelAddressMode " << this << '\n';
110       dbgs() << "Base_Reg ";
111       if (Base_Reg.getNode())
112         Base_Reg.getNode()->dump(DAG);
113       else
114         dbgs() << "nul\n";
115       if (BaseType == FrameIndexBase)
116         dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
117       dbgs() << " Scale " << Scale << '\n'
118              << "IndexReg ";
119       if (IndexReg.getNode())
120         IndexReg.getNode()->dump(DAG);
121       else
122         dbgs() << "nul\n";
123       dbgs() << " Disp " << Disp << '\n'
124              << "GV ";
125       if (GV)
126         GV->dump();
127       else
128         dbgs() << "nul";
129       dbgs() << " CP ";
130       if (CP)
131         CP->dump();
132       else
133         dbgs() << "nul";
134       dbgs() << '\n'
135              << "ES ";
136       if (ES)
137         dbgs() << ES;
138       else
139         dbgs() << "nul";
140       dbgs() << " MCSym ";
141       if (MCSym)
142         dbgs() << MCSym;
143       else
144         dbgs() << "nul";
145       dbgs() << " JT" << JT << " Align" << Align << '\n';
146     }
147 #endif
148   };
149 }
150 
151 namespace {
152   //===--------------------------------------------------------------------===//
153   /// ISel - X86-specific code to select X86 machine instructions for
154   /// SelectionDAG operations.
155   ///
156   class X86DAGToDAGISel final : public SelectionDAGISel {
157     /// Keep a pointer to the X86Subtarget around so that we can
158     /// make the right decision when generating code for different targets.
159     const X86Subtarget *Subtarget;
160 
161     /// If true, selector should try to optimize for code size instead of
162     /// performance.
163     bool OptForSize;
164 
165     /// If true, selector should try to optimize for minimum code size.
166     bool OptForMinSize;
167 
168     /// Disable direct TLS access through segment registers.
169     bool IndirectTlsSegRefs;
170 
171   public:
172     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
173         : SelectionDAGISel(tm, OptLevel), OptForSize(false),
174           OptForMinSize(false) {}
175 
176     StringRef getPassName() const override {
177       return "X86 DAG->DAG Instruction Selection";
178     }
179 
180     bool runOnMachineFunction(MachineFunction &MF) override {
181       // Reset the subtarget each time through.
182       Subtarget = &MF.getSubtarget<X86Subtarget>();
183       IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(
184                              "indirect-tls-seg-refs");
185       SelectionDAGISel::runOnMachineFunction(MF);
186       return true;
187     }
188 
189     void EmitFunctionEntryCode() override;
190 
191     bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
192 
193     void PreprocessISelDAG() override;
194     void PostprocessISelDAG() override;
195 
196 // Include the pieces autogenerated from the target description.
197 #include "X86GenDAGISel.inc"
198 
199   private:
200     void Select(SDNode *N) override;
201 
202     bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
203     bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
204     bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
205     bool matchAddress(SDValue N, X86ISelAddressMode &AM);
206     bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
207     bool matchAdd(SDValue N, X86ISelAddressMode &AM, unsigned Depth);
208     bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
209                                  unsigned Depth);
210     bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
211     bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
212                     SDValue &Scale, SDValue &Index, SDValue &Disp,
213                     SDValue &Segment);
214     bool selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
215                           SDValue &Scale, SDValue &Index, SDValue &Disp,
216                           SDValue &Segment);
217     bool selectMOV64Imm32(SDValue N, SDValue &Imm);
218     bool selectLEAAddr(SDValue N, SDValue &Base,
219                        SDValue &Scale, SDValue &Index, SDValue &Disp,
220                        SDValue &Segment);
221     bool selectLEA64_32Addr(SDValue N, SDValue &Base,
222                             SDValue &Scale, SDValue &Index, SDValue &Disp,
223                             SDValue &Segment);
224     bool selectTLSADDRAddr(SDValue N, SDValue &Base,
225                            SDValue &Scale, SDValue &Index, SDValue &Disp,
226                            SDValue &Segment);
227     bool selectScalarSSELoad(SDNode *Root, SDNode *Parent, SDValue N,
228                              SDValue &Base, SDValue &Scale,
229                              SDValue &Index, SDValue &Disp,
230                              SDValue &Segment,
231                              SDValue &NodeWithChain);
232     bool selectRelocImm(SDValue N, SDValue &Op);
233 
234     bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
235                      SDValue &Base, SDValue &Scale,
236                      SDValue &Index, SDValue &Disp,
237                      SDValue &Segment);
238 
239     // Convenience method where P is also root.
240     bool tryFoldLoad(SDNode *P, SDValue N,
241                      SDValue &Base, SDValue &Scale,
242                      SDValue &Index, SDValue &Disp,
243                      SDValue &Segment) {
244       return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
245     }
246 
247     /// Implement addressing mode selection for inline asm expressions.
248     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
249                                       unsigned ConstraintID,
250                                       std::vector<SDValue> &OutOps) override;
251 
252     void emitSpecialCodeForMain();
253 
254     inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
255                                    SDValue &Base, SDValue &Scale,
256                                    SDValue &Index, SDValue &Disp,
257                                    SDValue &Segment) {
258       Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
259                  ? CurDAG->getTargetFrameIndex(
260                        AM.Base_FrameIndex,
261                        TLI->getPointerTy(CurDAG->getDataLayout()))
262                  : AM.Base_Reg;
263       Scale = getI8Imm(AM.Scale, DL);
264       Index = AM.IndexReg;
265       // These are 32-bit even in 64-bit mode since RIP-relative offset
266       // is 32-bit.
267       if (AM.GV)
268         Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
269                                               MVT::i32, AM.Disp,
270                                               AM.SymbolFlags);
271       else if (AM.CP)
272         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
273                                              AM.Align, AM.Disp, AM.SymbolFlags);
274       else if (AM.ES) {
275         assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
276         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
277       } else if (AM.MCSym) {
278         assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
279         assert(AM.SymbolFlags == 0 && "oo");
280         Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
281       } else if (AM.JT != -1) {
282         assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
283         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
284       } else if (AM.BlockAddr)
285         Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
286                                              AM.SymbolFlags);
287       else
288         Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
289 
290       if (AM.Segment.getNode())
291         Segment = AM.Segment;
292       else
293         Segment = CurDAG->getRegister(0, MVT::i32);
294     }
295 
296     // Utility function to determine whether we should avoid selecting
297     // immediate forms of instructions for better code size or not.
298     // At a high level, we'd like to avoid such instructions when
299     // we have similar constants used within the same basic block
300     // that can be kept in a register.
301     //
302     bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
303       uint32_t UseCount = 0;
304 
305       // Do not want to hoist if we're not optimizing for size.
306       // TODO: We'd like to remove this restriction.
307       // See the comment in X86InstrInfo.td for more info.
308       if (!OptForSize)
309         return false;
310 
311       // Walk all the users of the immediate.
312       for (SDNode::use_iterator UI = N->use_begin(),
313            UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
314 
315         SDNode *User = *UI;
316 
317         // This user is already selected. Count it as a legitimate use and
318         // move on.
319         if (User->isMachineOpcode()) {
320           UseCount++;
321           continue;
322         }
323 
324         // We want to count stores of immediates as real uses.
325         if (User->getOpcode() == ISD::STORE &&
326             User->getOperand(1).getNode() == N) {
327           UseCount++;
328           continue;
329         }
330 
331         // We don't currently match users that have > 2 operands (except
332         // for stores, which are handled above)
333         // Those instruction won't match in ISEL, for now, and would
334         // be counted incorrectly.
335         // This may change in the future as we add additional instruction
336         // types.
337         if (User->getNumOperands() != 2)
338           continue;
339 
340         // Immediates that are used for offsets as part of stack
341         // manipulation should be left alone. These are typically
342         // used to indicate SP offsets for argument passing and
343         // will get pulled into stores/pushes (implicitly).
344         if (User->getOpcode() == X86ISD::ADD ||
345             User->getOpcode() == ISD::ADD    ||
346             User->getOpcode() == X86ISD::SUB ||
347             User->getOpcode() == ISD::SUB) {
348 
349           // Find the other operand of the add/sub.
350           SDValue OtherOp = User->getOperand(0);
351           if (OtherOp.getNode() == N)
352             OtherOp = User->getOperand(1);
353 
354           // Don't count if the other operand is SP.
355           RegisterSDNode *RegNode;
356           if (OtherOp->getOpcode() == ISD::CopyFromReg &&
357               (RegNode = dyn_cast_or_null<RegisterSDNode>(
358                  OtherOp->getOperand(1).getNode())))
359             if ((RegNode->getReg() == X86::ESP) ||
360                 (RegNode->getReg() == X86::RSP))
361               continue;
362         }
363 
364         // ... otherwise, count this and move on.
365         UseCount++;
366       }
367 
368       // If we have more than 1 use, then recommend for hoisting.
369       return (UseCount > 1);
370     }
371 
372     /// Return a target constant with the specified value of type i8.
373     inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
374       return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
375     }
376 
377     /// Return a target constant with the specified value, of type i32.
378     inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
379       return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
380     }
381 
382     /// Return a target constant with the specified value, of type i64.
383     inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
384       return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
385     }
386 
387     SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
388                                         const SDLoc &DL) {
389       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
390       uint64_t Index = N->getConstantOperandVal(1);
391       MVT VecVT = N->getOperand(0).getSimpleValueType();
392       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
393     }
394 
395     SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
396                                       const SDLoc &DL) {
397       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
398       uint64_t Index = N->getConstantOperandVal(2);
399       MVT VecVT = N->getSimpleValueType(0);
400       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
401     }
402 
403     /// Return an SDNode that returns the value of the global base register.
404     /// Output instructions required to initialize the global base register,
405     /// if necessary.
406     SDNode *getGlobalBaseReg();
407 
408     /// Return a reference to the TargetMachine, casted to the target-specific
409     /// type.
410     const X86TargetMachine &getTargetMachine() const {
411       return static_cast<const X86TargetMachine &>(TM);
412     }
413 
414     /// Return a reference to the TargetInstrInfo, casted to the target-specific
415     /// type.
416     const X86InstrInfo *getInstrInfo() const {
417       return Subtarget->getInstrInfo();
418     }
419 
420     /// Address-mode matching performs shift-of-and to and-of-shift
421     /// reassociation in order to expose more scaled addressing
422     /// opportunities.
423     bool ComplexPatternFuncMutatesDAG() const override {
424       return true;
425     }
426 
427     bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
428 
429     /// Returns whether this is a relocatable immediate in the range
430     /// [-2^Width .. 2^Width-1].
431     template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
432       if (auto *CN = dyn_cast<ConstantSDNode>(N))
433         return isInt<Width>(CN->getSExtValue());
434       return isSExtAbsoluteSymbolRef(Width, N);
435     }
436 
437     // Indicates we should prefer to use a non-temporal load for this load.
438     bool useNonTemporalLoad(LoadSDNode *N) const {
439       if (!N->isNonTemporal())
440         return false;
441 
442       unsigned StoreSize = N->getMemoryVT().getStoreSize();
443 
444       if (N->getAlignment() < StoreSize)
445         return false;
446 
447       switch (StoreSize) {
448       default: llvm_unreachable("Unsupported store size");
449       case 4:
450       case 8:
451         return false;
452       case 16:
453         return Subtarget->hasSSE41();
454       case 32:
455         return Subtarget->hasAVX2();
456       case 64:
457         return Subtarget->hasAVX512();
458       }
459     }
460 
461     bool foldLoadStoreIntoMemOperand(SDNode *Node);
462     MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);
463     bool matchBitExtract(SDNode *Node);
464     bool shrinkAndImmediate(SDNode *N);
465     bool isMaskZeroExtended(SDNode *N) const;
466     bool tryShiftAmountMod(SDNode *N);
467 
468     MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
469                                 const SDLoc &dl, MVT VT, SDNode *Node);
470     MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
471                                 const SDLoc &dl, MVT VT, SDNode *Node,
472                                 SDValue &InFlag);
473 
474     bool tryOptimizeRem8Extend(SDNode *N);
475 
476     bool onlyUsesZeroFlag(SDValue Flags) const;
477     bool hasNoSignFlagUses(SDValue Flags) const;
478     bool hasNoCarryFlagUses(SDValue Flags) const;
479   };
480 }
481 
482 
483 // Returns true if this masked compare can be implemented legally with this
484 // type.
485 static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
486   unsigned Opcode = N->getOpcode();
487   if (Opcode == X86ISD::CMPM || Opcode == ISD::SETCC ||
488       Opcode == X86ISD::CMPM_RND || Opcode == X86ISD::VFPCLASS) {
489     // We can get 256-bit 8 element types here without VLX being enabled. When
490     // this happens we will use 512-bit operations and the mask will not be
491     // zero extended.
492     EVT OpVT = N->getOperand(0).getValueType();
493     if (OpVT.is256BitVector() || OpVT.is128BitVector())
494       return Subtarget->hasVLX();
495 
496     return true;
497   }
498   // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
499   if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
500       Opcode == X86ISD::FSETCCM_RND)
501     return true;
502 
503   return false;
504 }
505 
506 // Returns true if we can assume the writer of the mask has zero extended it
507 // for us.
508 bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
509   // If this is an AND, check if we have a compare on either side. As long as
510   // one side guarantees the mask is zero extended, the AND will preserve those
511   // zeros.
512   if (N->getOpcode() == ISD::AND)
513     return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
514            isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
515 
516   return isLegalMaskCompare(N, Subtarget);
517 }
518 
519 bool
520 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
521   if (OptLevel == CodeGenOpt::None) return false;
522 
523   if (!N.hasOneUse())
524     return false;
525 
526   if (N.getOpcode() != ISD::LOAD)
527     return true;
528 
529   // Don't fold non-temporal loads if we have an instruction for them.
530   if (useNonTemporalLoad(cast<LoadSDNode>(N)))
531     return false;
532 
533   // If N is a load, do additional profitability checks.
534   if (U == Root) {
535     switch (U->getOpcode()) {
536     default: break;
537     case X86ISD::ADD:
538     case X86ISD::ADC:
539     case X86ISD::SUB:
540     case X86ISD::SBB:
541     case X86ISD::AND:
542     case X86ISD::XOR:
543     case X86ISD::OR:
544     case ISD::ADD:
545     case ISD::ADDCARRY:
546     case ISD::AND:
547     case ISD::OR:
548     case ISD::XOR: {
549       SDValue Op1 = U->getOperand(1);
550 
551       // If the other operand is a 8-bit immediate we should fold the immediate
552       // instead. This reduces code size.
553       // e.g.
554       // movl 4(%esp), %eax
555       // addl $4, %eax
556       // vs.
557       // movl $4, %eax
558       // addl 4(%esp), %eax
559       // The former is 2 bytes shorter. In case where the increment is 1, then
560       // the saving can be 4 bytes (by using incl %eax).
561       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) {
562         if (Imm->getAPIntValue().isSignedIntN(8))
563           return false;
564 
565         // If this is a 64-bit AND with an immediate that fits in 32-bits,
566         // prefer using the smaller and over folding the load. This is needed to
567         // make sure immediates created by shrinkAndImmediate are always folded.
568         // Ideally we would narrow the load during DAG combine and get the
569         // best of both worlds.
570         if (U->getOpcode() == ISD::AND &&
571             Imm->getAPIntValue().getBitWidth() == 64 &&
572             Imm->getAPIntValue().isIntN(32))
573           return false;
574       }
575 
576       // If the other operand is a TLS address, we should fold it instead.
577       // This produces
578       // movl    %gs:0, %eax
579       // leal    i@NTPOFF(%eax), %eax
580       // instead of
581       // movl    $i@NTPOFF, %eax
582       // addl    %gs:0, %eax
583       // if the block also has an access to a second TLS address this will save
584       // a load.
585       // FIXME: This is probably also true for non-TLS addresses.
586       if (Op1.getOpcode() == X86ISD::Wrapper) {
587         SDValue Val = Op1.getOperand(0);
588         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
589           return false;
590       }
591 
592       // Don't fold load if this matches the BTS/BTR/BTC patterns.
593       // BTS: (or X, (shl 1, n))
594       // BTR: (and X, (rotl -2, n))
595       // BTC: (xor X, (shl 1, n))
596       if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
597         if (U->getOperand(0).getOpcode() == ISD::SHL &&
598             isOneConstant(U->getOperand(0).getOperand(0)))
599           return false;
600 
601         if (U->getOperand(1).getOpcode() == ISD::SHL &&
602             isOneConstant(U->getOperand(1).getOperand(0)))
603           return false;
604       }
605       if (U->getOpcode() == ISD::AND) {
606         SDValue U0 = U->getOperand(0);
607         SDValue U1 = U->getOperand(1);
608         if (U0.getOpcode() == ISD::ROTL) {
609           auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
610           if (C && C->getSExtValue() == -2)
611             return false;
612         }
613 
614         if (U1.getOpcode() == ISD::ROTL) {
615           auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
616           if (C && C->getSExtValue() == -2)
617             return false;
618         }
619       }
620 
621       break;
622     }
623     case ISD::SHL:
624     case ISD::SRA:
625     case ISD::SRL:
626       // Don't fold a load into a shift by immediate. The BMI2 instructions
627       // support folding a load, but not an immediate. The legacy instructions
628       // support folding an immediate, but can't fold a load. Folding an
629       // immediate is preferable to folding a load.
630       if (isa<ConstantSDNode>(U->getOperand(1)))
631         return false;
632 
633       break;
634     }
635   }
636 
637   // Prevent folding a load if this can implemented with an insert_subreg or
638   // a move that implicitly zeroes.
639   if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
640       isNullConstant(Root->getOperand(2)) &&
641       (Root->getOperand(0).isUndef() ||
642        ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))
643     return false;
644 
645   return true;
646 }
647 
648 /// Replace the original chain operand of the call with
649 /// load's chain operand and move load below the call's chain operand.
650 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
651                                SDValue Call, SDValue OrigChain) {
652   SmallVector<SDValue, 8> Ops;
653   SDValue Chain = OrigChain.getOperand(0);
654   if (Chain.getNode() == Load.getNode())
655     Ops.push_back(Load.getOperand(0));
656   else {
657     assert(Chain.getOpcode() == ISD::TokenFactor &&
658            "Unexpected chain operand");
659     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
660       if (Chain.getOperand(i).getNode() == Load.getNode())
661         Ops.push_back(Load.getOperand(0));
662       else
663         Ops.push_back(Chain.getOperand(i));
664     SDValue NewChain =
665       CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
666     Ops.clear();
667     Ops.push_back(NewChain);
668   }
669   Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
670   CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
671   CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
672                              Load.getOperand(1), Load.getOperand(2));
673 
674   Ops.clear();
675   Ops.push_back(SDValue(Load.getNode(), 1));
676   Ops.append(Call->op_begin() + 1, Call->op_end());
677   CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
678 }
679 
680 /// Return true if call address is a load and it can be
681 /// moved below CALLSEQ_START and the chains leading up to the call.
682 /// Return the CALLSEQ_START by reference as a second output.
683 /// In the case of a tail call, there isn't a callseq node between the call
684 /// chain and the load.
685 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
686   // The transformation is somewhat dangerous if the call's chain was glued to
687   // the call. After MoveBelowOrigChain the load is moved between the call and
688   // the chain, this can create a cycle if the load is not folded. So it is
689   // *really* important that we are sure the load will be folded.
690   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
691     return false;
692   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
693   if (!LD ||
694       LD->isVolatile() ||
695       LD->getAddressingMode() != ISD::UNINDEXED ||
696       LD->getExtensionType() != ISD::NON_EXTLOAD)
697     return false;
698 
699   // Now let's find the callseq_start.
700   while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
701     if (!Chain.hasOneUse())
702       return false;
703     Chain = Chain.getOperand(0);
704   }
705 
706   if (!Chain.getNumOperands())
707     return false;
708   // Since we are not checking for AA here, conservatively abort if the chain
709   // writes to memory. It's not safe to move the callee (a load) across a store.
710   if (isa<MemSDNode>(Chain.getNode()) &&
711       cast<MemSDNode>(Chain.getNode())->writeMem())
712     return false;
713   if (Chain.getOperand(0).getNode() == Callee.getNode())
714     return true;
715   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
716       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
717       Callee.getValue(1).hasOneUse())
718     return true;
719   return false;
720 }
721 
722 void X86DAGToDAGISel::PreprocessISelDAG() {
723   // OptFor[Min]Size are used in pattern predicates that isel is matching.
724   OptForSize = MF->getFunction().optForSize();
725   OptForMinSize = MF->getFunction().optForMinSize();
726   assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
727 
728   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
729        E = CurDAG->allnodes_end(); I != E; ) {
730     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
731 
732     // If this is a target specific AND node with no flag usages, turn it back
733     // into ISD::AND to enable test instruction matching.
734     if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
735       SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
736                                     N->getOperand(0), N->getOperand(1));
737       --I;
738       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
739       ++I;
740       CurDAG->DeleteNode(N);
741       continue;
742     }
743 
744     if (OptLevel != CodeGenOpt::None &&
745         // Only do this when the target can fold the load into the call or
746         // jmp.
747         !Subtarget->useRetpolineIndirectCalls() &&
748         ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
749          (N->getOpcode() == X86ISD::TC_RETURN &&
750           (Subtarget->is64Bit() ||
751            !getTargetMachine().isPositionIndependent())))) {
752       /// Also try moving call address load from outside callseq_start to just
753       /// before the call to allow it to be folded.
754       ///
755       ///     [Load chain]
756       ///         ^
757       ///         |
758       ///       [Load]
759       ///       ^    ^
760       ///       |    |
761       ///      /      \--
762       ///     /          |
763       ///[CALLSEQ_START] |
764       ///     ^          |
765       ///     |          |
766       /// [LOAD/C2Reg]   |
767       ///     |          |
768       ///      \        /
769       ///       \      /
770       ///       [CALL]
771       bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
772       SDValue Chain = N->getOperand(0);
773       SDValue Load  = N->getOperand(1);
774       if (!isCalleeLoad(Load, Chain, HasCallSeq))
775         continue;
776       moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
777       ++NumLoadMoved;
778       continue;
779     }
780 
781     // Lower fpround and fpextend nodes that target the FP stack to be store and
782     // load to the stack.  This is a gross hack.  We would like to simply mark
783     // these as being illegal, but when we do that, legalize produces these when
784     // it expands calls, then expands these in the same legalize pass.  We would
785     // like dag combine to be able to hack on these between the call expansion
786     // and the node legalization.  As such this pass basically does "really
787     // late" legalization of these inline with the X86 isel pass.
788     // FIXME: This should only happen when not compiled with -O0.
789     if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
790       continue;
791 
792     MVT SrcVT = N->getOperand(0).getSimpleValueType();
793     MVT DstVT = N->getSimpleValueType(0);
794 
795     // If any of the sources are vectors, no fp stack involved.
796     if (SrcVT.isVector() || DstVT.isVector())
797       continue;
798 
799     // If the source and destination are SSE registers, then this is a legal
800     // conversion that should not be lowered.
801     const X86TargetLowering *X86Lowering =
802         static_cast<const X86TargetLowering *>(TLI);
803     bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
804     bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
805     if (SrcIsSSE && DstIsSSE)
806       continue;
807 
808     if (!SrcIsSSE && !DstIsSSE) {
809       // If this is an FPStack extension, it is a noop.
810       if (N->getOpcode() == ISD::FP_EXTEND)
811         continue;
812       // If this is a value-preserving FPStack truncation, it is a noop.
813       if (N->getConstantOperandVal(1))
814         continue;
815     }
816 
817     // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
818     // FPStack has extload and truncstore.  SSE can fold direct loads into other
819     // operations.  Based on this, decide what we want to do.
820     MVT MemVT;
821     if (N->getOpcode() == ISD::FP_ROUND)
822       MemVT = DstVT;  // FP_ROUND must use DstVT, we can't do a 'trunc load'.
823     else
824       MemVT = SrcIsSSE ? SrcVT : DstVT;
825 
826     SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
827     SDLoc dl(N);
828 
829     // FIXME: optimize the case where the src/dest is a load or store?
830     SDValue Store =
831         CurDAG->getTruncStore(CurDAG->getEntryNode(), dl, N->getOperand(0),
832                               MemTmp, MachinePointerInfo(), MemVT);
833     SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
834                                         MachinePointerInfo(), MemVT);
835 
836     // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
837     // extload we created.  This will cause general havok on the dag because
838     // anything below the conversion could be folded into other existing nodes.
839     // To avoid invalidating 'I', back it up to the convert node.
840     --I;
841     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
842 
843     // Now that we did that, the node is dead.  Increment the iterator to the
844     // next node to process, then delete N.
845     ++I;
846     CurDAG->DeleteNode(N);
847   }
848 }
849 
850 // Look for a redundant movzx/movsx that can occur after an 8-bit divrem.
851 bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {
852   unsigned Opc = N->getMachineOpcode();
853   if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&
854       Opc != X86::MOVSX64rr8)
855     return false;
856 
857   SDValue N0 = N->getOperand(0);
858 
859   // We need to be extracting the lower bit of an extend.
860   if (!N0.isMachineOpcode() ||
861       N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||
862       N0.getConstantOperandVal(1) != X86::sub_8bit)
863     return false;
864 
865   // We're looking for either a movsx or movzx to match the original opcode.
866   unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX
867                                                 : X86::MOVSX32rr8_NOREX;
868   SDValue N00 = N0.getOperand(0);
869   if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)
870     return false;
871 
872   if (Opc == X86::MOVSX64rr8) {
873     // If we had a sign extend from 8 to 64 bits. We still need to go from 32
874     // to 64.
875     MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),
876                                                    MVT::i64, N00);
877     ReplaceUses(N, Extend);
878   } else {
879     // Ok we can drop this extend and just use the original extend.
880     ReplaceUses(N, N00.getNode());
881   }
882 
883   return true;
884 }
885 
886 void X86DAGToDAGISel::PostprocessISelDAG() {
887   // Skip peepholes at -O0.
888   if (TM.getOptLevel() == CodeGenOpt::None)
889     return;
890 
891   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
892 
893   bool MadeChange = false;
894   while (Position != CurDAG->allnodes_begin()) {
895     SDNode *N = &*--Position;
896     // Skip dead nodes and any non-machine opcodes.
897     if (N->use_empty() || !N->isMachineOpcode())
898       continue;
899 
900     if (tryOptimizeRem8Extend(N)) {
901       MadeChange = true;
902       continue;
903     }
904 
905     // Look for a TESTrr+ANDrr pattern where both operands of the test are
906     // the same. Rewrite to remove the AND.
907     unsigned Opc = N->getMachineOpcode();
908     if ((Opc == X86::TEST8rr || Opc == X86::TEST16rr ||
909          Opc == X86::TEST32rr || Opc == X86::TEST64rr) &&
910         N->getOperand(0) == N->getOperand(1) &&
911         N->isOnlyUserOf(N->getOperand(0).getNode()) &&
912         N->getOperand(0).isMachineOpcode()) {
913       SDValue And = N->getOperand(0);
914       unsigned N0Opc = And.getMachineOpcode();
915       if (N0Opc == X86::AND8rr || N0Opc == X86::AND16rr ||
916           N0Opc == X86::AND32rr || N0Opc == X86::AND64rr) {
917         MachineSDNode *Test = CurDAG->getMachineNode(Opc, SDLoc(N),
918                                                      MVT::i32,
919                                                      And.getOperand(0),
920                                                      And.getOperand(1));
921         ReplaceUses(N, Test);
922         MadeChange = true;
923         continue;
924       }
925       if (N0Opc == X86::AND8rm || N0Opc == X86::AND16rm ||
926           N0Opc == X86::AND32rm || N0Opc == X86::AND64rm) {
927         unsigned NewOpc;
928         switch (N0Opc) {
929         case X86::AND8rm:  NewOpc = X86::TEST8mr; break;
930         case X86::AND16rm: NewOpc = X86::TEST16mr; break;
931         case X86::AND32rm: NewOpc = X86::TEST32mr; break;
932         case X86::AND64rm: NewOpc = X86::TEST64mr; break;
933         }
934 
935         // Need to swap the memory and register operand.
936         SDValue Ops[] = { And.getOperand(1),
937                           And.getOperand(2),
938                           And.getOperand(3),
939                           And.getOperand(4),
940                           And.getOperand(5),
941                           And.getOperand(0),
942                           And.getOperand(6)  /* Chain */ };
943         MachineSDNode *Test = CurDAG->getMachineNode(NewOpc, SDLoc(N),
944                                                      MVT::i32, MVT::Other, Ops);
945         ReplaceUses(N, Test);
946         MadeChange = true;
947         continue;
948       }
949     }
950 
951     // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is
952     // used. We're doing this late so we can prefer to fold the AND into masked
953     // comparisons. Doing that can be better for the live range of the mask
954     // register.
955     if ((Opc == X86::KORTESTBrr || Opc == X86::KORTESTWrr ||
956          Opc == X86::KORTESTDrr || Opc == X86::KORTESTQrr) &&
957         N->getOperand(0) == N->getOperand(1) &&
958         N->isOnlyUserOf(N->getOperand(0).getNode()) &&
959         N->getOperand(0).isMachineOpcode() &&
960         onlyUsesZeroFlag(SDValue(N, 0))) {
961       SDValue And = N->getOperand(0);
962       unsigned N0Opc = And.getMachineOpcode();
963       // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other
964       // KAND instructions and KTEST use the same ISA feature.
965       if (N0Opc == X86::KANDBrr ||
966           (N0Opc == X86::KANDWrr && Subtarget->hasDQI()) ||
967           N0Opc == X86::KANDDrr || N0Opc == X86::KANDQrr) {
968         unsigned NewOpc;
969         switch (Opc) {
970         default: llvm_unreachable("Unexpected opcode!");
971         case X86::KORTESTBrr: NewOpc = X86::KTESTBrr; break;
972         case X86::KORTESTWrr: NewOpc = X86::KTESTWrr; break;
973         case X86::KORTESTDrr: NewOpc = X86::KTESTDrr; break;
974         case X86::KORTESTQrr: NewOpc = X86::KTESTQrr; break;
975         }
976         MachineSDNode *KTest = CurDAG->getMachineNode(NewOpc, SDLoc(N),
977                                                       MVT::i32,
978                                                       And.getOperand(0),
979                                                       And.getOperand(1));
980         ReplaceUses(N, KTest);
981         MadeChange = true;
982         continue;
983       }
984     }
985 
986     // Attempt to remove vectors moves that were inserted to zero upper bits.
987     if (Opc != TargetOpcode::SUBREG_TO_REG)
988       continue;
989 
990     unsigned SubRegIdx = N->getConstantOperandVal(2);
991     if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
992       continue;
993 
994     SDValue Move = N->getOperand(1);
995     if (!Move.isMachineOpcode())
996       continue;
997 
998     // Make sure its one of the move opcodes we recognize.
999     switch (Move.getMachineOpcode()) {
1000     default:
1001       continue;
1002     case X86::VMOVAPDrr:       case X86::VMOVUPDrr:
1003     case X86::VMOVAPSrr:       case X86::VMOVUPSrr:
1004     case X86::VMOVDQArr:       case X86::VMOVDQUrr:
1005     case X86::VMOVAPDYrr:      case X86::VMOVUPDYrr:
1006     case X86::VMOVAPSYrr:      case X86::VMOVUPSYrr:
1007     case X86::VMOVDQAYrr:      case X86::VMOVDQUYrr:
1008     case X86::VMOVAPDZ128rr:   case X86::VMOVUPDZ128rr:
1009     case X86::VMOVAPSZ128rr:   case X86::VMOVUPSZ128rr:
1010     case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
1011     case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
1012     case X86::VMOVAPDZ256rr:   case X86::VMOVUPDZ256rr:
1013     case X86::VMOVAPSZ256rr:   case X86::VMOVUPSZ256rr:
1014     case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
1015     case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
1016       break;
1017     }
1018 
1019     SDValue In = Move.getOperand(0);
1020     if (!In.isMachineOpcode() ||
1021         In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
1022       continue;
1023 
1024     // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
1025     // the SHA instructions which use a legacy encoding.
1026     uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
1027     if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&
1028         (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
1029         (TSFlags & X86II::EncodingMask) != X86II::XOP)
1030       continue;
1031 
1032     // Producing instruction is another vector instruction. We can drop the
1033     // move.
1034     CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
1035     MadeChange = true;
1036   }
1037 
1038   if (MadeChange)
1039     CurDAG->RemoveDeadNodes();
1040 }
1041 
1042 
1043 /// Emit any code that needs to be executed only in the main function.
1044 void X86DAGToDAGISel::emitSpecialCodeForMain() {
1045   if (Subtarget->isTargetCygMing()) {
1046     TargetLowering::ArgListTy Args;
1047     auto &DL = CurDAG->getDataLayout();
1048 
1049     TargetLowering::CallLoweringInfo CLI(*CurDAG);
1050     CLI.setChain(CurDAG->getRoot())
1051         .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
1052                    CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
1053                    std::move(Args));
1054     const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
1055     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
1056     CurDAG->setRoot(Result.second);
1057   }
1058 }
1059 
1060 void X86DAGToDAGISel::EmitFunctionEntryCode() {
1061   // If this is main, emit special code for main.
1062   const Function &F = MF->getFunction();
1063   if (F.hasExternalLinkage() && F.getName() == "main")
1064     emitSpecialCodeForMain();
1065 }
1066 
1067 static bool isDispSafeForFrameIndex(int64_t Val) {
1068   // On 64-bit platforms, we can run into an issue where a frame index
1069   // includes a displacement that, when added to the explicit displacement,
1070   // will overflow the displacement field. Assuming that the frame index
1071   // displacement fits into a 31-bit integer  (which is only slightly more
1072   // aggressive than the current fundamental assumption that it fits into
1073   // a 32-bit integer), a 31-bit disp should always be safe.
1074   return isInt<31>(Val);
1075 }
1076 
1077 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
1078                                             X86ISelAddressMode &AM) {
1079   // If there's no offset to fold, we don't need to do any work.
1080   if (Offset == 0)
1081     return false;
1082 
1083   // Cannot combine ExternalSymbol displacements with integer offsets.
1084   if (AM.ES || AM.MCSym)
1085     return true;
1086 
1087   int64_t Val = AM.Disp + Offset;
1088   CodeModel::Model M = TM.getCodeModel();
1089   if (Subtarget->is64Bit()) {
1090     if (!X86::isOffsetSuitableForCodeModel(Val, M,
1091                                            AM.hasSymbolicDisplacement()))
1092       return true;
1093     // In addition to the checks required for a register base, check that
1094     // we do not try to use an unsafe Disp with a frame index.
1095     if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
1096         !isDispSafeForFrameIndex(Val))
1097       return true;
1098   }
1099   AM.Disp = Val;
1100   return false;
1101 
1102 }
1103 
1104 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
1105   SDValue Address = N->getOperand(1);
1106 
1107   // load gs:0 -> GS segment register.
1108   // load fs:0 -> FS segment register.
1109   //
1110   // This optimization is valid because the GNU TLS model defines that
1111   // gs:0 (or fs:0 on X86-64) contains its own address.
1112   // For more information see http://people.redhat.com/drepper/tls.pdf
1113   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
1114     if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
1115         !IndirectTlsSegRefs &&
1116         (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
1117          Subtarget->isTargetFuchsia()))
1118       switch (N->getPointerInfo().getAddrSpace()) {
1119       case 256:
1120         AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1121         return false;
1122       case 257:
1123         AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1124         return false;
1125       // Address space 258 is not handled here, because it is not used to
1126       // address TLS areas.
1127       }
1128 
1129   return true;
1130 }
1131 
1132 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
1133 /// mode. These wrap things that will resolve down into a symbol reference.
1134 /// If no match is possible, this returns true, otherwise it returns false.
1135 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
1136   // If the addressing mode already has a symbol as the displacement, we can
1137   // never match another symbol.
1138   if (AM.hasSymbolicDisplacement())
1139     return true;
1140 
1141   bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
1142 
1143   // We can't use an addressing mode in the 64-bit large code model. In the
1144   // medium code model, we use can use an mode when RIP wrappers are present.
1145   // That signifies access to globals that are known to be "near", such as the
1146   // GOT itself.
1147   CodeModel::Model M = TM.getCodeModel();
1148   if (Subtarget->is64Bit() &&
1149       (M == CodeModel::Large || (M == CodeModel::Medium && !IsRIPRel)))
1150     return true;
1151 
1152   // Base and index reg must be 0 in order to use %rip as base.
1153   if (IsRIPRel && AM.hasBaseOrIndexReg())
1154     return true;
1155 
1156   // Make a local copy in case we can't do this fold.
1157   X86ISelAddressMode Backup = AM;
1158 
1159   int64_t Offset = 0;
1160   SDValue N0 = N.getOperand(0);
1161   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1162     AM.GV = G->getGlobal();
1163     AM.SymbolFlags = G->getTargetFlags();
1164     Offset = G->getOffset();
1165   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1166     AM.CP = CP->getConstVal();
1167     AM.Align = CP->getAlignment();
1168     AM.SymbolFlags = CP->getTargetFlags();
1169     Offset = CP->getOffset();
1170   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1171     AM.ES = S->getSymbol();
1172     AM.SymbolFlags = S->getTargetFlags();
1173   } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1174     AM.MCSym = S->getMCSymbol();
1175   } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
1176     AM.JT = J->getIndex();
1177     AM.SymbolFlags = J->getTargetFlags();
1178   } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1179     AM.BlockAddr = BA->getBlockAddress();
1180     AM.SymbolFlags = BA->getTargetFlags();
1181     Offset = BA->getOffset();
1182   } else
1183     llvm_unreachable("Unhandled symbol reference node.");
1184 
1185   if (foldOffsetIntoAddress(Offset, AM)) {
1186     AM = Backup;
1187     return true;
1188   }
1189 
1190   if (IsRIPRel)
1191     AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
1192 
1193   // Commit the changes now that we know this fold is safe.
1194   return false;
1195 }
1196 
1197 /// Add the specified node to the specified addressing mode, returning true if
1198 /// it cannot be done. This just pattern matches for the addressing mode.
1199 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1200   if (matchAddressRecursively(N, AM, 0))
1201     return true;
1202 
1203   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1204   // a smaller encoding and avoids a scaled-index.
1205   if (AM.Scale == 2 &&
1206       AM.BaseType == X86ISelAddressMode::RegBase &&
1207       AM.Base_Reg.getNode() == nullptr) {
1208     AM.Base_Reg = AM.IndexReg;
1209     AM.Scale = 1;
1210   }
1211 
1212   // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1213   // because it has a smaller encoding.
1214   // TODO: Which other code models can use this?
1215   if (TM.getCodeModel() == CodeModel::Small &&
1216       Subtarget->is64Bit() &&
1217       AM.Scale == 1 &&
1218       AM.BaseType == X86ISelAddressMode::RegBase &&
1219       AM.Base_Reg.getNode() == nullptr &&
1220       AM.IndexReg.getNode() == nullptr &&
1221       AM.SymbolFlags == X86II::MO_NO_FLAG &&
1222       AM.hasSymbolicDisplacement())
1223     AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
1224 
1225   return false;
1226 }
1227 
1228 bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
1229                                unsigned Depth) {
1230   // Add an artificial use to this node so that we can keep track of
1231   // it if it gets CSE'd with a different node.
1232   HandleSDNode Handle(N);
1233 
1234   X86ISelAddressMode Backup = AM;
1235   if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1236       !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1237     return false;
1238   AM = Backup;
1239 
1240   // Try again after commuting the operands.
1241   if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
1242       !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
1243     return false;
1244   AM = Backup;
1245 
1246   // If we couldn't fold both operands into the address at the same time,
1247   // see if we can just put each operand into a register and fold at least
1248   // the add.
1249   if (AM.BaseType == X86ISelAddressMode::RegBase &&
1250       !AM.Base_Reg.getNode() &&
1251       !AM.IndexReg.getNode()) {
1252     N = Handle.getValue();
1253     AM.Base_Reg = N.getOperand(0);
1254     AM.IndexReg = N.getOperand(1);
1255     AM.Scale = 1;
1256     return false;
1257   }
1258   N = Handle.getValue();
1259   return true;
1260 }
1261 
1262 // Insert a node into the DAG at least before the Pos node's position. This
1263 // will reposition the node as needed, and will assign it a node ID that is <=
1264 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1265 // IDs! The selection DAG must no longer depend on their uniqueness when this
1266 // is used.
1267 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
1268   if (N->getNodeId() == -1 ||
1269       (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
1270        SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
1271     DAG.RepositionNode(Pos->getIterator(), N.getNode());
1272     // Mark Node as invalid for pruning as after this it may be a successor to a
1273     // selected node but otherwise be in the same position of Pos.
1274     // Conservatively mark it with the same -abs(Id) to assure node id
1275     // invariant is preserved.
1276     N->setNodeId(Pos->getNodeId());
1277     SelectionDAGISel::InvalidateNodeId(N.getNode());
1278   }
1279 }
1280 
1281 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1282 // safe. This allows us to convert the shift and and into an h-register
1283 // extract and a scaled index. Returns false if the simplification is
1284 // performed.
1285 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1286                                       uint64_t Mask,
1287                                       SDValue Shift, SDValue X,
1288                                       X86ISelAddressMode &AM) {
1289   if (Shift.getOpcode() != ISD::SRL ||
1290       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1291       !Shift.hasOneUse())
1292     return true;
1293 
1294   int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1295   if (ScaleLog <= 0 || ScaleLog >= 4 ||
1296       Mask != (0xffu << ScaleLog))
1297     return true;
1298 
1299   MVT VT = N.getSimpleValueType();
1300   SDLoc DL(N);
1301   SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1302   SDValue NewMask = DAG.getConstant(0xff, DL, VT);
1303   SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1304   SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
1305   SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
1306   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1307 
1308   // Insert the new nodes into the topological ordering. We must do this in
1309   // a valid topological ordering as nothing is going to go back and re-sort
1310   // these nodes. We continually insert before 'N' in sequence as this is
1311   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1312   // hierarchy left to express.
1313   insertDAGNode(DAG, N, Eight);
1314   insertDAGNode(DAG, N, Srl);
1315   insertDAGNode(DAG, N, NewMask);
1316   insertDAGNode(DAG, N, And);
1317   insertDAGNode(DAG, N, ShlCount);
1318   insertDAGNode(DAG, N, Shl);
1319   DAG.ReplaceAllUsesWith(N, Shl);
1320   AM.IndexReg = And;
1321   AM.Scale = (1 << ScaleLog);
1322   return false;
1323 }
1324 
1325 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1326 // allows us to fold the shift into this addressing mode. Returns false if the
1327 // transform succeeded.
1328 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1329                                         uint64_t Mask,
1330                                         SDValue Shift, SDValue X,
1331                                         X86ISelAddressMode &AM) {
1332   if (Shift.getOpcode() != ISD::SHL ||
1333       !isa<ConstantSDNode>(Shift.getOperand(1)))
1334     return true;
1335 
1336   // Not likely to be profitable if either the AND or SHIFT node has more
1337   // than one use (unless all uses are for address computation). Besides,
1338   // isel mechanism requires their node ids to be reused.
1339   if (!N.hasOneUse() || !Shift.hasOneUse())
1340     return true;
1341 
1342   // Verify that the shift amount is something we can fold.
1343   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1344   if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1345     return true;
1346 
1347   MVT VT = N.getSimpleValueType();
1348   SDLoc DL(N);
1349   SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
1350   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1351   SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1352 
1353   // Insert the new nodes into the topological ordering. We must do this in
1354   // a valid topological ordering as nothing is going to go back and re-sort
1355   // these nodes. We continually insert before 'N' in sequence as this is
1356   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1357   // hierarchy left to express.
1358   insertDAGNode(DAG, N, NewMask);
1359   insertDAGNode(DAG, N, NewAnd);
1360   insertDAGNode(DAG, N, NewShift);
1361   DAG.ReplaceAllUsesWith(N, NewShift);
1362 
1363   AM.Scale = 1 << ShiftAmt;
1364   AM.IndexReg = NewAnd;
1365   return false;
1366 }
1367 
1368 // Implement some heroics to detect shifts of masked values where the mask can
1369 // be replaced by extending the shift and undoing that in the addressing mode
1370 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1371 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1372 // the addressing mode. This results in code such as:
1373 //
1374 //   int f(short *y, int *lookup_table) {
1375 //     ...
1376 //     return *y + lookup_table[*y >> 11];
1377 //   }
1378 //
1379 // Turning into:
1380 //   movzwl (%rdi), %eax
1381 //   movl %eax, %ecx
1382 //   shrl $11, %ecx
1383 //   addl (%rsi,%rcx,4), %eax
1384 //
1385 // Instead of:
1386 //   movzwl (%rdi), %eax
1387 //   movl %eax, %ecx
1388 //   shrl $9, %ecx
1389 //   andl $124, %rcx
1390 //   addl (%rsi,%rcx), %eax
1391 //
1392 // Note that this function assumes the mask is provided as a mask *after* the
1393 // value is shifted. The input chain may or may not match that, but computing
1394 // such a mask is trivial.
1395 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1396                                     uint64_t Mask,
1397                                     SDValue Shift, SDValue X,
1398                                     X86ISelAddressMode &AM) {
1399   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1400       !isa<ConstantSDNode>(Shift.getOperand(1)))
1401     return true;
1402 
1403   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1404   unsigned MaskLZ = countLeadingZeros(Mask);
1405   unsigned MaskTZ = countTrailingZeros(Mask);
1406 
1407   // The amount of shift we're trying to fit into the addressing mode is taken
1408   // from the trailing zeros of the mask.
1409   unsigned AMShiftAmt = MaskTZ;
1410 
1411   // There is nothing we can do here unless the mask is removing some bits.
1412   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1413   if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1414 
1415   // We also need to ensure that mask is a continuous run of bits.
1416   if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1417 
1418   // Scale the leading zero count down based on the actual size of the value.
1419   // Also scale it down based on the size of the shift.
1420   unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1421   if (MaskLZ < ScaleDown)
1422     return true;
1423   MaskLZ -= ScaleDown;
1424 
1425   // The final check is to ensure that any masked out high bits of X are
1426   // already known to be zero. Otherwise, the mask has a semantic impact
1427   // other than masking out a couple of low bits. Unfortunately, because of
1428   // the mask, zero extensions will be removed from operands in some cases.
1429   // This code works extra hard to look through extensions because we can
1430   // replace them with zero extensions cheaply if necessary.
1431   bool ReplacingAnyExtend = false;
1432   if (X.getOpcode() == ISD::ANY_EXTEND) {
1433     unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1434                           X.getOperand(0).getSimpleValueType().getSizeInBits();
1435     // Assume that we'll replace the any-extend with a zero-extend, and
1436     // narrow the search to the extended value.
1437     X = X.getOperand(0);
1438     MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1439     ReplacingAnyExtend = true;
1440   }
1441   APInt MaskedHighBits =
1442     APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1443   KnownBits Known = DAG.computeKnownBits(X);
1444   if (MaskedHighBits != Known.Zero) return true;
1445 
1446   // We've identified a pattern that can be transformed into a single shift
1447   // and an addressing mode. Make it so.
1448   MVT VT = N.getSimpleValueType();
1449   if (ReplacingAnyExtend) {
1450     assert(X.getValueType() != VT);
1451     // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1452     SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1453     insertDAGNode(DAG, N, NewX);
1454     X = NewX;
1455   }
1456   SDLoc DL(N);
1457   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1458   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1459   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1460   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1461 
1462   // Insert the new nodes into the topological ordering. We must do this in
1463   // a valid topological ordering as nothing is going to go back and re-sort
1464   // these nodes. We continually insert before 'N' in sequence as this is
1465   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1466   // hierarchy left to express.
1467   insertDAGNode(DAG, N, NewSRLAmt);
1468   insertDAGNode(DAG, N, NewSRL);
1469   insertDAGNode(DAG, N, NewSHLAmt);
1470   insertDAGNode(DAG, N, NewSHL);
1471   DAG.ReplaceAllUsesWith(N, NewSHL);
1472 
1473   AM.Scale = 1 << AMShiftAmt;
1474   AM.IndexReg = NewSRL;
1475   return false;
1476 }
1477 
1478 // Transform "(X >> SHIFT) & (MASK << C1)" to
1479 // "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be
1480 // matched to a BEXTR later. Returns false if the simplification is performed.
1481 static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N,
1482                                    uint64_t Mask,
1483                                    SDValue Shift, SDValue X,
1484                                    X86ISelAddressMode &AM,
1485                                    const X86Subtarget &Subtarget) {
1486   if (Shift.getOpcode() != ISD::SRL ||
1487       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1488       !Shift.hasOneUse() || !N.hasOneUse())
1489     return true;
1490 
1491   // Only do this if BEXTR will be matched by matchBEXTRFromAndImm.
1492   if (!Subtarget.hasTBM() &&
1493       !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))
1494     return true;
1495 
1496   // We need to ensure that mask is a continuous run of bits.
1497   if (!isShiftedMask_64(Mask)) return true;
1498 
1499   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1500 
1501   // The amount of shift we're trying to fit into the addressing mode is taken
1502   // from the trailing zeros of the mask.
1503   unsigned AMShiftAmt = countTrailingZeros(Mask);
1504 
1505   // There is nothing we can do here unless the mask is removing some bits.
1506   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1507   if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1508 
1509   MVT VT = N.getSimpleValueType();
1510   SDLoc DL(N);
1511   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1512   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1513   SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, VT);
1514   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, NewSRL, NewMask);
1515   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1516   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewAnd, NewSHLAmt);
1517 
1518   // Insert the new nodes into the topological ordering. We must do this in
1519   // a valid topological ordering as nothing is going to go back and re-sort
1520   // these nodes. We continually insert before 'N' in sequence as this is
1521   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1522   // hierarchy left to express.
1523   insertDAGNode(DAG, N, NewSRLAmt);
1524   insertDAGNode(DAG, N, NewSRL);
1525   insertDAGNode(DAG, N, NewMask);
1526   insertDAGNode(DAG, N, NewAnd);
1527   insertDAGNode(DAG, N, NewSHLAmt);
1528   insertDAGNode(DAG, N, NewSHL);
1529   DAG.ReplaceAllUsesWith(N, NewSHL);
1530 
1531   AM.Scale = 1 << AMShiftAmt;
1532   AM.IndexReg = NewAnd;
1533   return false;
1534 }
1535 
1536 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1537                                               unsigned Depth) {
1538   SDLoc dl(N);
1539   LLVM_DEBUG({
1540     dbgs() << "MatchAddress: ";
1541     AM.dump(CurDAG);
1542   });
1543   // Limit recursion.
1544   if (Depth > 5)
1545     return matchAddressBase(N, AM);
1546 
1547   // If this is already a %rip relative address, we can only merge immediates
1548   // into it.  Instead of handling this in every case, we handle it here.
1549   // RIP relative addressing: %rip + 32-bit displacement!
1550   if (AM.isRIPRelative()) {
1551     // FIXME: JumpTable and ExternalSymbol address currently don't like
1552     // displacements.  It isn't very important, but this should be fixed for
1553     // consistency.
1554     if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1555       return true;
1556 
1557     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1558       if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
1559         return false;
1560     return true;
1561   }
1562 
1563   switch (N.getOpcode()) {
1564   default: break;
1565   case ISD::LOCAL_RECOVER: {
1566     if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1567       if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1568         // Use the symbol and don't prefix it.
1569         AM.MCSym = ESNode->getMCSymbol();
1570         return false;
1571       }
1572     break;
1573   }
1574   case ISD::Constant: {
1575     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1576     if (!foldOffsetIntoAddress(Val, AM))
1577       return false;
1578     break;
1579   }
1580 
1581   case X86ISD::Wrapper:
1582   case X86ISD::WrapperRIP:
1583     if (!matchWrapper(N, AM))
1584       return false;
1585     break;
1586 
1587   case ISD::LOAD:
1588     if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
1589       return false;
1590     break;
1591 
1592   case ISD::FrameIndex:
1593     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1594         AM.Base_Reg.getNode() == nullptr &&
1595         (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1596       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1597       AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1598       return false;
1599     }
1600     break;
1601 
1602   case ISD::SHL:
1603     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1604       break;
1605 
1606     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1607       unsigned Val = CN->getZExtValue();
1608       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1609       // that the base operand remains free for further matching. If
1610       // the base doesn't end up getting used, a post-processing step
1611       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1612       if (Val == 1 || Val == 2 || Val == 3) {
1613         AM.Scale = 1 << Val;
1614         SDValue ShVal = N.getOperand(0);
1615 
1616         // Okay, we know that we have a scale by now.  However, if the scaled
1617         // value is an add of something and a constant, we can fold the
1618         // constant into the disp field here.
1619         if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1620           AM.IndexReg = ShVal.getOperand(0);
1621           ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
1622           uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1623           if (!foldOffsetIntoAddress(Disp, AM))
1624             return false;
1625         }
1626 
1627         AM.IndexReg = ShVal;
1628         return false;
1629       }
1630     }
1631     break;
1632 
1633   case ISD::SRL: {
1634     // Scale must not be used already.
1635     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1636 
1637     SDValue And = N.getOperand(0);
1638     if (And.getOpcode() != ISD::AND) break;
1639     SDValue X = And.getOperand(0);
1640 
1641     // We only handle up to 64-bit values here as those are what matter for
1642     // addressing mode optimizations.
1643     if (X.getSimpleValueType().getSizeInBits() > 64) break;
1644 
1645     // The mask used for the transform is expected to be post-shift, but we
1646     // found the shift first so just apply the shift to the mask before passing
1647     // it down.
1648     if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1649         !isa<ConstantSDNode>(And.getOperand(1)))
1650       break;
1651     uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1652 
1653     // Try to fold the mask and shift into the scale, and return false if we
1654     // succeed.
1655     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1656       return false;
1657     break;
1658   }
1659 
1660   case ISD::SMUL_LOHI:
1661   case ISD::UMUL_LOHI:
1662     // A mul_lohi where we need the low part can be folded as a plain multiply.
1663     if (N.getResNo() != 0) break;
1664     LLVM_FALLTHROUGH;
1665   case ISD::MUL:
1666   case X86ISD::MUL_IMM:
1667     // X*[3,5,9] -> X+X*[2,4,8]
1668     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1669         AM.Base_Reg.getNode() == nullptr &&
1670         AM.IndexReg.getNode() == nullptr) {
1671       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1672         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1673             CN->getZExtValue() == 9) {
1674           AM.Scale = unsigned(CN->getZExtValue())-1;
1675 
1676           SDValue MulVal = N.getOperand(0);
1677           SDValue Reg;
1678 
1679           // Okay, we know that we have a scale by now.  However, if the scaled
1680           // value is an add of something and a constant, we can fold the
1681           // constant into the disp field here.
1682           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1683               isa<ConstantSDNode>(MulVal.getOperand(1))) {
1684             Reg = MulVal.getOperand(0);
1685             ConstantSDNode *AddVal =
1686               cast<ConstantSDNode>(MulVal.getOperand(1));
1687             uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1688             if (foldOffsetIntoAddress(Disp, AM))
1689               Reg = N.getOperand(0);
1690           } else {
1691             Reg = N.getOperand(0);
1692           }
1693 
1694           AM.IndexReg = AM.Base_Reg = Reg;
1695           return false;
1696         }
1697     }
1698     break;
1699 
1700   case ISD::SUB: {
1701     // Given A-B, if A can be completely folded into the address and
1702     // the index field with the index field unused, use -B as the index.
1703     // This is a win if a has multiple parts that can be folded into
1704     // the address. Also, this saves a mov if the base register has
1705     // other uses, since it avoids a two-address sub instruction, however
1706     // it costs an additional mov if the index register has other uses.
1707 
1708     // Add an artificial use to this node so that we can keep track of
1709     // it if it gets CSE'd with a different node.
1710     HandleSDNode Handle(N);
1711 
1712     // Test if the LHS of the sub can be folded.
1713     X86ISelAddressMode Backup = AM;
1714     if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
1715       AM = Backup;
1716       break;
1717     }
1718     // Test if the index field is free for use.
1719     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1720       AM = Backup;
1721       break;
1722     }
1723 
1724     int Cost = 0;
1725     SDValue RHS = Handle.getValue().getOperand(1);
1726     // If the RHS involves a register with multiple uses, this
1727     // transformation incurs an extra mov, due to the neg instruction
1728     // clobbering its operand.
1729     if (!RHS.getNode()->hasOneUse() ||
1730         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1731         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1732         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1733         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1734          RHS.getOperand(0).getValueType() == MVT::i32))
1735       ++Cost;
1736     // If the base is a register with multiple uses, this
1737     // transformation may save a mov.
1738     // FIXME: Don't rely on DELETED_NODEs.
1739     if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
1740          AM.Base_Reg->getOpcode() != ISD::DELETED_NODE &&
1741          !AM.Base_Reg.getNode()->hasOneUse()) ||
1742         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1743       --Cost;
1744     // If the folded LHS was interesting, this transformation saves
1745     // address arithmetic.
1746     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1747         ((AM.Disp != 0) && (Backup.Disp == 0)) +
1748         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1749       --Cost;
1750     // If it doesn't look like it may be an overall win, don't do it.
1751     if (Cost >= 0) {
1752       AM = Backup;
1753       break;
1754     }
1755 
1756     // Ok, the transformation is legal and appears profitable. Go for it.
1757     SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1758     SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1759     AM.IndexReg = Neg;
1760     AM.Scale = 1;
1761 
1762     // Insert the new nodes into the topological ordering.
1763     insertDAGNode(*CurDAG, Handle.getValue(), Zero);
1764     insertDAGNode(*CurDAG, Handle.getValue(), Neg);
1765     return false;
1766   }
1767 
1768   case ISD::ADD:
1769     if (!matchAdd(N, AM, Depth))
1770       return false;
1771     break;
1772 
1773   case ISD::OR:
1774     // We want to look through a transform in InstCombine and DAGCombiner that
1775     // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
1776     // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
1777     // An 'lea' can then be used to match the shift (multiply) and add:
1778     // and $1, %esi
1779     // lea (%rsi, %rdi, 8), %rax
1780     if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1781         !matchAdd(N, AM, Depth))
1782       return false;
1783     break;
1784 
1785   case ISD::AND: {
1786     // Perform some heroic transforms on an and of a constant-count shift
1787     // with a constant to enable use of the scaled offset field.
1788 
1789     // Scale must not be used already.
1790     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1791 
1792     SDValue Shift = N.getOperand(0);
1793     if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1794     SDValue X = Shift.getOperand(0);
1795 
1796     // We only handle up to 64-bit values here as those are what matter for
1797     // addressing mode optimizations.
1798     if (X.getSimpleValueType().getSizeInBits() > 64) break;
1799 
1800     if (!isa<ConstantSDNode>(N.getOperand(1)))
1801       break;
1802     uint64_t Mask = N.getConstantOperandVal(1);
1803 
1804     // Try to fold the mask and shift into an extract and scale.
1805     if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1806       return false;
1807 
1808     // Try to fold the mask and shift directly into the scale.
1809     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1810       return false;
1811 
1812     // Try to swap the mask and shift to place shifts which can be done as
1813     // a scale on the outside of the mask.
1814     if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1815       return false;
1816 
1817     // Try to fold the mask and shift into BEXTR and scale.
1818     if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))
1819       return false;
1820 
1821     break;
1822   }
1823   }
1824 
1825   return matchAddressBase(N, AM);
1826 }
1827 
1828 /// Helper for MatchAddress. Add the specified node to the
1829 /// specified addressing mode without any further recursion.
1830 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1831   // Is the base register already occupied?
1832   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1833     // If so, check to see if the scale index register is set.
1834     if (!AM.IndexReg.getNode()) {
1835       AM.IndexReg = N;
1836       AM.Scale = 1;
1837       return false;
1838     }
1839 
1840     // Otherwise, we cannot select it.
1841     return true;
1842   }
1843 
1844   // Default, generate it as a register.
1845   AM.BaseType = X86ISelAddressMode::RegBase;
1846   AM.Base_Reg = N;
1847   return false;
1848 }
1849 
1850 /// Helper for selectVectorAddr. Handles things that can be folded into a
1851 /// gather scatter address. The index register and scale should have already
1852 /// been handled.
1853 bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
1854   // TODO: Support other operations.
1855   switch (N.getOpcode()) {
1856   case ISD::Constant: {
1857     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1858     if (!foldOffsetIntoAddress(Val, AM))
1859       return false;
1860     break;
1861   }
1862   case X86ISD::Wrapper:
1863     if (!matchWrapper(N, AM))
1864       return false;
1865     break;
1866   }
1867 
1868   return matchAddressBase(N, AM);
1869 }
1870 
1871 bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1872                                        SDValue &Scale, SDValue &Index,
1873                                        SDValue &Disp, SDValue &Segment) {
1874   X86ISelAddressMode AM;
1875   auto *Mgs = cast<X86MaskedGatherScatterSDNode>(Parent);
1876   AM.IndexReg = Mgs->getIndex();
1877   AM.Scale = cast<ConstantSDNode>(Mgs->getScale())->getZExtValue();
1878 
1879   unsigned AddrSpace = cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1880   // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1881   if (AddrSpace == 256)
1882     AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1883   if (AddrSpace == 257)
1884     AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1885   if (AddrSpace == 258)
1886     AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1887 
1888   // Try to match into the base and displacement fields.
1889   if (matchVectorAddress(N, AM))
1890     return false;
1891 
1892   MVT VT = N.getSimpleValueType();
1893   if (AM.BaseType == X86ISelAddressMode::RegBase) {
1894     if (!AM.Base_Reg.getNode())
1895       AM.Base_Reg = CurDAG->getRegister(0, VT);
1896   }
1897 
1898   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1899   return true;
1900 }
1901 
1902 /// Returns true if it is able to pattern match an addressing mode.
1903 /// It returns the operands which make up the maximal addressing mode it can
1904 /// match by reference.
1905 ///
1906 /// Parent is the parent node of the addr operand that is being matched.  It
1907 /// is always a load, store, atomic node, or null.  It is only null when
1908 /// checking memory operands for inline asm nodes.
1909 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1910                                  SDValue &Scale, SDValue &Index,
1911                                  SDValue &Disp, SDValue &Segment) {
1912   X86ISelAddressMode AM;
1913 
1914   if (Parent &&
1915       // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1916       // that are not a MemSDNode, and thus don't have proper addrspace info.
1917       Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1918       Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1919       Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1920       Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1921       Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1922     unsigned AddrSpace =
1923       cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1924     // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
1925     if (AddrSpace == 256)
1926       AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1927     if (AddrSpace == 257)
1928       AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1929     if (AddrSpace == 258)
1930       AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
1931   }
1932 
1933   if (matchAddress(N, AM))
1934     return false;
1935 
1936   MVT VT = N.getSimpleValueType();
1937   if (AM.BaseType == X86ISelAddressMode::RegBase) {
1938     if (!AM.Base_Reg.getNode())
1939       AM.Base_Reg = CurDAG->getRegister(0, VT);
1940   }
1941 
1942   if (!AM.IndexReg.getNode())
1943     AM.IndexReg = CurDAG->getRegister(0, VT);
1944 
1945   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1946   return true;
1947 }
1948 
1949 // We can only fold a load if all nodes between it and the root node have a
1950 // single use. If there are additional uses, we could end up duplicating the
1951 // load.
1952 static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *User) {
1953   while (User != Root) {
1954     if (!User->hasOneUse())
1955       return false;
1956     User = *User->use_begin();
1957   }
1958 
1959   return true;
1960 }
1961 
1962 /// Match a scalar SSE load. In particular, we want to match a load whose top
1963 /// elements are either undef or zeros. The load flavor is derived from the
1964 /// type of N, which is either v4f32 or v2f64.
1965 ///
1966 /// We also return:
1967 ///   PatternChainNode: this is the matched node that has a chain input and
1968 ///   output.
1969 bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root, SDNode *Parent,
1970                                           SDValue N, SDValue &Base,
1971                                           SDValue &Scale, SDValue &Index,
1972                                           SDValue &Disp, SDValue &Segment,
1973                                           SDValue &PatternNodeWithChain) {
1974   if (!hasSingleUsesFromRoot(Root, Parent))
1975     return false;
1976 
1977   // We can allow a full vector load here since narrowing a load is ok.
1978   if (ISD::isNON_EXTLoad(N.getNode())) {
1979     PatternNodeWithChain = N;
1980     if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1981         IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
1982       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1983       return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
1984                         Segment);
1985     }
1986   }
1987 
1988   // We can also match the special zero extended load opcode.
1989   if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
1990     PatternNodeWithChain = N;
1991     if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
1992         IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
1993       auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
1994       return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
1995                         Segment);
1996     }
1997   }
1998 
1999   // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
2000   // once. Otherwise the load might get duplicated and the chain output of the
2001   // duplicate load will not be observed by all dependencies.
2002   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
2003     PatternNodeWithChain = N.getOperand(0);
2004     if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
2005         IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
2006         IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
2007       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
2008       return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
2009                         Segment);
2010     }
2011   }
2012 
2013   // Also handle the case where we explicitly require zeros in the top
2014   // elements.  This is a vector shuffle from the zero vector.
2015   if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
2016       // Check to see if the top elements are all zeros (or bitcast of zeros).
2017       N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
2018       N.getOperand(0).getNode()->hasOneUse()) {
2019     PatternNodeWithChain = N.getOperand(0).getOperand(0);
2020     if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
2021         IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
2022         IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
2023       // Okay, this is a zero extending load.  Fold it.
2024       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
2025       return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
2026                         Segment);
2027     }
2028   }
2029 
2030   return false;
2031 }
2032 
2033 
2034 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
2035   if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2036     uint64_t ImmVal = CN->getZExtValue();
2037     if (!isUInt<32>(ImmVal))
2038       return false;
2039 
2040     Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
2041     return true;
2042   }
2043 
2044   // In static codegen with small code model, we can get the address of a label
2045   // into a register with 'movl'
2046   if (N->getOpcode() != X86ISD::Wrapper)
2047     return false;
2048 
2049   N = N.getOperand(0);
2050 
2051   // At least GNU as does not accept 'movl' for TPOFF relocations.
2052   // FIXME: We could use 'movl' when we know we are targeting MC.
2053   if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
2054     return false;
2055 
2056   Imm = N;
2057   if (N->getOpcode() != ISD::TargetGlobalAddress)
2058     return TM.getCodeModel() == CodeModel::Small;
2059 
2060   Optional<ConstantRange> CR =
2061       cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
2062   if (!CR)
2063     return TM.getCodeModel() == CodeModel::Small;
2064 
2065   return CR->getUnsignedMax().ult(1ull << 32);
2066 }
2067 
2068 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
2069                                          SDValue &Scale, SDValue &Index,
2070                                          SDValue &Disp, SDValue &Segment) {
2071   // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
2072   SDLoc DL(N);
2073 
2074   if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
2075     return false;
2076 
2077   RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
2078   if (RN && RN->getReg() == 0)
2079     Base = CurDAG->getRegister(0, MVT::i64);
2080   else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
2081     // Base could already be %rip, particularly in the x32 ABI.
2082     Base = SDValue(CurDAG->getMachineNode(
2083                        TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
2084                        CurDAG->getTargetConstant(0, DL, MVT::i64),
2085                        Base,
2086                        CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
2087                    0);
2088   }
2089 
2090   RN = dyn_cast<RegisterSDNode>(Index);
2091   if (RN && RN->getReg() == 0)
2092     Index = CurDAG->getRegister(0, MVT::i64);
2093   else {
2094     assert(Index.getValueType() == MVT::i32 &&
2095            "Expect to be extending 32-bit registers for use in LEA");
2096     Index = SDValue(CurDAG->getMachineNode(
2097                         TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
2098                         CurDAG->getTargetConstant(0, DL, MVT::i64),
2099                         Index,
2100                         CurDAG->getTargetConstant(X86::sub_32bit, DL,
2101                                                   MVT::i32)),
2102                     0);
2103   }
2104 
2105   return true;
2106 }
2107 
2108 /// Calls SelectAddr and determines if the maximal addressing
2109 /// mode it matches can be cost effectively emitted as an LEA instruction.
2110 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
2111                                     SDValue &Base, SDValue &Scale,
2112                                     SDValue &Index, SDValue &Disp,
2113                                     SDValue &Segment) {
2114   X86ISelAddressMode AM;
2115 
2116   // Save the DL and VT before calling matchAddress, it can invalidate N.
2117   SDLoc DL(N);
2118   MVT VT = N.getSimpleValueType();
2119 
2120   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
2121   // segments.
2122   SDValue Copy = AM.Segment;
2123   SDValue T = CurDAG->getRegister(0, MVT::i32);
2124   AM.Segment = T;
2125   if (matchAddress(N, AM))
2126     return false;
2127   assert (T == AM.Segment);
2128   AM.Segment = Copy;
2129 
2130   unsigned Complexity = 0;
2131   if (AM.BaseType == X86ISelAddressMode::RegBase)
2132     if (AM.Base_Reg.getNode())
2133       Complexity = 1;
2134     else
2135       AM.Base_Reg = CurDAG->getRegister(0, VT);
2136   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2137     Complexity = 4;
2138 
2139   if (AM.IndexReg.getNode())
2140     Complexity++;
2141   else
2142     AM.IndexReg = CurDAG->getRegister(0, VT);
2143 
2144   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
2145   // a simple shift.
2146   if (AM.Scale > 1)
2147     Complexity++;
2148 
2149   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
2150   // to a LEA. This is determined with some experimentation but is by no means
2151   // optimal (especially for code size consideration). LEA is nice because of
2152   // its three-address nature. Tweak the cost function again when we can run
2153   // convertToThreeAddress() at register allocation time.
2154   if (AM.hasSymbolicDisplacement()) {
2155     // For X86-64, always use LEA to materialize RIP-relative addresses.
2156     if (Subtarget->is64Bit())
2157       Complexity = 4;
2158     else
2159       Complexity += 2;
2160   }
2161 
2162   if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
2163     Complexity++;
2164 
2165   // If it isn't worth using an LEA, reject it.
2166   if (Complexity <= 2)
2167     return false;
2168 
2169   getAddressOperands(AM, DL, Base, Scale, Index, Disp, Segment);
2170   return true;
2171 }
2172 
2173 /// This is only run on TargetGlobalTLSAddress nodes.
2174 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
2175                                         SDValue &Scale, SDValue &Index,
2176                                         SDValue &Disp, SDValue &Segment) {
2177   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
2178   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
2179 
2180   X86ISelAddressMode AM;
2181   AM.GV = GA->getGlobal();
2182   AM.Disp += GA->getOffset();
2183   AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
2184   AM.SymbolFlags = GA->getTargetFlags();
2185 
2186   if (N.getValueType() == MVT::i32) {
2187     AM.Scale = 1;
2188     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
2189   } else {
2190     AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
2191   }
2192 
2193   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
2194   return true;
2195 }
2196 
2197 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
2198   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2199     Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
2200                                    N.getValueType());
2201     return true;
2202   }
2203 
2204   // Keep track of the original value type and whether this value was
2205   // truncated. If we see a truncation from pointer type to VT that truncates
2206   // bits that are known to be zero, we can use a narrow reference.
2207   EVT VT = N.getValueType();
2208   bool WasTruncated = false;
2209   if (N.getOpcode() == ISD::TRUNCATE) {
2210     WasTruncated = true;
2211     N = N.getOperand(0);
2212   }
2213 
2214   if (N.getOpcode() != X86ISD::Wrapper)
2215     return false;
2216 
2217   // We can only use non-GlobalValues as immediates if they were not truncated,
2218   // as we do not have any range information. If we have a GlobalValue and the
2219   // address was not truncated, we can select it as an operand directly.
2220   unsigned Opc = N.getOperand(0)->getOpcode();
2221   if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
2222     Op = N.getOperand(0);
2223     // We can only select the operand directly if we didn't have to look past a
2224     // truncate.
2225     return !WasTruncated;
2226   }
2227 
2228   // Check that the global's range fits into VT.
2229   auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
2230   Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2231   if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2232     return false;
2233 
2234   // Okay, we can use a narrow reference.
2235   Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2236                                       GA->getOffset(), GA->getTargetFlags());
2237   return true;
2238 }
2239 
2240 bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
2241                                   SDValue &Base, SDValue &Scale,
2242                                   SDValue &Index, SDValue &Disp,
2243                                   SDValue &Segment) {
2244   if (!ISD::isNON_EXTLoad(N.getNode()) ||
2245       !IsProfitableToFold(N, P, Root) ||
2246       !IsLegalToFold(N, P, Root, OptLevel))
2247     return false;
2248 
2249   return selectAddr(N.getNode(),
2250                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
2251 }
2252 
2253 /// Return an SDNode that returns the value of the global base register.
2254 /// Output instructions required to initialize the global base register,
2255 /// if necessary.
2256 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
2257   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
2258   auto &DL = MF->getDataLayout();
2259   return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
2260 }
2261 
2262 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2263   if (N->getOpcode() == ISD::TRUNCATE)
2264     N = N->getOperand(0).getNode();
2265   if (N->getOpcode() != X86ISD::Wrapper)
2266     return false;
2267 
2268   auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2269   if (!GA)
2270     return false;
2271 
2272   Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2273   return CR && CR->getSignedMin().sge(-1ull << Width) &&
2274          CR->getSignedMax().slt(1ull << Width);
2275 }
2276 
2277 static X86::CondCode getCondFromOpc(unsigned Opc) {
2278   X86::CondCode CC = X86::COND_INVALID;
2279   if (CC == X86::COND_INVALID)
2280     CC = X86::getCondFromBranchOpc(Opc);
2281   if (CC == X86::COND_INVALID)
2282     CC = X86::getCondFromSETOpc(Opc);
2283   if (CC == X86::COND_INVALID)
2284     CC = X86::getCondFromCMovOpc(Opc);
2285 
2286   return CC;
2287 }
2288 
2289 /// Test whether the given X86ISD::CMP node has any users that use a flag
2290 /// other than ZF.
2291 bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const {
2292   // Examine each user of the node.
2293   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2294          UI != UE; ++UI) {
2295     // Only check things that use the flags.
2296     if (UI.getUse().getResNo() != Flags.getResNo())
2297       continue;
2298     // Only examine CopyToReg uses that copy to EFLAGS.
2299     if (UI->getOpcode() != ISD::CopyToReg ||
2300         cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2301       return false;
2302     // Examine each user of the CopyToReg use.
2303     for (SDNode::use_iterator FlagUI = UI->use_begin(),
2304            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2305       // Only examine the Flag result.
2306       if (FlagUI.getUse().getResNo() != 1) continue;
2307       // Anything unusual: assume conservatively.
2308       if (!FlagUI->isMachineOpcode()) return false;
2309       // Examine the condition code of the user.
2310       X86::CondCode CC = getCondFromOpc(FlagUI->getMachineOpcode());
2311 
2312       switch (CC) {
2313       // Comparisons which only use the zero flag.
2314       case X86::COND_E: case X86::COND_NE:
2315         continue;
2316       // Anything else: assume conservatively.
2317       default:
2318         return false;
2319       }
2320     }
2321   }
2322   return true;
2323 }
2324 
2325 /// Test whether the given X86ISD::CMP node has any uses which require the SF
2326 /// flag to be accurate.
2327 bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const {
2328   // Examine each user of the node.
2329   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2330          UI != UE; ++UI) {
2331     // Only check things that use the flags.
2332     if (UI.getUse().getResNo() != Flags.getResNo())
2333       continue;
2334     // Only examine CopyToReg uses that copy to EFLAGS.
2335     if (UI->getOpcode() != ISD::CopyToReg ||
2336         cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2337       return false;
2338     // Examine each user of the CopyToReg use.
2339     for (SDNode::use_iterator FlagUI = UI->use_begin(),
2340            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2341       // Only examine the Flag result.
2342       if (FlagUI.getUse().getResNo() != 1) continue;
2343       // Anything unusual: assume conservatively.
2344       if (!FlagUI->isMachineOpcode()) return false;
2345       // Examine the condition code of the user.
2346       X86::CondCode CC = getCondFromOpc(FlagUI->getMachineOpcode());
2347 
2348       switch (CC) {
2349       // Comparisons which don't examine the SF flag.
2350       case X86::COND_A: case X86::COND_AE:
2351       case X86::COND_B: case X86::COND_BE:
2352       case X86::COND_E: case X86::COND_NE:
2353       case X86::COND_O: case X86::COND_NO:
2354       case X86::COND_P: case X86::COND_NP:
2355         continue;
2356       // Anything else: assume conservatively.
2357       default:
2358         return false;
2359       }
2360     }
2361   }
2362   return true;
2363 }
2364 
2365 static bool mayUseCarryFlag(X86::CondCode CC) {
2366   switch (CC) {
2367   // Comparisons which don't examine the CF flag.
2368   case X86::COND_O: case X86::COND_NO:
2369   case X86::COND_E: case X86::COND_NE:
2370   case X86::COND_S: case X86::COND_NS:
2371   case X86::COND_P: case X86::COND_NP:
2372   case X86::COND_L: case X86::COND_GE:
2373   case X86::COND_G: case X86::COND_LE:
2374     return false;
2375   // Anything else: assume conservatively.
2376   default:
2377     return true;
2378   }
2379 }
2380 
2381 /// Test whether the given node which sets flags has any uses which require the
2382 /// CF flag to be accurate.
2383  bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const {
2384   // Examine each user of the node.
2385   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2386          UI != UE; ++UI) {
2387     // Only check things that use the flags.
2388     if (UI.getUse().getResNo() != Flags.getResNo())
2389       continue;
2390 
2391     unsigned UIOpc = UI->getOpcode();
2392 
2393     if (UIOpc == ISD::CopyToReg) {
2394       // Only examine CopyToReg uses that copy to EFLAGS.
2395       if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2396         return false;
2397       // Examine each user of the CopyToReg use.
2398       for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2399            FlagUI != FlagUE; ++FlagUI) {
2400         // Only examine the Flag result.
2401         if (FlagUI.getUse().getResNo() != 1)
2402           continue;
2403         // Anything unusual: assume conservatively.
2404         if (!FlagUI->isMachineOpcode())
2405           return false;
2406         // Examine the condition code of the user.
2407         X86::CondCode CC = getCondFromOpc(FlagUI->getMachineOpcode());
2408 
2409         if (mayUseCarryFlag(CC))
2410           return false;
2411       }
2412 
2413       // This CopyToReg is ok. Move on to the next user.
2414       continue;
2415     }
2416 
2417     // This might be an unselected node. So look for the pre-isel opcodes that
2418     // use flags.
2419     unsigned CCOpNo;
2420     switch (UIOpc) {
2421     default:
2422       // Something unusual. Be conservative.
2423       return false;
2424     case X86ISD::SETCC:       CCOpNo = 0; break;
2425     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
2426     case X86ISD::CMOV:        CCOpNo = 2; break;
2427     case X86ISD::BRCOND:      CCOpNo = 2; break;
2428     }
2429 
2430     X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo);
2431     if (mayUseCarryFlag(CC))
2432       return false;
2433   }
2434   return true;
2435 }
2436 
2437 /// Check whether or not the chain ending in StoreNode is suitable for doing
2438 /// the {load; op; store} to modify transformation.
2439 static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2440                                         SDValue StoredVal, SelectionDAG *CurDAG,
2441                                         unsigned LoadOpNo,
2442                                         LoadSDNode *&LoadNode,
2443                                         SDValue &InputChain) {
2444   // Is the stored value result 0 of the operation?
2445   if (StoredVal.getResNo() != 0) return false;
2446 
2447   // Are there other uses of the operation other than the store?
2448   if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
2449 
2450   // Is the store non-extending and non-indexed?
2451   if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
2452     return false;
2453 
2454   SDValue Load = StoredVal->getOperand(LoadOpNo);
2455   // Is the stored value a non-extending and non-indexed load?
2456   if (!ISD::isNormalLoad(Load.getNode())) return false;
2457 
2458   // Return LoadNode by reference.
2459   LoadNode = cast<LoadSDNode>(Load);
2460 
2461   // Is store the only read of the loaded value?
2462   if (!Load.hasOneUse())
2463     return false;
2464 
2465   // Is the address of the store the same as the load?
2466   if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
2467       LoadNode->getOffset() != StoreNode->getOffset())
2468     return false;
2469 
2470   bool FoundLoad = false;
2471   SmallVector<SDValue, 4> ChainOps;
2472   SmallVector<const SDNode *, 4> LoopWorklist;
2473   SmallPtrSet<const SDNode *, 16> Visited;
2474   const unsigned int Max = 1024;
2475 
2476   //  Visualization of Load-Op-Store fusion:
2477   // -------------------------
2478   // Legend:
2479   //    *-lines = Chain operand dependencies.
2480   //    |-lines = Normal operand dependencies.
2481   //    Dependencies flow down and right. n-suffix references multiple nodes.
2482   //
2483   //        C                        Xn  C
2484   //        *                         *  *
2485   //        *                          * *
2486   //  Xn  A-LD    Yn                    TF         Yn
2487   //   *    * \   |                       *        |
2488   //    *   *  \  |                        *       |
2489   //     *  *   \ |             =>       A--LD_OP_ST
2490   //      * *    \|                                 \
2491   //       TF    OP                                  \
2492   //         *   | \                                  Zn
2493   //          *  |  \
2494   //         A-ST    Zn
2495   //
2496 
2497   // This merge induced dependences from: #1: Xn -> LD, OP, Zn
2498   //                                      #2: Yn -> LD
2499   //                                      #3: ST -> Zn
2500 
2501   // Ensure the transform is safe by checking for the dual
2502   // dependencies to make sure we do not induce a loop.
2503 
2504   // As LD is a predecessor to both OP and ST we can do this by checking:
2505   //  a). if LD is a predecessor to a member of Xn or Yn.
2506   //  b). if a Zn is a predecessor to ST.
2507 
2508   // However, (b) can only occur through being a chain predecessor to
2509   // ST, which is the same as Zn being a member or predecessor of Xn,
2510   // which is a subset of LD being a predecessor of Xn. So it's
2511   // subsumed by check (a).
2512 
2513   SDValue Chain = StoreNode->getChain();
2514 
2515   // Gather X elements in ChainOps.
2516   if (Chain == Load.getValue(1)) {
2517     FoundLoad = true;
2518     ChainOps.push_back(Load.getOperand(0));
2519   } else if (Chain.getOpcode() == ISD::TokenFactor) {
2520     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
2521       SDValue Op = Chain.getOperand(i);
2522       if (Op == Load.getValue(1)) {
2523         FoundLoad = true;
2524         // Drop Load, but keep its chain. No cycle check necessary.
2525         ChainOps.push_back(Load.getOperand(0));
2526         continue;
2527       }
2528       LoopWorklist.push_back(Op.getNode());
2529       ChainOps.push_back(Op);
2530     }
2531   }
2532 
2533   if (!FoundLoad)
2534     return false;
2535 
2536   // Worklist is currently Xn. Add Yn to worklist.
2537   for (SDValue Op : StoredVal->ops())
2538     if (Op.getNode() != LoadNode)
2539       LoopWorklist.push_back(Op.getNode());
2540 
2541   // Check (a) if Load is a predecessor to Xn + Yn
2542   if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
2543                                    true))
2544     return false;
2545 
2546   InputChain =
2547       CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
2548   return true;
2549 }
2550 
2551 // Change a chain of {load; op; store} of the same value into a simple op
2552 // through memory of that value, if the uses of the modified value and its
2553 // address are suitable.
2554 //
2555 // The tablegen pattern memory operand pattern is currently not able to match
2556 // the case where the EFLAGS on the original operation are used.
2557 //
2558 // To move this to tablegen, we'll need to improve tablegen to allow flags to
2559 // be transferred from a node in the pattern to the result node, probably with
2560 // a new keyword. For example, we have this
2561 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2562 //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2563 //   (implicit EFLAGS)]>;
2564 // but maybe need something like this
2565 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2566 //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2567 //   (transferrable EFLAGS)]>;
2568 //
2569 // Until then, we manually fold these and instruction select the operation
2570 // here.
2571 bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
2572   StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2573   SDValue StoredVal = StoreNode->getOperand(1);
2574   unsigned Opc = StoredVal->getOpcode();
2575 
2576   // Before we try to select anything, make sure this is memory operand size
2577   // and opcode we can handle. Note that this must match the code below that
2578   // actually lowers the opcodes.
2579   EVT MemVT = StoreNode->getMemoryVT();
2580   if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
2581       MemVT != MVT::i8)
2582     return false;
2583 
2584   bool IsCommutable = false;
2585   switch (Opc) {
2586   default:
2587     return false;
2588   case X86ISD::SUB:
2589   case X86ISD::SBB:
2590     break;
2591   case X86ISD::ADD:
2592   case X86ISD::ADC:
2593   case X86ISD::AND:
2594   case X86ISD::OR:
2595   case X86ISD::XOR:
2596     IsCommutable = true;
2597     break;
2598   }
2599 
2600   unsigned LoadOpNo = 0;
2601   LoadSDNode *LoadNode = nullptr;
2602   SDValue InputChain;
2603   if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
2604                                    LoadNode, InputChain)) {
2605     if (!IsCommutable)
2606       return false;
2607 
2608     // This operation is commutable, try the other operand.
2609     LoadOpNo = 1;
2610     if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
2611                                      LoadNode, InputChain))
2612       return false;
2613   }
2614 
2615   SDValue Base, Scale, Index, Disp, Segment;
2616   if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
2617                   Segment))
2618     return false;
2619 
2620   auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
2621                           unsigned Opc8) {
2622     switch (MemVT.getSimpleVT().SimpleTy) {
2623     case MVT::i64:
2624       return Opc64;
2625     case MVT::i32:
2626       return Opc32;
2627     case MVT::i16:
2628       return Opc16;
2629     case MVT::i8:
2630       return Opc8;
2631     default:
2632       llvm_unreachable("Invalid size!");
2633     }
2634   };
2635 
2636   MachineSDNode *Result;
2637   switch (Opc) {
2638   case X86ISD::ADD:
2639   case X86ISD::SUB:
2640     // Try to match inc/dec.
2641     if (!Subtarget->slowIncDec() ||
2642         CurDAG->getMachineFunction().getFunction().optForSize()) {
2643       bool IsOne = isOneConstant(StoredVal.getOperand(1));
2644       bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1));
2645       // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec.
2646       if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) {
2647         unsigned NewOpc =
2648           ((Opc == X86ISD::ADD) == IsOne)
2649               ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
2650               : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
2651         const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
2652         Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
2653                                         MVT::Other, Ops);
2654         break;
2655       }
2656     }
2657     LLVM_FALLTHROUGH;
2658   case X86ISD::ADC:
2659   case X86ISD::SBB:
2660   case X86ISD::AND:
2661   case X86ISD::OR:
2662   case X86ISD::XOR: {
2663     auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
2664       switch (Opc) {
2665       case X86ISD::ADD:
2666         return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
2667                             X86::ADD8mr);
2668       case X86ISD::ADC:
2669         return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
2670                             X86::ADC8mr);
2671       case X86ISD::SUB:
2672         return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
2673                             X86::SUB8mr);
2674       case X86ISD::SBB:
2675         return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
2676                             X86::SBB8mr);
2677       case X86ISD::AND:
2678         return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
2679                             X86::AND8mr);
2680       case X86ISD::OR:
2681         return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
2682       case X86ISD::XOR:
2683         return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
2684                             X86::XOR8mr);
2685       default:
2686         llvm_unreachable("Invalid opcode!");
2687       }
2688     };
2689     auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
2690       switch (Opc) {
2691       case X86ISD::ADD:
2692         return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
2693       case X86ISD::ADC:
2694         return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
2695       case X86ISD::SUB:
2696         return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
2697       case X86ISD::SBB:
2698         return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
2699       case X86ISD::AND:
2700         return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
2701       case X86ISD::OR:
2702         return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
2703       case X86ISD::XOR:
2704         return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
2705       default:
2706         llvm_unreachable("Invalid opcode!");
2707       }
2708     };
2709     auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
2710       switch (Opc) {
2711       case X86ISD::ADD:
2712         return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
2713                             X86::ADD8mi);
2714       case X86ISD::ADC:
2715         return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
2716                             X86::ADC8mi);
2717       case X86ISD::SUB:
2718         return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
2719                             X86::SUB8mi);
2720       case X86ISD::SBB:
2721         return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
2722                             X86::SBB8mi);
2723       case X86ISD::AND:
2724         return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
2725                             X86::AND8mi);
2726       case X86ISD::OR:
2727         return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
2728                             X86::OR8mi);
2729       case X86ISD::XOR:
2730         return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
2731                             X86::XOR8mi);
2732       default:
2733         llvm_unreachable("Invalid opcode!");
2734       }
2735     };
2736 
2737     unsigned NewOpc = SelectRegOpcode(Opc);
2738     SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
2739 
2740     // See if the operand is a constant that we can fold into an immediate
2741     // operand.
2742     if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
2743       auto OperandV = OperandC->getAPIntValue();
2744 
2745       // Check if we can shrink the operand enough to fit in an immediate (or
2746       // fit into a smaller immediate) by negating it and switching the
2747       // operation.
2748       if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
2749           ((MemVT != MVT::i8 && OperandV.getMinSignedBits() > 8 &&
2750             (-OperandV).getMinSignedBits() <= 8) ||
2751            (MemVT == MVT::i64 && OperandV.getMinSignedBits() > 32 &&
2752             (-OperandV).getMinSignedBits() <= 32)) &&
2753           hasNoCarryFlagUses(StoredVal.getValue(1))) {
2754         OperandV = -OperandV;
2755         Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
2756       }
2757 
2758       // First try to fit this into an Imm8 operand. If it doesn't fit, then try
2759       // the larger immediate operand.
2760       if (MemVT != MVT::i8 && OperandV.getMinSignedBits() <= 8) {
2761         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2762         NewOpc = SelectImm8Opcode(Opc);
2763       } else if (OperandV.getActiveBits() <= MemVT.getSizeInBits() &&
2764                  (MemVT != MVT::i64 || OperandV.getMinSignedBits() <= 32)) {
2765         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
2766         NewOpc = SelectImmOpcode(Opc);
2767       }
2768     }
2769 
2770     if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
2771       SDValue CopyTo =
2772           CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
2773                                StoredVal.getOperand(2), SDValue());
2774 
2775       const SDValue Ops[] = {Base,    Scale,   Index,  Disp,
2776                              Segment, Operand, CopyTo, CopyTo.getValue(1)};
2777       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2778                                       Ops);
2779     } else {
2780       const SDValue Ops[] = {Base,    Scale,   Index,     Disp,
2781                              Segment, Operand, InputChain};
2782       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
2783                                       Ops);
2784     }
2785     break;
2786   }
2787   default:
2788     llvm_unreachable("Invalid opcode!");
2789   }
2790 
2791   MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
2792                                  LoadNode->getMemOperand()};
2793   CurDAG->setNodeMemRefs(Result, MemOps);
2794 
2795   // Update Load Chain uses as well.
2796   ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
2797   ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2798   ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2799   CurDAG->RemoveDeadNode(Node);
2800   return true;
2801 }
2802 
2803 // See if this is an  X & Mask  that we can match to BEXTR/BZHI.
2804 // Where Mask is one of the following patterns:
2805 //   a) x &  (1 << nbits) - 1
2806 //   b) x & ~(-1 << nbits)
2807 //   c) x &  (-1 >> (32 - y))
2808 //   d) x << (32 - y) >> (32 - y)
2809 bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {
2810   assert(
2811       (Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) &&
2812       "Should be either an and-mask, or right-shift after clearing high bits.");
2813 
2814   // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.
2815   if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())
2816     return false;
2817 
2818   MVT NVT = Node->getSimpleValueType(0);
2819 
2820   // Only supported for 32 and 64 bits.
2821   if (NVT != MVT::i32 && NVT != MVT::i64)
2822     return false;
2823 
2824   unsigned Size = NVT.getSizeInBits();
2825 
2826   SDValue NBits;
2827 
2828   // If we have BMI2's BZHI, we are ok with muti-use patterns.
2829   // Else, if we only have BMI1's BEXTR, we require one-use.
2830   const bool CanHaveExtraUses = Subtarget->hasBMI2();
2831   auto checkUses = [CanHaveExtraUses](SDValue Op, unsigned NUses) {
2832     return CanHaveExtraUses ||
2833            Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());
2834   };
2835   auto checkOneUse = [checkUses](SDValue Op) { return checkUses(Op, 1); };
2836   auto checkTwoUse = [checkUses](SDValue Op) { return checkUses(Op, 2); };
2837 
2838   // a) x & ((1 << nbits) + (-1))
2839   auto matchPatternA = [&checkOneUse, &NBits](SDValue Mask) -> bool {
2840     // Match `add`. Must only have one use!
2841     if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))
2842       return false;
2843     // We should be adding all-ones constant (i.e. subtracting one.)
2844     if (!isAllOnesConstant(Mask->getOperand(1)))
2845       return false;
2846     // Match `1 << nbits`. Must only have one use!
2847     SDValue M0 = Mask->getOperand(0);
2848     if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
2849       return false;
2850     if (!isOneConstant(M0->getOperand(0)))
2851       return false;
2852     NBits = M0->getOperand(1);
2853     return true;
2854   };
2855 
2856   // b) x & ~(-1 << nbits)
2857   auto matchPatternB = [&checkOneUse, &NBits](SDValue Mask) -> bool {
2858     // Match `~()`. Must only have one use!
2859     if (!isBitwiseNot(Mask) || !checkOneUse(Mask))
2860       return false;
2861     // Match `-1 << nbits`. Must only have one use!
2862     SDValue M0 = Mask->getOperand(0);
2863     if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
2864       return false;
2865     if (!isAllOnesConstant(M0->getOperand(0)))
2866       return false;
2867     NBits = M0->getOperand(1);
2868     return true;
2869   };
2870 
2871   // Match potentially-truncated (bitwidth - y)
2872   auto matchShiftAmt = [checkOneUse, Size, &NBits](SDValue ShiftAmt) {
2873     // Skip over a truncate of the shift amount.
2874     if (ShiftAmt.getOpcode() == ISD::TRUNCATE) {
2875       ShiftAmt = ShiftAmt.getOperand(0);
2876       // The trunc should have been the only user of the real shift amount.
2877       if (!checkOneUse(ShiftAmt))
2878         return false;
2879     }
2880     // Match the shift amount as: (bitwidth - y). It should go away, too.
2881     if (ShiftAmt.getOpcode() != ISD::SUB)
2882       return false;
2883     auto V0 = dyn_cast<ConstantSDNode>(ShiftAmt.getOperand(0));
2884     if (!V0 || V0->getZExtValue() != Size)
2885       return false;
2886     NBits = ShiftAmt.getOperand(1);
2887     return true;
2888   };
2889 
2890   // c) x &  (-1 >> (32 - y))
2891   auto matchPatternC = [&checkOneUse, matchShiftAmt](SDValue Mask) -> bool {
2892     // Match `l>>`. Must only have one use!
2893     if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))
2894       return false;
2895     // We should be shifting all-ones constant.
2896     if (!isAllOnesConstant(Mask.getOperand(0)))
2897       return false;
2898     SDValue M1 = Mask.getOperand(1);
2899     // The shift amount should not be used externally.
2900     if (!checkOneUse(M1))
2901       return false;
2902     return matchShiftAmt(M1);
2903   };
2904 
2905   SDValue X;
2906 
2907   // d) x << (32 - y) >> (32 - y)
2908   auto matchPatternD = [&checkOneUse, &checkTwoUse, matchShiftAmt,
2909                         &X](SDNode *Node) -> bool {
2910     if (Node->getOpcode() != ISD::SRL)
2911       return false;
2912     SDValue N0 = Node->getOperand(0);
2913     if (N0->getOpcode() != ISD::SHL || !checkOneUse(N0))
2914       return false;
2915     SDValue N1 = Node->getOperand(1);
2916     SDValue N01 = N0->getOperand(1);
2917     // Both of the shifts must be by the exact same value.
2918     // There should not be any uses of the shift amount outside of the pattern.
2919     if (N1 != N01 || !checkTwoUse(N1))
2920       return false;
2921     if (!matchShiftAmt(N1))
2922       return false;
2923     X = N0->getOperand(0);
2924     return true;
2925   };
2926 
2927   auto matchLowBitMask = [&matchPatternA, &matchPatternB,
2928                           &matchPatternC](SDValue Mask) -> bool {
2929     // FIXME: pattern c.
2930     return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);
2931   };
2932 
2933   if (Node->getOpcode() == ISD::AND) {
2934     X = Node->getOperand(0);
2935     SDValue Mask = Node->getOperand(1);
2936 
2937     if (matchLowBitMask(Mask)) {
2938       // Great.
2939     } else {
2940       std::swap(X, Mask);
2941       if (!matchLowBitMask(Mask))
2942         return false;
2943     }
2944   } else if (!matchPatternD(Node))
2945     return false;
2946 
2947   SDLoc DL(Node);
2948 
2949   SDValue OrigNBits = NBits;
2950   if (NBits.getValueType() != NVT) {
2951     // Truncate the shift amount.
2952     NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);
2953     insertDAGNode(*CurDAG, OrigNBits, NBits);
2954 
2955     // Insert 8-bit NBits into lowest 8 bits of NVT-sized (32 or 64-bit)
2956     // register. All the other bits are undefined, we do not care about them.
2957     SDValue ImplDef =
2958         SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, NVT), 0);
2959     insertDAGNode(*CurDAG, OrigNBits, ImplDef);
2960     NBits =
2961         CurDAG->getTargetInsertSubreg(X86::sub_8bit, DL, NVT, ImplDef, NBits);
2962     insertDAGNode(*CurDAG, OrigNBits, NBits);
2963   }
2964 
2965   if (Subtarget->hasBMI2()) {
2966     // Great, just emit the the BZHI..
2967     SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits);
2968     ReplaceNode(Node, Extract.getNode());
2969     SelectCode(Extract.getNode());
2970     return true;
2971   }
2972 
2973   // Else, emitting BEXTR requires one more step.
2974   // The 'control' of BEXTR has the pattern of:
2975   // [15...8 bit][ 7...0 bit] location
2976   // [ bit count][     shift] name
2977   // I.e. 0b000000011'00000001 means  (x >> 0b1) & 0b11
2978 
2979   // Shift NBits left by 8 bits, thus producing 'control'.
2980   // This makes the low 8 bits to be zero.
2981   SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);
2982   SDValue Control = CurDAG->getNode(ISD::SHL, DL, NVT, NBits, C8);
2983   insertDAGNode(*CurDAG, OrigNBits, Control);
2984 
2985   // If the 'X' is *logically* shifted, we can fold that shift into 'control'.
2986   if (X.getOpcode() == ISD::SRL) {
2987     SDValue ShiftAmt = X.getOperand(1);
2988     X = X.getOperand(0);
2989 
2990     assert(ShiftAmt.getValueType() == MVT::i8 &&
2991            "Expected shift amount to be i8");
2992 
2993     // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!
2994     SDValue OrigShiftAmt = ShiftAmt;
2995     ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, NVT, ShiftAmt);
2996     insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);
2997 
2998     // And now 'or' these low 8 bits of shift amount into the 'control'.
2999     Control = CurDAG->getNode(ISD::OR, DL, NVT, Control, ShiftAmt);
3000     insertDAGNode(*CurDAG, OrigNBits, Control);
3001   }
3002 
3003   // And finally, form the BEXTR itself.
3004   SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, NVT, X, Control);
3005   ReplaceNode(Node, Extract.getNode());
3006   SelectCode(Extract.getNode());
3007 
3008   return true;
3009 }
3010 
3011 // See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
3012 MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {
3013   MVT NVT = Node->getSimpleValueType(0);
3014   SDLoc dl(Node);
3015 
3016   SDValue N0 = Node->getOperand(0);
3017   SDValue N1 = Node->getOperand(1);
3018 
3019   // If we have TBM we can use an immediate for the control. If we have BMI
3020   // we should only do this if the BEXTR instruction is implemented well.
3021   // Otherwise moving the control into a register makes this more costly.
3022   // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
3023   // hoisting the move immediate would make it worthwhile with a less optimal
3024   // BEXTR?
3025   if (!Subtarget->hasTBM() &&
3026       !(Subtarget->hasBMI() && Subtarget->hasFastBEXTR()))
3027     return nullptr;
3028 
3029   // Must have a shift right.
3030   if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
3031     return nullptr;
3032 
3033   // Shift can't have additional users.
3034   if (!N0->hasOneUse())
3035     return nullptr;
3036 
3037   // Only supported for 32 and 64 bits.
3038   if (NVT != MVT::i32 && NVT != MVT::i64)
3039     return nullptr;
3040 
3041   // Shift amount and RHS of and must be constant.
3042   ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
3043   ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
3044   if (!MaskCst || !ShiftCst)
3045     return nullptr;
3046 
3047   // And RHS must be a mask.
3048   uint64_t Mask = MaskCst->getZExtValue();
3049   if (!isMask_64(Mask))
3050     return nullptr;
3051 
3052   uint64_t Shift = ShiftCst->getZExtValue();
3053   uint64_t MaskSize = countPopulation(Mask);
3054 
3055   // Don't interfere with something that can be handled by extracting AH.
3056   // TODO: If we are able to fold a load, BEXTR might still be better than AH.
3057   if (Shift == 8 && MaskSize == 8)
3058     return nullptr;
3059 
3060   // Make sure we are only using bits that were in the original value, not
3061   // shifted in.
3062   if (Shift + MaskSize > NVT.getSizeInBits())
3063     return nullptr;
3064 
3065   SDValue New = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
3066   unsigned ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
3067   unsigned MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
3068 
3069   // BMI requires the immediate to placed in a register.
3070   if (!Subtarget->hasTBM()) {
3071     ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
3072     MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
3073     unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
3074     New = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, New), 0);
3075   }
3076 
3077   MachineSDNode *NewNode;
3078   SDValue Input = N0->getOperand(0);
3079   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3080   if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3081     SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, New, Input.getOperand(0) };
3082     SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
3083     NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3084     // Update the chain.
3085     ReplaceUses(Input.getValue(1), SDValue(NewNode, 1));
3086     // Record the mem-refs
3087     CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});
3088   } else {
3089     NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, Input, New);
3090   }
3091 
3092   return NewNode;
3093 }
3094 
3095 // Emit a PCMISTR(I/M) instruction.
3096 MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
3097                                              bool MayFoldLoad, const SDLoc &dl,
3098                                              MVT VT, SDNode *Node) {
3099   SDValue N0 = Node->getOperand(0);
3100   SDValue N1 = Node->getOperand(1);
3101   SDValue Imm = Node->getOperand(2);
3102   const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3103   Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3104 
3105   // Try to fold a load. No need to check alignment.
3106   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3107   if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3108     SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3109                       N1.getOperand(0) };
3110     SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
3111     MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3112     // Update the chain.
3113     ReplaceUses(N1.getValue(1), SDValue(CNode, 2));
3114     // Record the mem-refs
3115     CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
3116     return CNode;
3117   }
3118 
3119   SDValue Ops[] = { N0, N1, Imm };
3120   SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
3121   MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3122   return CNode;
3123 }
3124 
3125 // Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
3126 // to emit a second instruction after this one. This is needed since we have two
3127 // copyToReg nodes glued before this and we need to continue that glue through.
3128 MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
3129                                              bool MayFoldLoad, const SDLoc &dl,
3130                                              MVT VT, SDNode *Node,
3131                                              SDValue &InFlag) {
3132   SDValue N0 = Node->getOperand(0);
3133   SDValue N2 = Node->getOperand(2);
3134   SDValue Imm = Node->getOperand(4);
3135   const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3136   Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3137 
3138   // Try to fold a load. No need to check alignment.
3139   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3140   if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3141     SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3142                       N2.getOperand(0), InFlag };
3143     SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
3144     MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3145     InFlag = SDValue(CNode, 3);
3146     // Update the chain.
3147     ReplaceUses(N2.getValue(1), SDValue(CNode, 2));
3148     // Record the mem-refs
3149     CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});
3150     return CNode;
3151   }
3152 
3153   SDValue Ops[] = { N0, N2, Imm, InFlag };
3154   SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
3155   MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3156   InFlag = SDValue(CNode, 2);
3157   return CNode;
3158 }
3159 
3160 bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
3161   EVT VT = N->getValueType(0);
3162 
3163   // Only handle scalar shifts.
3164   if (VT.isVector())
3165     return false;
3166 
3167   // Narrower shifts only mask to 5 bits in hardware.
3168   unsigned Size = VT == MVT::i64 ? 64 : 32;
3169 
3170   SDValue OrigShiftAmt = N->getOperand(1);
3171   SDValue ShiftAmt = OrigShiftAmt;
3172   SDLoc DL(N);
3173 
3174   // Skip over a truncate of the shift amount.
3175   if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
3176     ShiftAmt = ShiftAmt->getOperand(0);
3177 
3178   // This function is called after X86DAGToDAGISel::matchBitExtract(),
3179   // so we are not afraid that we might mess up BZHI/BEXTR pattern.
3180 
3181   SDValue NewShiftAmt;
3182   if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) {
3183     SDValue Add0 = ShiftAmt->getOperand(0);
3184     SDValue Add1 = ShiftAmt->getOperand(1);
3185     // If we are shifting by X+/-N where N == 0 mod Size, then just shift by X
3186     // to avoid the ADD/SUB.
3187     if (isa<ConstantSDNode>(Add1) &&
3188         cast<ConstantSDNode>(Add1)->getZExtValue() % Size == 0) {
3189       NewShiftAmt = Add0;
3190     // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
3191     // generate a NEG instead of a SUB of a constant.
3192     } else if (ShiftAmt->getOpcode() == ISD::SUB &&
3193                isa<ConstantSDNode>(Add0) &&
3194                cast<ConstantSDNode>(Add0)->getZExtValue() != 0 &&
3195                cast<ConstantSDNode>(Add0)->getZExtValue() % Size == 0) {
3196       // Insert a negate op.
3197       // TODO: This isn't guaranteed to replace the sub if there is a logic cone
3198       // that uses it that's not a shift.
3199       EVT SubVT = ShiftAmt.getValueType();
3200       SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
3201       SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, Add1);
3202       NewShiftAmt = Neg;
3203 
3204       // Insert these operands into a valid topological order so they can
3205       // get selected independently.
3206       insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
3207       insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
3208     } else
3209       return false;
3210   } else
3211     return false;
3212 
3213   if (NewShiftAmt.getValueType() != MVT::i8) {
3214     // Need to truncate the shift amount.
3215     NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
3216     // Add to a correct topological ordering.
3217     insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3218   }
3219 
3220   // Insert a new mask to keep the shift amount legal. This should be removed
3221   // by isel patterns.
3222   NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
3223                                 CurDAG->getConstant(Size - 1, DL, MVT::i8));
3224   // Place in a correct topological ordering.
3225   insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3226 
3227   SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
3228                                                    NewShiftAmt);
3229   if (UpdatedNode != N) {
3230     // If we found an existing node, we should replace ourselves with that node
3231     // and wait for it to be selected after its other users.
3232     ReplaceNode(N, UpdatedNode);
3233     return true;
3234   }
3235 
3236   // If the original shift amount is now dead, delete it so that we don't run
3237   // it through isel.
3238   if (OrigShiftAmt.getNode()->use_empty())
3239     CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
3240 
3241   // Now that we've optimized the shift amount, defer to normal isel to get
3242   // load folding and legacy vs BMI2 selection without repeating it here.
3243   SelectCode(N);
3244   return true;
3245 }
3246 
3247 /// If the high bits of an 'and' operand are known zero, try setting the
3248 /// high bits of an 'and' constant operand to produce a smaller encoding by
3249 /// creating a small, sign-extended negative immediate rather than a large
3250 /// positive one. This reverses a transform in SimplifyDemandedBits that
3251 /// shrinks mask constants by clearing bits. There is also a possibility that
3252 /// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
3253 /// case, just replace the 'and'. Return 'true' if the node is replaced.
3254 bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
3255   // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
3256   // have immediate operands.
3257   MVT VT = And->getSimpleValueType(0);
3258   if (VT != MVT::i32 && VT != MVT::i64)
3259     return false;
3260 
3261   auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
3262   if (!And1C)
3263     return false;
3264 
3265   // Bail out if the mask constant is already negative. It's can't shrink more.
3266   // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
3267   // patterns to use a 32-bit and instead of a 64-bit and by relying on the
3268   // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
3269   // are negative too.
3270   APInt MaskVal = And1C->getAPIntValue();
3271   unsigned MaskLZ = MaskVal.countLeadingZeros();
3272   if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
3273     return false;
3274 
3275   // Don't extend into the upper 32 bits of a 64 bit mask.
3276   if (VT == MVT::i64 && MaskLZ >= 32) {
3277     MaskLZ -= 32;
3278     MaskVal = MaskVal.trunc(32);
3279   }
3280 
3281   SDValue And0 = And->getOperand(0);
3282   APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
3283   APInt NegMaskVal = MaskVal | HighZeros;
3284 
3285   // If a negative constant would not allow a smaller encoding, there's no need
3286   // to continue. Only change the constant when we know it's a win.
3287   unsigned MinWidth = NegMaskVal.getMinSignedBits();
3288   if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
3289     return false;
3290 
3291   // Extend masks if we truncated above.
3292   if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
3293     NegMaskVal = NegMaskVal.zext(64);
3294     HighZeros = HighZeros.zext(64);
3295   }
3296 
3297   // The variable operand must be all zeros in the top bits to allow using the
3298   // new, negative constant as the mask.
3299   if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
3300     return false;
3301 
3302   // Check if the mask is -1. In that case, this is an unnecessary instruction
3303   // that escaped earlier analysis.
3304   if (NegMaskVal.isAllOnesValue()) {
3305     ReplaceNode(And, And0.getNode());
3306     return true;
3307   }
3308 
3309   // A negative mask allows a smaller encoding. Create a new 'and' node.
3310   SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
3311   SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
3312   ReplaceNode(And, NewAnd.getNode());
3313   SelectCode(NewAnd.getNode());
3314   return true;
3315 }
3316 
3317 void X86DAGToDAGISel::Select(SDNode *Node) {
3318   MVT NVT = Node->getSimpleValueType(0);
3319   unsigned Opcode = Node->getOpcode();
3320   SDLoc dl(Node);
3321 
3322   if (Node->isMachineOpcode()) {
3323     LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
3324     Node->setNodeId(-1);
3325     return;   // Already selected.
3326   }
3327 
3328   switch (Opcode) {
3329   default: break;
3330   case ISD::BRIND: {
3331     if (Subtarget->isTargetNaCl())
3332       // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
3333       // leave the instruction alone.
3334       break;
3335     if (Subtarget->isTarget64BitILP32()) {
3336       // Converts a 32-bit register to a 64-bit, zero-extended version of
3337       // it. This is needed because x86-64 can do many things, but jmp %r32
3338       // ain't one of them.
3339       const SDValue &Target = Node->getOperand(1);
3340       assert(Target.getSimpleValueType() == llvm::MVT::i32);
3341       SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
3342       SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
3343                                       Node->getOperand(0), ZextTarget);
3344       ReplaceNode(Node, Brind.getNode());
3345       SelectCode(ZextTarget.getNode());
3346       SelectCode(Brind.getNode());
3347       return;
3348     }
3349     break;
3350   }
3351   case X86ISD::GlobalBaseReg:
3352     ReplaceNode(Node, getGlobalBaseReg());
3353     return;
3354 
3355   case ISD::BITCAST:
3356     // Just drop all 128/256/512-bit bitcasts.
3357     if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||
3358         NVT == MVT::f128) {
3359       ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
3360       CurDAG->RemoveDeadNode(Node);
3361       return;
3362     }
3363     break;
3364 
3365   case X86ISD::SELECT:
3366   case X86ISD::SHRUNKBLEND: {
3367     // SHRUNKBLEND selects like a regular VSELECT. Same with X86ISD::SELECT.
3368     SDValue VSelect = CurDAG->getNode(
3369         ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
3370         Node->getOperand(1), Node->getOperand(2));
3371     ReplaceNode(Node, VSelect.getNode());
3372     SelectCode(VSelect.getNode());
3373     // We already called ReplaceUses.
3374     return;
3375   }
3376 
3377   case ISD::SRL:
3378     if (matchBitExtract(Node))
3379       return;
3380     LLVM_FALLTHROUGH;
3381   case ISD::SRA:
3382   case ISD::SHL:
3383     if (tryShiftAmountMod(Node))
3384       return;
3385     break;
3386 
3387   case ISD::AND:
3388     if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) {
3389       ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
3390       CurDAG->RemoveDeadNode(Node);
3391       return;
3392     }
3393     if (matchBitExtract(Node))
3394       return;
3395     if (AndImmShrink && shrinkAndImmediate(Node))
3396       return;
3397 
3398     LLVM_FALLTHROUGH;
3399   case ISD::OR:
3400   case ISD::XOR: {
3401 
3402     // For operations of the form (x << C1) op C2, check if we can use a smaller
3403     // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
3404     SDValue N0 = Node->getOperand(0);
3405     SDValue N1 = Node->getOperand(1);
3406 
3407     if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
3408       break;
3409 
3410     // i8 is unshrinkable, i16 should be promoted to i32.
3411     if (NVT != MVT::i32 && NVT != MVT::i64)
3412       break;
3413 
3414     ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
3415     ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
3416     if (!Cst || !ShlCst)
3417       break;
3418 
3419     int64_t Val = Cst->getSExtValue();
3420     uint64_t ShlVal = ShlCst->getZExtValue();
3421 
3422     // Make sure that we don't change the operation by removing bits.
3423     // This only matters for OR and XOR, AND is unaffected.
3424     uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
3425     if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
3426       break;
3427 
3428     unsigned ShlOp, AddOp, Op;
3429     MVT CstVT = NVT;
3430 
3431     // Check the minimum bitwidth for the new constant.
3432     // TODO: AND32ri is the same as AND64ri32 with zext imm.
3433     // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
3434     // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
3435     if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
3436       CstVT = MVT::i8;
3437     else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
3438       CstVT = MVT::i32;
3439 
3440     // Bail if there is no smaller encoding.
3441     if (NVT == CstVT)
3442       break;
3443 
3444     switch (NVT.SimpleTy) {
3445     default: llvm_unreachable("Unsupported VT!");
3446     case MVT::i32:
3447       assert(CstVT == MVT::i8);
3448       ShlOp = X86::SHL32ri;
3449       AddOp = X86::ADD32rr;
3450 
3451       switch (Opcode) {
3452       default: llvm_unreachable("Impossible opcode");
3453       case ISD::AND: Op = X86::AND32ri8; break;
3454       case ISD::OR:  Op =  X86::OR32ri8; break;
3455       case ISD::XOR: Op = X86::XOR32ri8; break;
3456       }
3457       break;
3458     case MVT::i64:
3459       assert(CstVT == MVT::i8 || CstVT == MVT::i32);
3460       ShlOp = X86::SHL64ri;
3461       AddOp = X86::ADD64rr;
3462 
3463       switch (Opcode) {
3464       default: llvm_unreachable("Impossible opcode");
3465       case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
3466       case ISD::OR:  Op = CstVT==MVT::i8?  X86::OR64ri8 :  X86::OR64ri32; break;
3467       case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
3468       }
3469       break;
3470     }
3471 
3472     // Emit the smaller op and the shift.
3473     SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
3474     SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
3475     if (ShlVal == 1)
3476       CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
3477                            SDValue(New, 0));
3478     else
3479       CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
3480                            getI8Imm(ShlVal, dl));
3481     return;
3482   }
3483   case X86ISD::SMUL:
3484     // i16/i32/i64 are handled with isel patterns.
3485     if (NVT != MVT::i8)
3486       break;
3487     LLVM_FALLTHROUGH;
3488   case X86ISD::UMUL: {
3489     SDValue N0 = Node->getOperand(0);
3490     SDValue N1 = Node->getOperand(1);
3491 
3492     unsigned LoReg, ROpc, MOpc;
3493     switch (NVT.SimpleTy) {
3494     default: llvm_unreachable("Unsupported VT!");
3495     case MVT::i8:
3496       LoReg = X86::AL;
3497       ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r;
3498       MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m;
3499       break;
3500     case MVT::i16:
3501       LoReg = X86::AX;
3502       ROpc = X86::MUL16r;
3503       MOpc = X86::MUL16m;
3504       break;
3505     case MVT::i32:
3506       LoReg = X86::EAX;
3507       ROpc = X86::MUL32r;
3508       MOpc = X86::MUL32m;
3509       break;
3510     case MVT::i64:
3511       LoReg = X86::RAX;
3512       ROpc = X86::MUL64r;
3513       MOpc = X86::MUL64m;
3514       break;
3515     }
3516 
3517     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3518     bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
3519     // Multiply is commmutative.
3520     if (!FoldedLoad) {
3521       FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
3522       if (FoldedLoad)
3523         std::swap(N0, N1);
3524     }
3525 
3526     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
3527                                           N0, SDValue()).getValue(1);
3528 
3529     MachineSDNode *CNode;
3530     if (FoldedLoad) {
3531       // i16/i32/i64 use an instruction that produces a low and high result even
3532       // though only the low result is used.
3533       SDVTList VTs;
3534       if (NVT == MVT::i8)
3535         VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
3536       else
3537         VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other);
3538 
3539       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3540                         InFlag };
3541       CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3542 
3543       // Update the chain.
3544       ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3));
3545       // Record the mem-refs
3546       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
3547     } else {
3548       // i16/i32/i64 use an instruction that produces a low and high result even
3549       // though only the low result is used.
3550       SDVTList VTs;
3551       if (NVT == MVT::i8)
3552         VTs = CurDAG->getVTList(NVT, MVT::i32);
3553       else
3554         VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
3555 
3556       CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InFlag});
3557     }
3558 
3559     ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
3560     ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2));
3561     CurDAG->RemoveDeadNode(Node);
3562     return;
3563   }
3564 
3565   case ISD::SMUL_LOHI:
3566   case ISD::UMUL_LOHI: {
3567     SDValue N0 = Node->getOperand(0);
3568     SDValue N1 = Node->getOperand(1);
3569 
3570     unsigned Opc, MOpc;
3571     bool isSigned = Opcode == ISD::SMUL_LOHI;
3572     if (!isSigned) {
3573       switch (NVT.SimpleTy) {
3574       default: llvm_unreachable("Unsupported VT!");
3575       case MVT::i32: Opc = X86::MUL32r; MOpc = X86::MUL32m; break;
3576       case MVT::i64: Opc = X86::MUL64r; MOpc = X86::MUL64m; break;
3577       }
3578     } else {
3579       switch (NVT.SimpleTy) {
3580       default: llvm_unreachable("Unsupported VT!");
3581       case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
3582       case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
3583       }
3584     }
3585 
3586     unsigned SrcReg, LoReg, HiReg;
3587     switch (Opc) {
3588     default: llvm_unreachable("Unknown MUL opcode!");
3589     case X86::IMUL32r:
3590     case X86::MUL32r:
3591       SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
3592       break;
3593     case X86::IMUL64r:
3594     case X86::MUL64r:
3595       SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
3596       break;
3597     }
3598 
3599     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3600     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
3601     // Multiply is commmutative.
3602     if (!foldedLoad) {
3603       foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
3604       if (foldedLoad)
3605         std::swap(N0, N1);
3606     }
3607 
3608     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
3609                                           N0, SDValue()).getValue(1);
3610     if (foldedLoad) {
3611       SDValue Chain;
3612       MachineSDNode *CNode = nullptr;
3613       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3614                         InFlag };
3615       SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
3616       CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3617       Chain = SDValue(CNode, 0);
3618       InFlag = SDValue(CNode, 1);
3619 
3620       // Update the chain.
3621       ReplaceUses(N1.getValue(1), Chain);
3622       // Record the mem-refs
3623       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
3624     } else {
3625       SDValue Ops[] = { N1, InFlag };
3626       SDVTList VTs = CurDAG->getVTList(MVT::Glue);
3627       SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
3628       InFlag = SDValue(CNode, 0);
3629     }
3630 
3631     // Copy the low half of the result, if it is needed.
3632     if (!SDValue(Node, 0).use_empty()) {
3633       assert(LoReg && "Register for low half is not defined!");
3634       SDValue ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg,
3635                                              NVT, InFlag);
3636       InFlag = ResLo.getValue(2);
3637       ReplaceUses(SDValue(Node, 0), ResLo);
3638       LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);
3639                  dbgs() << '\n');
3640     }
3641     // Copy the high half of the result, if it is needed.
3642     if (!SDValue(Node, 1).use_empty()) {
3643       assert(HiReg && "Register for high half is not defined!");
3644       SDValue ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg,
3645                                              NVT, InFlag);
3646       InFlag = ResHi.getValue(2);
3647       ReplaceUses(SDValue(Node, 1), ResHi);
3648       LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);
3649                  dbgs() << '\n');
3650     }
3651 
3652     CurDAG->RemoveDeadNode(Node);
3653     return;
3654   }
3655 
3656   case ISD::SDIVREM:
3657   case ISD::UDIVREM: {
3658     SDValue N0 = Node->getOperand(0);
3659     SDValue N1 = Node->getOperand(1);
3660 
3661     unsigned Opc, MOpc;
3662     bool isSigned = Opcode == ISD::SDIVREM;
3663     if (!isSigned) {
3664       switch (NVT.SimpleTy) {
3665       default: llvm_unreachable("Unsupported VT!");
3666       case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
3667       case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
3668       case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
3669       case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
3670       }
3671     } else {
3672       switch (NVT.SimpleTy) {
3673       default: llvm_unreachable("Unsupported VT!");
3674       case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
3675       case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
3676       case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
3677       case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
3678       }
3679     }
3680 
3681     unsigned LoReg, HiReg, ClrReg;
3682     unsigned SExtOpcode;
3683     switch (NVT.SimpleTy) {
3684     default: llvm_unreachable("Unsupported VT!");
3685     case MVT::i8:
3686       LoReg = X86::AL;  ClrReg = HiReg = X86::AH;
3687       SExtOpcode = X86::CBW;
3688       break;
3689     case MVT::i16:
3690       LoReg = X86::AX;  HiReg = X86::DX;
3691       ClrReg = X86::DX;
3692       SExtOpcode = X86::CWD;
3693       break;
3694     case MVT::i32:
3695       LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
3696       SExtOpcode = X86::CDQ;
3697       break;
3698     case MVT::i64:
3699       LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
3700       SExtOpcode = X86::CQO;
3701       break;
3702     }
3703 
3704     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3705     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
3706     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
3707 
3708     SDValue InFlag;
3709     if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
3710       // Special case for div8, just use a move with zero extension to AX to
3711       // clear the upper 8 bits (AH).
3712       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;
3713       MachineSDNode *Move;
3714       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3715         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
3716         Move = CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
3717                                       MVT::Other, Ops);
3718         Chain = SDValue(Move, 1);
3719         ReplaceUses(N0.getValue(1), Chain);
3720         // Record the mem-refs
3721         CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});
3722       } else {
3723         Move = CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0);
3724         Chain = CurDAG->getEntryNode();
3725       }
3726       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::EAX, SDValue(Move, 0),
3727                                     SDValue());
3728       InFlag = Chain.getValue(1);
3729     } else {
3730       InFlag =
3731         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
3732                              LoReg, N0, SDValue()).getValue(1);
3733       if (isSigned && !signBitIsZero) {
3734         // Sign extend the low part into the high part.
3735         InFlag =
3736           SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
3737       } else {
3738         // Zero out the high part, effectively zero extending the input.
3739         SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
3740         switch (NVT.SimpleTy) {
3741         case MVT::i16:
3742           ClrNode =
3743               SDValue(CurDAG->getMachineNode(
3744                           TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
3745                           CurDAG->getTargetConstant(X86::sub_16bit, dl,
3746                                                     MVT::i32)),
3747                       0);
3748           break;
3749         case MVT::i32:
3750           break;
3751         case MVT::i64:
3752           ClrNode =
3753               SDValue(CurDAG->getMachineNode(
3754                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
3755                           CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
3756                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
3757                                                     MVT::i32)),
3758                       0);
3759           break;
3760         default:
3761           llvm_unreachable("Unexpected division source");
3762         }
3763 
3764         InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
3765                                       ClrNode, InFlag).getValue(1);
3766       }
3767     }
3768 
3769     if (foldedLoad) {
3770       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
3771                         InFlag };
3772       MachineSDNode *CNode =
3773         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
3774       InFlag = SDValue(CNode, 1);
3775       // Update the chain.
3776       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
3777       // Record the mem-refs
3778       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
3779     } else {
3780       InFlag =
3781         SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
3782     }
3783 
3784     // Prevent use of AH in a REX instruction by explicitly copying it to
3785     // an ABCD_L register.
3786     //
3787     // The current assumption of the register allocator is that isel
3788     // won't generate explicit references to the GR8_ABCD_H registers. If
3789     // the allocator and/or the backend get enhanced to be more robust in
3790     // that regard, this can be, and should be, removed.
3791     if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
3792       SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
3793       unsigned AHExtOpcode =
3794           isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
3795 
3796       SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
3797                                              MVT::Glue, AHCopy, InFlag);
3798       SDValue Result(RNode, 0);
3799       InFlag = SDValue(RNode, 1);
3800 
3801       Result =
3802           CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
3803 
3804       ReplaceUses(SDValue(Node, 1), Result);
3805       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3806                  dbgs() << '\n');
3807     }
3808     // Copy the division (low) result, if it is needed.
3809     if (!SDValue(Node, 0).use_empty()) {
3810       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3811                                                 LoReg, NVT, InFlag);
3812       InFlag = Result.getValue(2);
3813       ReplaceUses(SDValue(Node, 0), Result);
3814       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3815                  dbgs() << '\n');
3816     }
3817     // Copy the remainder (high) result, if it is needed.
3818     if (!SDValue(Node, 1).use_empty()) {
3819       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
3820                                               HiReg, NVT, InFlag);
3821       InFlag = Result.getValue(2);
3822       ReplaceUses(SDValue(Node, 1), Result);
3823       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
3824                  dbgs() << '\n');
3825     }
3826     CurDAG->RemoveDeadNode(Node);
3827     return;
3828   }
3829 
3830   case X86ISD::CMP: {
3831     SDValue N0 = Node->getOperand(0);
3832     SDValue N1 = Node->getOperand(1);
3833 
3834     // Optimizations for TEST compares.
3835     if (!isNullConstant(N1))
3836       break;
3837 
3838     // Save the original VT of the compare.
3839     MVT CmpVT = N0.getSimpleValueType();
3840 
3841     // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed
3842     // by a test instruction. The test should be removed later by
3843     // analyzeCompare if we are using only the zero flag.
3844     // TODO: Should we check the users and use the BEXTR flags directly?
3845     if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
3846       if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) {
3847         unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr
3848                                              : X86::TEST32rr;
3849         SDValue BEXTR = SDValue(NewNode, 0);
3850         NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR);
3851         ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
3852         CurDAG->RemoveDeadNode(Node);
3853         return;
3854       }
3855     }
3856 
3857     // We can peek through truncates, but we need to be careful below.
3858     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
3859       N0 = N0.getOperand(0);
3860 
3861     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
3862     // use a smaller encoding.
3863     // Look past the truncate if CMP is the only use of it.
3864     if (N0.getOpcode() == ISD::AND &&
3865         N0.getNode()->hasOneUse() &&
3866         N0.getValueType() != MVT::i8) {
3867       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3868       if (!C) break;
3869       uint64_t Mask = C->getZExtValue();
3870 
3871       // Check if we can replace AND+IMM64 with a shift. This is possible for
3872       // masks/ like 0xFF000000 or 0x00FFFFFF and if we care only about the zero
3873       // flag.
3874       if (CmpVT == MVT::i64 && !isInt<32>(Mask) &&
3875           onlyUsesZeroFlag(SDValue(Node, 0))) {
3876         if (isMask_64(~Mask)) {
3877           unsigned TrailingZeros = countTrailingZeros(Mask);
3878           SDValue Imm = CurDAG->getTargetConstant(TrailingZeros, dl, MVT::i64);
3879           SDValue Shift =
3880             SDValue(CurDAG->getMachineNode(X86::SHR64ri, dl, MVT::i64,
3881                                            N0.getOperand(0), Imm), 0);
3882           MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl,
3883                                                        MVT::i32, Shift, Shift);
3884           ReplaceNode(Node, Test);
3885           return;
3886         }
3887         if (isMask_64(Mask)) {
3888           unsigned LeadingZeros = countLeadingZeros(Mask);
3889           SDValue Imm = CurDAG->getTargetConstant(LeadingZeros, dl, MVT::i64);
3890           SDValue Shift =
3891             SDValue(CurDAG->getMachineNode(X86::SHL64ri, dl, MVT::i64,
3892                                            N0.getOperand(0), Imm), 0);
3893           MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl,
3894                                                        MVT::i32, Shift, Shift);
3895           ReplaceNode(Node, Test);
3896           return;
3897         }
3898       }
3899 
3900       MVT VT;
3901       int SubRegOp;
3902       unsigned ROpc, MOpc;
3903 
3904       // For each of these checks we need to be careful if the sign flag is
3905       // being used. It is only safe to use the sign flag in two conditions,
3906       // either the sign bit in the shrunken mask is zero or the final test
3907       // size is equal to the original compare size.
3908 
3909       if (isUInt<8>(Mask) &&
3910           (!(Mask & 0x80) || CmpVT == MVT::i8 ||
3911            hasNoSignFlagUses(SDValue(Node, 0)))) {
3912         // For example, convert "testl %eax, $8" to "testb %al, $8"
3913         VT = MVT::i8;
3914         SubRegOp = X86::sub_8bit;
3915         ROpc = X86::TEST8ri;
3916         MOpc = X86::TEST8mi;
3917       } else if (OptForMinSize && isUInt<16>(Mask) &&
3918                  (!(Mask & 0x8000) || CmpVT == MVT::i16 ||
3919                   hasNoSignFlagUses(SDValue(Node, 0)))) {
3920         // For example, "testl %eax, $32776" to "testw %ax, $32776".
3921         // NOTE: We only want to form TESTW instructions if optimizing for
3922         // min size. Otherwise we only save one byte and possibly get a length
3923         // changing prefix penalty in the decoders.
3924         VT = MVT::i16;
3925         SubRegOp = X86::sub_16bit;
3926         ROpc = X86::TEST16ri;
3927         MOpc = X86::TEST16mi;
3928       } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
3929                  ((!(Mask & 0x80000000) &&
3930                    // Without minsize 16-bit Cmps can get here so we need to
3931                    // be sure we calculate the correct sign flag if needed.
3932                    (CmpVT != MVT::i16 || !(Mask & 0x8000))) ||
3933                   CmpVT == MVT::i32 ||
3934                   hasNoSignFlagUses(SDValue(Node, 0)))) {
3935         // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
3936         // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
3937         // Otherwize, we find ourselves in a position where we have to do
3938         // promotion. If previous passes did not promote the and, we assume
3939         // they had a good reason not to and do not promote here.
3940         VT = MVT::i32;
3941         SubRegOp = X86::sub_32bit;
3942         ROpc = X86::TEST32ri;
3943         MOpc = X86::TEST32mi;
3944       } else {
3945         // No eligible transformation was found.
3946         break;
3947       }
3948 
3949       // FIXME: We should be able to fold loads here.
3950 
3951       SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
3952       SDValue Reg = N0.getOperand(0);
3953 
3954       // Emit a testl or testw.
3955       MachineSDNode *NewNode;
3956       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3957       if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3958         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3959                           Reg.getOperand(0) };
3960         NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops);
3961         // Update the chain.
3962         ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1));
3963         // Record the mem-refs
3964         CurDAG->setNodeMemRefs(NewNode,
3965                                {cast<LoadSDNode>(Reg)->getMemOperand()});
3966       } else {
3967         // Extract the subregister if necessary.
3968         if (N0.getValueType() != VT)
3969           Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
3970 
3971         NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm);
3972       }
3973       // Replace CMP with TEST.
3974       ReplaceNode(Node, NewNode);
3975       return;
3976     }
3977     break;
3978   }
3979   case X86ISD::PCMPISTR: {
3980     if (!Subtarget->hasSSE42())
3981       break;
3982 
3983     bool NeedIndex = !SDValue(Node, 0).use_empty();
3984     bool NeedMask = !SDValue(Node, 1).use_empty();
3985     // We can't fold a load if we are going to make two instructions.
3986     bool MayFoldLoad = !NeedIndex || !NeedMask;
3987 
3988     MachineSDNode *CNode;
3989     if (NeedMask) {
3990       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr;
3991       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm;
3992       CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
3993       ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
3994     }
3995     if (NeedIndex || !NeedMask) {
3996       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr;
3997       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm;
3998       CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
3999       ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4000     }
4001 
4002     // Connect the flag usage to the last instruction created.
4003     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
4004     CurDAG->RemoveDeadNode(Node);
4005     return;
4006   }
4007   case X86ISD::PCMPESTR: {
4008     if (!Subtarget->hasSSE42())
4009       break;
4010 
4011     // Copy the two implicit register inputs.
4012     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
4013                                           Node->getOperand(1),
4014                                           SDValue()).getValue(1);
4015     InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
4016                                   Node->getOperand(3), InFlag).getValue(1);
4017 
4018     bool NeedIndex = !SDValue(Node, 0).use_empty();
4019     bool NeedMask = !SDValue(Node, 1).use_empty();
4020     // We can't fold a load if we are going to make two instructions.
4021     bool MayFoldLoad = !NeedIndex || !NeedMask;
4022 
4023     MachineSDNode *CNode;
4024     if (NeedMask) {
4025       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr;
4026       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm;
4027       CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node,
4028                            InFlag);
4029       ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
4030     }
4031     if (NeedIndex || !NeedMask) {
4032       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr;
4033       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm;
4034       CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag);
4035       ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4036     }
4037     // Connect the flag usage to the last instruction created.
4038     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
4039     CurDAG->RemoveDeadNode(Node);
4040     return;
4041   }
4042 
4043   case ISD::STORE:
4044     if (foldLoadStoreIntoMemOperand(Node))
4045       return;
4046     break;
4047   }
4048 
4049   SelectCode(Node);
4050 }
4051 
4052 bool X86DAGToDAGISel::
4053 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
4054                              std::vector<SDValue> &OutOps) {
4055   SDValue Op0, Op1, Op2, Op3, Op4;
4056   switch (ConstraintID) {
4057   default:
4058     llvm_unreachable("Unexpected asm memory constraint");
4059   case InlineAsm::Constraint_i:
4060     // FIXME: It seems strange that 'i' is needed here since it's supposed to
4061     //        be an immediate and not a memory constraint.
4062     LLVM_FALLTHROUGH;
4063   case InlineAsm::Constraint_o: // offsetable        ??
4064   case InlineAsm::Constraint_v: // not offsetable    ??
4065   case InlineAsm::Constraint_m: // memory
4066   case InlineAsm::Constraint_X:
4067     if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
4068       return true;
4069     break;
4070   }
4071 
4072   OutOps.push_back(Op0);
4073   OutOps.push_back(Op1);
4074   OutOps.push_back(Op2);
4075   OutOps.push_back(Op3);
4076   OutOps.push_back(Op4);
4077   return false;
4078 }
4079 
4080 /// This pass converts a legalized DAG into a X86-specific DAG,
4081 /// ready for instruction scheduling.
4082 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
4083                                      CodeGenOpt::Level OptLevel) {
4084   return new X86DAGToDAGISel(TM, OptLevel);
4085 }
4086