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