1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a DAG pattern matching instruction selector for X86,
11 // converting from a legalized dag to a X86 dag.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86.h"
16 #include "X86InstrBuilder.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86RegisterInfo.h"
19 #include "X86Subtarget.h"
20 #include "X86TargetMachine.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAGISel.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include <stdint.h>
38 using namespace llvm;
39 
40 #define DEBUG_TYPE "x86-isel"
41 
42 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
43 
44 //===----------------------------------------------------------------------===//
45 //                      Pattern Matcher Implementation
46 //===----------------------------------------------------------------------===//
47 
48 namespace {
49   /// This corresponds to X86AddressMode, but uses SDValue's instead of register
50   /// numbers for the leaves of the matched tree.
51   struct X86ISelAddressMode {
52     enum {
53       RegBase,
54       FrameIndexBase
55     } BaseType;
56 
57     // This is really a union, discriminated by BaseType!
58     SDValue Base_Reg;
59     int Base_FrameIndex;
60 
61     unsigned Scale;
62     SDValue IndexReg;
63     int32_t Disp;
64     SDValue Segment;
65     const GlobalValue *GV;
66     const Constant *CP;
67     const BlockAddress *BlockAddr;
68     const char *ES;
69     MCSymbol *MCSym;
70     int JT;
71     unsigned Align;    // CP alignment.
72     unsigned char SymbolFlags;  // X86II::MO_*
73 
74     X86ISelAddressMode()
75         : BaseType(RegBase), Base_FrameIndex(0), Scale(1), IndexReg(), Disp(0),
76           Segment(), GV(nullptr), CP(nullptr), BlockAddr(nullptr), ES(nullptr),
77           MCSym(nullptr), JT(-1), Align(0), SymbolFlags(X86II::MO_NO_FLAG) {}
78 
79     bool hasSymbolicDisplacement() const {
80       return GV != nullptr || CP != nullptr || ES != nullptr ||
81              MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
82     }
83 
84     bool hasBaseOrIndexReg() const {
85       return BaseType == FrameIndexBase ||
86              IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
87     }
88 
89     /// Return true if this addressing mode is already RIP-relative.
90     bool isRIPRelative() const {
91       if (BaseType != RegBase) return false;
92       if (RegisterSDNode *RegNode =
93             dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
94         return RegNode->getReg() == X86::RIP;
95       return false;
96     }
97 
98     void setBaseReg(SDValue Reg) {
99       BaseType = RegBase;
100       Base_Reg = Reg;
101     }
102 
103 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
104     void dump() {
105       dbgs() << "X86ISelAddressMode " << this << '\n';
106       dbgs() << "Base_Reg ";
107       if (Base_Reg.getNode())
108         Base_Reg.getNode()->dump();
109       else
110         dbgs() << "nul";
111       dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n'
112              << " Scale" << Scale << '\n'
113              << "IndexReg ";
114       if (IndexReg.getNode())
115         IndexReg.getNode()->dump();
116       else
117         dbgs() << "nul";
118       dbgs() << " Disp " << Disp << '\n'
119              << "GV ";
120       if (GV)
121         GV->dump();
122       else
123         dbgs() << "nul";
124       dbgs() << " CP ";
125       if (CP)
126         CP->dump();
127       else
128         dbgs() << "nul";
129       dbgs() << '\n'
130              << "ES ";
131       if (ES)
132         dbgs() << ES;
133       else
134         dbgs() << "nul";
135       dbgs() << " MCSym ";
136       if (MCSym)
137         dbgs() << MCSym;
138       else
139         dbgs() << "nul";
140       dbgs() << " JT" << JT << " Align" << Align << '\n';
141     }
142 #endif
143   };
144 }
145 
146 namespace {
147   //===--------------------------------------------------------------------===//
148   /// ISel - X86-specific code to select X86 machine instructions for
149   /// SelectionDAG operations.
150   ///
151   class X86DAGToDAGISel final : public SelectionDAGISel {
152     /// Keep a pointer to the X86Subtarget around so that we can
153     /// make the right decision when generating code for different targets.
154     const X86Subtarget *Subtarget;
155 
156     /// If true, selector should try to optimize for code size instead of
157     /// performance.
158     bool OptForSize;
159 
160     /// If true, selector should try to optimize for minimum code size.
161     bool OptForMinSize;
162 
163   public:
164     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
165         : SelectionDAGISel(tm, OptLevel), OptForSize(false),
166           OptForMinSize(false) {}
167 
168     const char *getPassName() const override {
169       return "X86 DAG->DAG Instruction Selection";
170     }
171 
172     bool runOnMachineFunction(MachineFunction &MF) override {
173       // Reset the subtarget each time through.
174       Subtarget = &MF.getSubtarget<X86Subtarget>();
175       SelectionDAGISel::runOnMachineFunction(MF);
176       return true;
177     }
178 
179     void EmitFunctionEntryCode() override;
180 
181     bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
182 
183     void PreprocessISelDAG() override;
184 
185     inline bool immSext8(SDNode *N) const {
186       return isInt<8>(cast<ConstantSDNode>(N)->getSExtValue());
187     }
188 
189     // True if the 64-bit immediate fits in a 32-bit sign-extended field.
190     inline bool i64immSExt32(SDNode *N) const {
191       uint64_t v = cast<ConstantSDNode>(N)->getZExtValue();
192       return (int64_t)v == (int32_t)v;
193     }
194 
195 // Include the pieces autogenerated from the target description.
196 #include "X86GenDAGISel.inc"
197 
198   private:
199     SDNode *Select(SDNode *N) override;
200     SDNode *selectGather(SDNode *N, unsigned Opc);
201 
202     bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
203     bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
204     bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
205     bool matchAddress(SDValue N, X86ISelAddressMode &AM);
206     bool 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, SDValue N,
227                              SDValue &Base, SDValue &Scale,
228                              SDValue &Index, SDValue &Disp,
229                              SDValue &Segment,
230                              SDValue &NodeWithChain);
231 
232     bool tryFoldLoad(SDNode *P, SDValue N,
233                      SDValue &Base, SDValue &Scale,
234                      SDValue &Index, SDValue &Disp,
235                      SDValue &Segment);
236 
237     /// Implement addressing mode selection for inline asm expressions.
238     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
239                                       unsigned ConstraintID,
240                                       std::vector<SDValue> &OutOps) override;
241 
242     void emitSpecialCodeForMain();
243 
244     inline void getAddressOperands(X86ISelAddressMode &AM, SDLoc DL,
245                                    SDValue &Base, SDValue &Scale,
246                                    SDValue &Index, SDValue &Disp,
247                                    SDValue &Segment) {
248       Base = (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
249                  ? CurDAG->getTargetFrameIndex(
250                        AM.Base_FrameIndex,
251                        TLI->getPointerTy(CurDAG->getDataLayout()))
252                  : AM.Base_Reg;
253       Scale = getI8Imm(AM.Scale, DL);
254       Index = AM.IndexReg;
255       // These are 32-bit even in 64-bit mode since RIP-relative offset
256       // is 32-bit.
257       if (AM.GV)
258         Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
259                                               MVT::i32, AM.Disp,
260                                               AM.SymbolFlags);
261       else if (AM.CP)
262         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
263                                              AM.Align, AM.Disp, AM.SymbolFlags);
264       else if (AM.ES) {
265         assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
266         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
267       } else if (AM.MCSym) {
268         assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
269         assert(AM.SymbolFlags == 0 && "oo");
270         Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
271       } else if (AM.JT != -1) {
272         assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
273         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
274       } else if (AM.BlockAddr)
275         Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
276                                              AM.SymbolFlags);
277       else
278         Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
279 
280       if (AM.Segment.getNode())
281         Segment = AM.Segment;
282       else
283         Segment = CurDAG->getRegister(0, MVT::i32);
284     }
285 
286     // Utility function to determine whether we should avoid selecting
287     // immediate forms of instructions for better code size or not.
288     // At a high level, we'd like to avoid such instructions when
289     // we have similar constants used within the same basic block
290     // that can be kept in a register.
291     //
292     bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
293       uint32_t UseCount = 0;
294 
295       // Do not want to hoist if we're not optimizing for size.
296       // TODO: We'd like to remove this restriction.
297       // See the comment in X86InstrInfo.td for more info.
298       if (!OptForSize)
299         return false;
300 
301       // Walk all the users of the immediate.
302       for (SDNode::use_iterator UI = N->use_begin(),
303            UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
304 
305         SDNode *User = *UI;
306 
307         // This user is already selected. Count it as a legitimate use and
308         // move on.
309         if (User->isMachineOpcode()) {
310           UseCount++;
311           continue;
312         }
313 
314         // We want to count stores of immediates as real uses.
315         if (User->getOpcode() == ISD::STORE &&
316             User->getOperand(1).getNode() == N) {
317           UseCount++;
318           continue;
319         }
320 
321         // We don't currently match users that have > 2 operands (except
322         // for stores, which are handled above)
323         // Those instruction won't match in ISEL, for now, and would
324         // be counted incorrectly.
325         // This may change in the future as we add additional instruction
326         // types.
327         if (User->getNumOperands() != 2)
328           continue;
329 
330         // Immediates that are used for offsets as part of stack
331         // manipulation should be left alone. These are typically
332         // used to indicate SP offsets for argument passing and
333         // will get pulled into stores/pushes (implicitly).
334         if (User->getOpcode() == X86ISD::ADD ||
335             User->getOpcode() == ISD::ADD    ||
336             User->getOpcode() == X86ISD::SUB ||
337             User->getOpcode() == ISD::SUB) {
338 
339           // Find the other operand of the add/sub.
340           SDValue OtherOp = User->getOperand(0);
341           if (OtherOp.getNode() == N)
342             OtherOp = User->getOperand(1);
343 
344           // Don't count if the other operand is SP.
345           RegisterSDNode *RegNode;
346           if (OtherOp->getOpcode() == ISD::CopyFromReg &&
347               (RegNode = dyn_cast_or_null<RegisterSDNode>(
348                  OtherOp->getOperand(1).getNode())))
349             if ((RegNode->getReg() == X86::ESP) ||
350                 (RegNode->getReg() == X86::RSP))
351               continue;
352         }
353 
354         // ... otherwise, count this and move on.
355         UseCount++;
356       }
357 
358       // If we have more than 1 use, then recommend for hoisting.
359       return (UseCount > 1);
360     }
361 
362     /// Return a target constant with the specified value of type i8.
363     inline SDValue getI8Imm(unsigned Imm, SDLoc DL) {
364       return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
365     }
366 
367     /// Return a target constant with the specified value, of type i32.
368     inline SDValue getI32Imm(unsigned Imm, SDLoc DL) {
369       return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
370     }
371 
372     /// Return an SDNode that returns the value of the global base register.
373     /// Output instructions required to initialize the global base register,
374     /// if necessary.
375     SDNode *getGlobalBaseReg();
376 
377     /// Return a reference to the TargetMachine, casted to the target-specific
378     /// type.
379     const X86TargetMachine &getTargetMachine() const {
380       return static_cast<const X86TargetMachine &>(TM);
381     }
382 
383     /// Return a reference to the TargetInstrInfo, casted to the target-specific
384     /// type.
385     const X86InstrInfo *getInstrInfo() const {
386       return Subtarget->getInstrInfo();
387     }
388 
389     /// \brief Address-mode matching performs shift-of-and to and-of-shift
390     /// reassociation in order to expose more scaled addressing
391     /// opportunities.
392     bool ComplexPatternFuncMutatesDAG() const override {
393       return true;
394     }
395   };
396 }
397 
398 
399 bool
400 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
401   if (OptLevel == CodeGenOpt::None) return false;
402 
403   if (!N.hasOneUse())
404     return false;
405 
406   if (N.getOpcode() != ISD::LOAD)
407     return true;
408 
409   // If N is a load, do additional profitability checks.
410   if (U == Root) {
411     switch (U->getOpcode()) {
412     default: break;
413     case X86ISD::ADD:
414     case X86ISD::SUB:
415     case X86ISD::AND:
416     case X86ISD::XOR:
417     case X86ISD::OR:
418     case ISD::ADD:
419     case ISD::ADDC:
420     case ISD::ADDE:
421     case ISD::AND:
422     case ISD::OR:
423     case ISD::XOR: {
424       SDValue Op1 = U->getOperand(1);
425 
426       // If the other operand is a 8-bit immediate we should fold the immediate
427       // instead. This reduces code size.
428       // e.g.
429       // movl 4(%esp), %eax
430       // addl $4, %eax
431       // vs.
432       // movl $4, %eax
433       // addl 4(%esp), %eax
434       // The former is 2 bytes shorter. In case where the increment is 1, then
435       // the saving can be 4 bytes (by using incl %eax).
436       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1))
437         if (Imm->getAPIntValue().isSignedIntN(8))
438           return false;
439 
440       // If the other operand is a TLS address, we should fold it instead.
441       // This produces
442       // movl    %gs:0, %eax
443       // leal    i@NTPOFF(%eax), %eax
444       // instead of
445       // movl    $i@NTPOFF, %eax
446       // addl    %gs:0, %eax
447       // if the block also has an access to a second TLS address this will save
448       // a load.
449       // FIXME: This is probably also true for non-TLS addresses.
450       if (Op1.getOpcode() == X86ISD::Wrapper) {
451         SDValue Val = Op1.getOperand(0);
452         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
453           return false;
454       }
455     }
456     }
457   }
458 
459   return true;
460 }
461 
462 /// Replace the original chain operand of the call with
463 /// load's chain operand and move load below the call's chain operand.
464 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
465                                SDValue Call, SDValue OrigChain) {
466   SmallVector<SDValue, 8> Ops;
467   SDValue Chain = OrigChain.getOperand(0);
468   if (Chain.getNode() == Load.getNode())
469     Ops.push_back(Load.getOperand(0));
470   else {
471     assert(Chain.getOpcode() == ISD::TokenFactor &&
472            "Unexpected chain operand");
473     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
474       if (Chain.getOperand(i).getNode() == Load.getNode())
475         Ops.push_back(Load.getOperand(0));
476       else
477         Ops.push_back(Chain.getOperand(i));
478     SDValue NewChain =
479       CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
480     Ops.clear();
481     Ops.push_back(NewChain);
482   }
483   Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
484   CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
485   CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
486                              Load.getOperand(1), Load.getOperand(2));
487 
488   Ops.clear();
489   Ops.push_back(SDValue(Load.getNode(), 1));
490   Ops.append(Call->op_begin() + 1, Call->op_end());
491   CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
492 }
493 
494 /// Return true if call address is a load and it can be
495 /// moved below CALLSEQ_START and the chains leading up to the call.
496 /// Return the CALLSEQ_START by reference as a second output.
497 /// In the case of a tail call, there isn't a callseq node between the call
498 /// chain and the load.
499 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
500   // The transformation is somewhat dangerous if the call's chain was glued to
501   // the call. After MoveBelowOrigChain the load is moved between the call and
502   // the chain, this can create a cycle if the load is not folded. So it is
503   // *really* important that we are sure the load will be folded.
504   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
505     return false;
506   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
507   if (!LD ||
508       LD->isVolatile() ||
509       LD->getAddressingMode() != ISD::UNINDEXED ||
510       LD->getExtensionType() != ISD::NON_EXTLOAD)
511     return false;
512 
513   // Now let's find the callseq_start.
514   while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
515     if (!Chain.hasOneUse())
516       return false;
517     Chain = Chain.getOperand(0);
518   }
519 
520   if (!Chain.getNumOperands())
521     return false;
522   // Since we are not checking for AA here, conservatively abort if the chain
523   // writes to memory. It's not safe to move the callee (a load) across a store.
524   if (isa<MemSDNode>(Chain.getNode()) &&
525       cast<MemSDNode>(Chain.getNode())->writeMem())
526     return false;
527   if (Chain.getOperand(0).getNode() == Callee.getNode())
528     return true;
529   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
530       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
531       Callee.getValue(1).hasOneUse())
532     return true;
533   return false;
534 }
535 
536 void X86DAGToDAGISel::PreprocessISelDAG() {
537   // OptFor[Min]Size are used in pattern predicates that isel is matching.
538   OptForSize = MF->getFunction()->optForSize();
539   OptForMinSize = MF->getFunction()->optForMinSize();
540   assert((!OptForMinSize || OptForSize) && "OptForMinSize implies OptForSize");
541 
542   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
543        E = CurDAG->allnodes_end(); I != E; ) {
544     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
545 
546     if (OptLevel != CodeGenOpt::None &&
547         // Only does this when target favors doesn't favor register indirect
548         // call.
549         ((N->getOpcode() == X86ISD::CALL && !Subtarget->callRegIndirect()) ||
550          (N->getOpcode() == X86ISD::TC_RETURN &&
551           // Only does this if load can be folded into TC_RETURN.
552           (Subtarget->is64Bit() ||
553            getTargetMachine().getRelocationModel() != Reloc::PIC_)))) {
554       /// Also try moving call address load from outside callseq_start to just
555       /// before the call to allow it to be folded.
556       ///
557       ///     [Load chain]
558       ///         ^
559       ///         |
560       ///       [Load]
561       ///       ^    ^
562       ///       |    |
563       ///      /      \--
564       ///     /          |
565       ///[CALLSEQ_START] |
566       ///     ^          |
567       ///     |          |
568       /// [LOAD/C2Reg]   |
569       ///     |          |
570       ///      \        /
571       ///       \      /
572       ///       [CALL]
573       bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
574       SDValue Chain = N->getOperand(0);
575       SDValue Load  = N->getOperand(1);
576       if (!isCalleeLoad(Load, Chain, HasCallSeq))
577         continue;
578       moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
579       ++NumLoadMoved;
580       continue;
581     }
582 
583     // Lower fpround and fpextend nodes that target the FP stack to be store and
584     // load to the stack.  This is a gross hack.  We would like to simply mark
585     // these as being illegal, but when we do that, legalize produces these when
586     // it expands calls, then expands these in the same legalize pass.  We would
587     // like dag combine to be able to hack on these between the call expansion
588     // and the node legalization.  As such this pass basically does "really
589     // late" legalization of these inline with the X86 isel pass.
590     // FIXME: This should only happen when not compiled with -O0.
591     if (N->getOpcode() != ISD::FP_ROUND && N->getOpcode() != ISD::FP_EXTEND)
592       continue;
593 
594     MVT SrcVT = N->getOperand(0).getSimpleValueType();
595     MVT DstVT = N->getSimpleValueType(0);
596 
597     // If any of the sources are vectors, no fp stack involved.
598     if (SrcVT.isVector() || DstVT.isVector())
599       continue;
600 
601     // If the source and destination are SSE registers, then this is a legal
602     // conversion that should not be lowered.
603     const X86TargetLowering *X86Lowering =
604         static_cast<const X86TargetLowering *>(TLI);
605     bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
606     bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
607     if (SrcIsSSE && DstIsSSE)
608       continue;
609 
610     if (!SrcIsSSE && !DstIsSSE) {
611       // If this is an FPStack extension, it is a noop.
612       if (N->getOpcode() == ISD::FP_EXTEND)
613         continue;
614       // If this is a value-preserving FPStack truncation, it is a noop.
615       if (N->getConstantOperandVal(1))
616         continue;
617     }
618 
619     // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
620     // FPStack has extload and truncstore.  SSE can fold direct loads into other
621     // operations.  Based on this, decide what we want to do.
622     MVT MemVT;
623     if (N->getOpcode() == ISD::FP_ROUND)
624       MemVT = DstVT;  // FP_ROUND must use DstVT, we can't do a 'trunc load'.
625     else
626       MemVT = SrcIsSSE ? SrcVT : DstVT;
627 
628     SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
629     SDLoc dl(N);
630 
631     // FIXME: optimize the case where the src/dest is a load or store?
632     SDValue Store = CurDAG->getTruncStore(CurDAG->getEntryNode(), dl,
633                                           N->getOperand(0),
634                                           MemTmp, MachinePointerInfo(), MemVT,
635                                           false, false, 0);
636     SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, MemTmp,
637                                         MachinePointerInfo(),
638                                         MemVT, false, false, false, 0);
639 
640     // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
641     // extload we created.  This will cause general havok on the dag because
642     // anything below the conversion could be folded into other existing nodes.
643     // To avoid invalidating 'I', back it up to the convert node.
644     --I;
645     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
646 
647     // Now that we did that, the node is dead.  Increment the iterator to the
648     // next node to process, then delete N.
649     ++I;
650     CurDAG->DeleteNode(N);
651   }
652 }
653 
654 
655 /// Emit any code that needs to be executed only in the main function.
656 void X86DAGToDAGISel::emitSpecialCodeForMain() {
657   if (Subtarget->isTargetCygMing()) {
658     TargetLowering::ArgListTy Args;
659     auto &DL = CurDAG->getDataLayout();
660 
661     TargetLowering::CallLoweringInfo CLI(*CurDAG);
662     CLI.setChain(CurDAG->getRoot())
663         .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
664                    CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
665                    std::move(Args), 0);
666     const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
667     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
668     CurDAG->setRoot(Result.second);
669   }
670 }
671 
672 void X86DAGToDAGISel::EmitFunctionEntryCode() {
673   // If this is main, emit special code for main.
674   if (const Function *Fn = MF->getFunction())
675     if (Fn->hasExternalLinkage() && Fn->getName() == "main")
676       emitSpecialCodeForMain();
677 }
678 
679 static bool isDispSafeForFrameIndex(int64_t Val) {
680   // On 64-bit platforms, we can run into an issue where a frame index
681   // includes a displacement that, when added to the explicit displacement,
682   // will overflow the displacement field. Assuming that the frame index
683   // displacement fits into a 31-bit integer  (which is only slightly more
684   // aggressive than the current fundamental assumption that it fits into
685   // a 32-bit integer), a 31-bit disp should always be safe.
686   return isInt<31>(Val);
687 }
688 
689 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
690                                             X86ISelAddressMode &AM) {
691   // Cannot combine ExternalSymbol displacements with integer offsets.
692   if (Offset != 0 && (AM.ES || AM.MCSym))
693     return true;
694   int64_t Val = AM.Disp + Offset;
695   CodeModel::Model M = TM.getCodeModel();
696   if (Subtarget->is64Bit()) {
697     if (!X86::isOffsetSuitableForCodeModel(Val, M,
698                                            AM.hasSymbolicDisplacement()))
699       return true;
700     // In addition to the checks required for a register base, check that
701     // we do not try to use an unsafe Disp with a frame index.
702     if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
703         !isDispSafeForFrameIndex(Val))
704       return true;
705   }
706   AM.Disp = Val;
707   return false;
708 
709 }
710 
711 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
712   SDValue Address = N->getOperand(1);
713 
714   // load gs:0 -> GS segment register.
715   // load fs:0 -> FS segment register.
716   //
717   // This optimization is valid because the GNU TLS model defines that
718   // gs:0 (or fs:0 on X86-64) contains its own address.
719   // For more information see http://people.redhat.com/drepper/tls.pdf
720   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
721     if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
722         Subtarget->isTargetLinux())
723       switch (N->getPointerInfo().getAddrSpace()) {
724       case 256:
725         AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
726         return false;
727       case 257:
728         AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
729         return false;
730       }
731 
732   return true;
733 }
734 
735 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
736 /// mode. These wrap things that will resolve down into a symbol reference.
737 /// If no match is possible, this returns true, otherwise it returns false.
738 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
739   // If the addressing mode already has a symbol as the displacement, we can
740   // never match another symbol.
741   if (AM.hasSymbolicDisplacement())
742     return true;
743 
744   SDValue N0 = N.getOperand(0);
745   CodeModel::Model M = TM.getCodeModel();
746 
747   // Handle X86-64 rip-relative addresses.  We check this before checking direct
748   // folding because RIP is preferable to non-RIP accesses.
749   if (Subtarget->is64Bit() && N.getOpcode() == X86ISD::WrapperRIP &&
750       // Under X86-64 non-small code model, GV (and friends) are 64-bits, so
751       // they cannot be folded into immediate fields.
752       // FIXME: This can be improved for kernel and other models?
753       (M == CodeModel::Small || M == CodeModel::Kernel)) {
754     // Base and index reg must be 0 in order to use %rip as base.
755     if (AM.hasBaseOrIndexReg())
756       return true;
757     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
758       X86ISelAddressMode Backup = AM;
759       AM.GV = G->getGlobal();
760       AM.SymbolFlags = G->getTargetFlags();
761       if (foldOffsetIntoAddress(G->getOffset(), AM)) {
762         AM = Backup;
763         return true;
764       }
765     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
766       X86ISelAddressMode Backup = AM;
767       AM.CP = CP->getConstVal();
768       AM.Align = CP->getAlignment();
769       AM.SymbolFlags = CP->getTargetFlags();
770       if (foldOffsetIntoAddress(CP->getOffset(), AM)) {
771         AM = Backup;
772         return true;
773       }
774     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
775       AM.ES = S->getSymbol();
776       AM.SymbolFlags = S->getTargetFlags();
777     } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
778       AM.MCSym = S->getMCSymbol();
779     } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
780       AM.JT = J->getIndex();
781       AM.SymbolFlags = J->getTargetFlags();
782     } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
783       X86ISelAddressMode Backup = AM;
784       AM.BlockAddr = BA->getBlockAddress();
785       AM.SymbolFlags = BA->getTargetFlags();
786       if (foldOffsetIntoAddress(BA->getOffset(), AM)) {
787         AM = Backup;
788         return true;
789       }
790     } else
791       llvm_unreachable("Unhandled symbol reference node.");
792 
793     if (N.getOpcode() == X86ISD::WrapperRIP)
794       AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
795     return false;
796   }
797 
798   // Handle the case when globals fit in our immediate field: This is true for
799   // X86-32 always and X86-64 when in -mcmodel=small mode.  In 64-bit
800   // mode, this only applies to a non-RIP-relative computation.
801   if (!Subtarget->is64Bit() ||
802       M == CodeModel::Small || M == CodeModel::Kernel) {
803     assert(N.getOpcode() != X86ISD::WrapperRIP &&
804            "RIP-relative addressing already handled");
805     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
806       AM.GV = G->getGlobal();
807       AM.Disp += G->getOffset();
808       AM.SymbolFlags = G->getTargetFlags();
809     } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
810       AM.CP = CP->getConstVal();
811       AM.Align = CP->getAlignment();
812       AM.Disp += CP->getOffset();
813       AM.SymbolFlags = CP->getTargetFlags();
814     } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
815       AM.ES = S->getSymbol();
816       AM.SymbolFlags = S->getTargetFlags();
817     } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
818       AM.MCSym = S->getMCSymbol();
819     } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
820       AM.JT = J->getIndex();
821       AM.SymbolFlags = J->getTargetFlags();
822     } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
823       AM.BlockAddr = BA->getBlockAddress();
824       AM.Disp += BA->getOffset();
825       AM.SymbolFlags = BA->getTargetFlags();
826     } else
827       llvm_unreachable("Unhandled symbol reference node.");
828     return false;
829   }
830 
831   return true;
832 }
833 
834 /// Add the specified node to the specified addressing mode, returning true if
835 /// it cannot be done. This just pattern matches for the addressing mode.
836 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
837   if (matchAddressRecursively(N, AM, 0))
838     return true;
839 
840   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
841   // a smaller encoding and avoids a scaled-index.
842   if (AM.Scale == 2 &&
843       AM.BaseType == X86ISelAddressMode::RegBase &&
844       AM.Base_Reg.getNode() == nullptr) {
845     AM.Base_Reg = AM.IndexReg;
846     AM.Scale = 1;
847   }
848 
849   // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
850   // because it has a smaller encoding.
851   // TODO: Which other code models can use this?
852   if (TM.getCodeModel() == CodeModel::Small &&
853       Subtarget->is64Bit() &&
854       AM.Scale == 1 &&
855       AM.BaseType == X86ISelAddressMode::RegBase &&
856       AM.Base_Reg.getNode() == nullptr &&
857       AM.IndexReg.getNode() == nullptr &&
858       AM.SymbolFlags == X86II::MO_NO_FLAG &&
859       AM.hasSymbolicDisplacement())
860     AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
861 
862   return false;
863 }
864 
865 bool X86DAGToDAGISel::matchAdd(SDValue N, X86ISelAddressMode &AM,
866                                unsigned Depth) {
867   // Add an artificial use to this node so that we can keep track of
868   // it if it gets CSE'd with a different node.
869   HandleSDNode Handle(N);
870 
871   X86ISelAddressMode Backup = AM;
872   if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
873       !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
874     return false;
875   AM = Backup;
876 
877   // Try again after commuting the operands.
878   if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1) &&
879       !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth+1))
880     return false;
881   AM = Backup;
882 
883   // If we couldn't fold both operands into the address at the same time,
884   // see if we can just put each operand into a register and fold at least
885   // the add.
886   if (AM.BaseType == X86ISelAddressMode::RegBase &&
887       !AM.Base_Reg.getNode() &&
888       !AM.IndexReg.getNode()) {
889     N = Handle.getValue();
890     AM.Base_Reg = N.getOperand(0);
891     AM.IndexReg = N.getOperand(1);
892     AM.Scale = 1;
893     return false;
894   }
895   N = Handle.getValue();
896   return true;
897 }
898 
899 // Insert a node into the DAG at least before the Pos node's position. This
900 // will reposition the node as needed, and will assign it a node ID that is <=
901 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
902 // IDs! The selection DAG must no longer depend on their uniqueness when this
903 // is used.
904 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
905   if (N.getNode()->getNodeId() == -1 ||
906       N.getNode()->getNodeId() > Pos.getNode()->getNodeId()) {
907     DAG.RepositionNode(Pos.getNode()->getIterator(), N.getNode());
908     N.getNode()->setNodeId(Pos.getNode()->getNodeId());
909   }
910 }
911 
912 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
913 // safe. This allows us to convert the shift and and into an h-register
914 // extract and a scaled index. Returns false if the simplification is
915 // performed.
916 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
917                                       uint64_t Mask,
918                                       SDValue Shift, SDValue X,
919                                       X86ISelAddressMode &AM) {
920   if (Shift.getOpcode() != ISD::SRL ||
921       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
922       !Shift.hasOneUse())
923     return true;
924 
925   int ScaleLog = 8 - Shift.getConstantOperandVal(1);
926   if (ScaleLog <= 0 || ScaleLog >= 4 ||
927       Mask != (0xffu << ScaleLog))
928     return true;
929 
930   MVT VT = N.getSimpleValueType();
931   SDLoc DL(N);
932   SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
933   SDValue NewMask = DAG.getConstant(0xff, DL, VT);
934   SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
935   SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
936   SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
937   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
938 
939   // Insert the new nodes into the topological ordering. We must do this in
940   // a valid topological ordering as nothing is going to go back and re-sort
941   // these nodes. We continually insert before 'N' in sequence as this is
942   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
943   // hierarchy left to express.
944   insertDAGNode(DAG, N, Eight);
945   insertDAGNode(DAG, N, Srl);
946   insertDAGNode(DAG, N, NewMask);
947   insertDAGNode(DAG, N, And);
948   insertDAGNode(DAG, N, ShlCount);
949   insertDAGNode(DAG, N, Shl);
950   DAG.ReplaceAllUsesWith(N, Shl);
951   AM.IndexReg = And;
952   AM.Scale = (1 << ScaleLog);
953   return false;
954 }
955 
956 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
957 // allows us to fold the shift into this addressing mode. Returns false if the
958 // transform succeeded.
959 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
960                                         uint64_t Mask,
961                                         SDValue Shift, SDValue X,
962                                         X86ISelAddressMode &AM) {
963   if (Shift.getOpcode() != ISD::SHL ||
964       !isa<ConstantSDNode>(Shift.getOperand(1)))
965     return true;
966 
967   // Not likely to be profitable if either the AND or SHIFT node has more
968   // than one use (unless all uses are for address computation). Besides,
969   // isel mechanism requires their node ids to be reused.
970   if (!N.hasOneUse() || !Shift.hasOneUse())
971     return true;
972 
973   // Verify that the shift amount is something we can fold.
974   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
975   if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
976     return true;
977 
978   MVT VT = N.getSimpleValueType();
979   SDLoc DL(N);
980   SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
981   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
982   SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
983 
984   // Insert the new nodes into the topological ordering. We must do this in
985   // a valid topological ordering as nothing is going to go back and re-sort
986   // these nodes. We continually insert before 'N' in sequence as this is
987   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
988   // hierarchy left to express.
989   insertDAGNode(DAG, N, NewMask);
990   insertDAGNode(DAG, N, NewAnd);
991   insertDAGNode(DAG, N, NewShift);
992   DAG.ReplaceAllUsesWith(N, NewShift);
993 
994   AM.Scale = 1 << ShiftAmt;
995   AM.IndexReg = NewAnd;
996   return false;
997 }
998 
999 // Implement some heroics to detect shifts of masked values where the mask can
1000 // be replaced by extending the shift and undoing that in the addressing mode
1001 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1002 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1003 // the addressing mode. This results in code such as:
1004 //
1005 //   int f(short *y, int *lookup_table) {
1006 //     ...
1007 //     return *y + lookup_table[*y >> 11];
1008 //   }
1009 //
1010 // Turning into:
1011 //   movzwl (%rdi), %eax
1012 //   movl %eax, %ecx
1013 //   shrl $11, %ecx
1014 //   addl (%rsi,%rcx,4), %eax
1015 //
1016 // Instead of:
1017 //   movzwl (%rdi), %eax
1018 //   movl %eax, %ecx
1019 //   shrl $9, %ecx
1020 //   andl $124, %rcx
1021 //   addl (%rsi,%rcx), %eax
1022 //
1023 // Note that this function assumes the mask is provided as a mask *after* the
1024 // value is shifted. The input chain may or may not match that, but computing
1025 // such a mask is trivial.
1026 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1027                                     uint64_t Mask,
1028                                     SDValue Shift, SDValue X,
1029                                     X86ISelAddressMode &AM) {
1030   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1031       !isa<ConstantSDNode>(Shift.getOperand(1)))
1032     return true;
1033 
1034   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1035   unsigned MaskLZ = countLeadingZeros(Mask);
1036   unsigned MaskTZ = countTrailingZeros(Mask);
1037 
1038   // The amount of shift we're trying to fit into the addressing mode is taken
1039   // from the trailing zeros of the mask.
1040   unsigned AMShiftAmt = MaskTZ;
1041 
1042   // There is nothing we can do here unless the mask is removing some bits.
1043   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1044   if (AMShiftAmt <= 0 || AMShiftAmt > 3) return true;
1045 
1046   // We also need to ensure that mask is a continuous run of bits.
1047   if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1048 
1049   // Scale the leading zero count down based on the actual size of the value.
1050   // Also scale it down based on the size of the shift.
1051   MaskLZ -= (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1052 
1053   // The final check is to ensure that any masked out high bits of X are
1054   // already known to be zero. Otherwise, the mask has a semantic impact
1055   // other than masking out a couple of low bits. Unfortunately, because of
1056   // the mask, zero extensions will be removed from operands in some cases.
1057   // This code works extra hard to look through extensions because we can
1058   // replace them with zero extensions cheaply if necessary.
1059   bool ReplacingAnyExtend = false;
1060   if (X.getOpcode() == ISD::ANY_EXTEND) {
1061     unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1062                           X.getOperand(0).getSimpleValueType().getSizeInBits();
1063     // Assume that we'll replace the any-extend with a zero-extend, and
1064     // narrow the search to the extended value.
1065     X = X.getOperand(0);
1066     MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1067     ReplacingAnyExtend = true;
1068   }
1069   APInt MaskedHighBits =
1070     APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1071   APInt KnownZero, KnownOne;
1072   DAG.computeKnownBits(X, KnownZero, KnownOne);
1073   if (MaskedHighBits != KnownZero) return true;
1074 
1075   // We've identified a pattern that can be transformed into a single shift
1076   // and an addressing mode. Make it so.
1077   MVT VT = N.getSimpleValueType();
1078   if (ReplacingAnyExtend) {
1079     assert(X.getValueType() != VT);
1080     // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1081     SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1082     insertDAGNode(DAG, N, NewX);
1083     X = NewX;
1084   }
1085   SDLoc DL(N);
1086   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1087   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1088   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1089   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1090 
1091   // Insert the new nodes into the topological ordering. We must do this in
1092   // a valid topological ordering as nothing is going to go back and re-sort
1093   // these nodes. We continually insert before 'N' in sequence as this is
1094   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1095   // hierarchy left to express.
1096   insertDAGNode(DAG, N, NewSRLAmt);
1097   insertDAGNode(DAG, N, NewSRL);
1098   insertDAGNode(DAG, N, NewSHLAmt);
1099   insertDAGNode(DAG, N, NewSHL);
1100   DAG.ReplaceAllUsesWith(N, NewSHL);
1101 
1102   AM.Scale = 1 << AMShiftAmt;
1103   AM.IndexReg = NewSRL;
1104   return false;
1105 }
1106 
1107 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
1108                                               unsigned Depth) {
1109   SDLoc dl(N);
1110   DEBUG({
1111       dbgs() << "MatchAddress: ";
1112       AM.dump();
1113     });
1114   // Limit recursion.
1115   if (Depth > 5)
1116     return matchAddressBase(N, AM);
1117 
1118   // If this is already a %rip relative address, we can only merge immediates
1119   // into it.  Instead of handling this in every case, we handle it here.
1120   // RIP relative addressing: %rip + 32-bit displacement!
1121   if (AM.isRIPRelative()) {
1122     // FIXME: JumpTable and ExternalSymbol address currently don't like
1123     // displacements.  It isn't very important, but this should be fixed for
1124     // consistency.
1125     if (!(AM.ES || AM.MCSym) && AM.JT != -1)
1126       return true;
1127 
1128     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
1129       if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
1130         return false;
1131     return true;
1132   }
1133 
1134   switch (N.getOpcode()) {
1135   default: break;
1136   case ISD::LOCAL_RECOVER: {
1137     if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
1138       if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
1139         // Use the symbol and don't prefix it.
1140         AM.MCSym = ESNode->getMCSymbol();
1141         return false;
1142       }
1143     break;
1144   }
1145   case ISD::Constant: {
1146     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1147     if (!foldOffsetIntoAddress(Val, AM))
1148       return false;
1149     break;
1150   }
1151 
1152   case X86ISD::Wrapper:
1153   case X86ISD::WrapperRIP:
1154     if (!matchWrapper(N, AM))
1155       return false;
1156     break;
1157 
1158   case ISD::LOAD:
1159     if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
1160       return false;
1161     break;
1162 
1163   case ISD::FrameIndex:
1164     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1165         AM.Base_Reg.getNode() == nullptr &&
1166         (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
1167       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1168       AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1169       return false;
1170     }
1171     break;
1172 
1173   case ISD::SHL:
1174     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
1175       break;
1176 
1177     if (ConstantSDNode
1178           *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1))) {
1179       unsigned Val = CN->getZExtValue();
1180       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
1181       // that the base operand remains free for further matching. If
1182       // the base doesn't end up getting used, a post-processing step
1183       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
1184       if (Val == 1 || Val == 2 || Val == 3) {
1185         AM.Scale = 1 << Val;
1186         SDValue ShVal = N.getNode()->getOperand(0);
1187 
1188         // Okay, we know that we have a scale by now.  However, if the scaled
1189         // value is an add of something and a constant, we can fold the
1190         // constant into the disp field here.
1191         if (CurDAG->isBaseWithConstantOffset(ShVal)) {
1192           AM.IndexReg = ShVal.getNode()->getOperand(0);
1193           ConstantSDNode *AddVal =
1194             cast<ConstantSDNode>(ShVal.getNode()->getOperand(1));
1195           uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
1196           if (!foldOffsetIntoAddress(Disp, AM))
1197             return false;
1198         }
1199 
1200         AM.IndexReg = ShVal;
1201         return false;
1202       }
1203     }
1204     break;
1205 
1206   case ISD::SRL: {
1207     // Scale must not be used already.
1208     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1209 
1210     SDValue And = N.getOperand(0);
1211     if (And.getOpcode() != ISD::AND) break;
1212     SDValue X = And.getOperand(0);
1213 
1214     // We only handle up to 64-bit values here as those are what matter for
1215     // addressing mode optimizations.
1216     if (X.getSimpleValueType().getSizeInBits() > 64) break;
1217 
1218     // The mask used for the transform is expected to be post-shift, but we
1219     // found the shift first so just apply the shift to the mask before passing
1220     // it down.
1221     if (!isa<ConstantSDNode>(N.getOperand(1)) ||
1222         !isa<ConstantSDNode>(And.getOperand(1)))
1223       break;
1224     uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
1225 
1226     // Try to fold the mask and shift into the scale, and return false if we
1227     // succeed.
1228     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
1229       return false;
1230     break;
1231   }
1232 
1233   case ISD::SMUL_LOHI:
1234   case ISD::UMUL_LOHI:
1235     // A mul_lohi where we need the low part can be folded as a plain multiply.
1236     if (N.getResNo() != 0) break;
1237     // FALL THROUGH
1238   case ISD::MUL:
1239   case X86ISD::MUL_IMM:
1240     // X*[3,5,9] -> X+X*[2,4,8]
1241     if (AM.BaseType == X86ISelAddressMode::RegBase &&
1242         AM.Base_Reg.getNode() == nullptr &&
1243         AM.IndexReg.getNode() == nullptr) {
1244       if (ConstantSDNode
1245             *CN = dyn_cast<ConstantSDNode>(N.getNode()->getOperand(1)))
1246         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
1247             CN->getZExtValue() == 9) {
1248           AM.Scale = unsigned(CN->getZExtValue())-1;
1249 
1250           SDValue MulVal = N.getNode()->getOperand(0);
1251           SDValue Reg;
1252 
1253           // Okay, we know that we have a scale by now.  However, if the scaled
1254           // value is an add of something and a constant, we can fold the
1255           // constant into the disp field here.
1256           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1257               isa<ConstantSDNode>(MulVal.getNode()->getOperand(1))) {
1258             Reg = MulVal.getNode()->getOperand(0);
1259             ConstantSDNode *AddVal =
1260               cast<ConstantSDNode>(MulVal.getNode()->getOperand(1));
1261             uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
1262             if (foldOffsetIntoAddress(Disp, AM))
1263               Reg = N.getNode()->getOperand(0);
1264           } else {
1265             Reg = N.getNode()->getOperand(0);
1266           }
1267 
1268           AM.IndexReg = AM.Base_Reg = Reg;
1269           return false;
1270         }
1271     }
1272     break;
1273 
1274   case ISD::SUB: {
1275     // Given A-B, if A can be completely folded into the address and
1276     // the index field with the index field unused, use -B as the index.
1277     // This is a win if a has multiple parts that can be folded into
1278     // the address. Also, this saves a mov if the base register has
1279     // other uses, since it avoids a two-address sub instruction, however
1280     // it costs an additional mov if the index register has other uses.
1281 
1282     // Add an artificial use to this node so that we can keep track of
1283     // it if it gets CSE'd with a different node.
1284     HandleSDNode Handle(N);
1285 
1286     // Test if the LHS of the sub can be folded.
1287     X86ISelAddressMode Backup = AM;
1288     if (matchAddressRecursively(N.getNode()->getOperand(0), AM, Depth+1)) {
1289       AM = Backup;
1290       break;
1291     }
1292     // Test if the index field is free for use.
1293     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
1294       AM = Backup;
1295       break;
1296     }
1297 
1298     int Cost = 0;
1299     SDValue RHS = Handle.getValue().getNode()->getOperand(1);
1300     // If the RHS involves a register with multiple uses, this
1301     // transformation incurs an extra mov, due to the neg instruction
1302     // clobbering its operand.
1303     if (!RHS.getNode()->hasOneUse() ||
1304         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
1305         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
1306         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
1307         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
1308          RHS.getNode()->getOperand(0).getValueType() == MVT::i32))
1309       ++Cost;
1310     // If the base is a register with multiple uses, this
1311     // transformation may save a mov.
1312     if ((AM.BaseType == X86ISelAddressMode::RegBase &&
1313          AM.Base_Reg.getNode() &&
1314          !AM.Base_Reg.getNode()->hasOneUse()) ||
1315         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1316       --Cost;
1317     // If the folded LHS was interesting, this transformation saves
1318     // address arithmetic.
1319     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
1320         ((AM.Disp != 0) && (Backup.Disp == 0)) +
1321         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
1322       --Cost;
1323     // If it doesn't look like it may be an overall win, don't do it.
1324     if (Cost >= 0) {
1325       AM = Backup;
1326       break;
1327     }
1328 
1329     // Ok, the transformation is legal and appears profitable. Go for it.
1330     SDValue Zero = CurDAG->getConstant(0, dl, N.getValueType());
1331     SDValue Neg = CurDAG->getNode(ISD::SUB, dl, N.getValueType(), Zero, RHS);
1332     AM.IndexReg = Neg;
1333     AM.Scale = 1;
1334 
1335     // Insert the new nodes into the topological ordering.
1336     insertDAGNode(*CurDAG, N, Zero);
1337     insertDAGNode(*CurDAG, N, Neg);
1338     return false;
1339   }
1340 
1341   case ISD::ADD:
1342     if (!matchAdd(N, AM, Depth))
1343       return false;
1344     break;
1345 
1346   case ISD::OR:
1347     // We want to look through a transform in InstCombine and DAGCombiner that
1348     // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
1349     // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
1350     // An 'lea' can then be used to match the shift (multiply) and add:
1351     // and $1, %esi
1352     // lea (%rsi, %rdi, 8), %rax
1353     if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
1354         !matchAdd(N, AM, Depth))
1355       return false;
1356     break;
1357 
1358   case ISD::AND: {
1359     // Perform some heroic transforms on an and of a constant-count shift
1360     // with a constant to enable use of the scaled offset field.
1361 
1362     // Scale must not be used already.
1363     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
1364 
1365     SDValue Shift = N.getOperand(0);
1366     if (Shift.getOpcode() != ISD::SRL && Shift.getOpcode() != ISD::SHL) break;
1367     SDValue X = Shift.getOperand(0);
1368 
1369     // We only handle up to 64-bit values here as those are what matter for
1370     // addressing mode optimizations.
1371     if (X.getSimpleValueType().getSizeInBits() > 64) break;
1372 
1373     if (!isa<ConstantSDNode>(N.getOperand(1)))
1374       break;
1375     uint64_t Mask = N.getConstantOperandVal(1);
1376 
1377     // Try to fold the mask and shift into an extract and scale.
1378     if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
1379       return false;
1380 
1381     // Try to fold the mask and shift directly into the scale.
1382     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
1383       return false;
1384 
1385     // Try to swap the mask and shift to place shifts which can be done as
1386     // a scale on the outside of the mask.
1387     if (!foldMaskedShiftToScaledMask(*CurDAG, N, Mask, Shift, X, AM))
1388       return false;
1389     break;
1390   }
1391   }
1392 
1393   return matchAddressBase(N, AM);
1394 }
1395 
1396 /// Helper for MatchAddress. Add the specified node to the
1397 /// specified addressing mode without any further recursion.
1398 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
1399   // Is the base register already occupied?
1400   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
1401     // If so, check to see if the scale index register is set.
1402     if (!AM.IndexReg.getNode()) {
1403       AM.IndexReg = N;
1404       AM.Scale = 1;
1405       return false;
1406     }
1407 
1408     // Otherwise, we cannot select it.
1409     return true;
1410   }
1411 
1412   // Default, generate it as a register.
1413   AM.BaseType = X86ISelAddressMode::RegBase;
1414   AM.Base_Reg = N;
1415   return false;
1416 }
1417 
1418 bool X86DAGToDAGISel::selectVectorAddr(SDNode *Parent, SDValue N, SDValue &Base,
1419                                       SDValue &Scale, SDValue &Index,
1420                                       SDValue &Disp, SDValue &Segment) {
1421 
1422   MaskedGatherScatterSDNode *Mgs = dyn_cast<MaskedGatherScatterSDNode>(Parent);
1423   if (!Mgs)
1424     return false;
1425   X86ISelAddressMode AM;
1426   unsigned AddrSpace = Mgs->getPointerInfo().getAddrSpace();
1427   // AddrSpace 256 -> GS, 257 -> FS.
1428   if (AddrSpace == 256)
1429     AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1430   if (AddrSpace == 257)
1431     AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1432 
1433   SDLoc DL(N);
1434   Base = Mgs->getBasePtr();
1435   Index = Mgs->getIndex();
1436   unsigned ScalarSize = Mgs->getValue().getValueType().getScalarSizeInBits();
1437   Scale = getI8Imm(ScalarSize/8, DL);
1438 
1439   // If Base is 0, the whole address is in index and the Scale is 1
1440   if (isa<ConstantSDNode>(Base)) {
1441     assert(cast<ConstantSDNode>(Base)->isNullValue() &&
1442            "Unexpected base in gather/scatter");
1443     Scale = getI8Imm(1, DL);
1444     Base = CurDAG->getRegister(0, MVT::i32);
1445   }
1446   if (AM.Segment.getNode())
1447     Segment = AM.Segment;
1448   else
1449     Segment = CurDAG->getRegister(0, MVT::i32);
1450   Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1451   return true;
1452 }
1453 
1454 /// Returns true if it is able to pattern match an addressing mode.
1455 /// It returns the operands which make up the maximal addressing mode it can
1456 /// match by reference.
1457 ///
1458 /// Parent is the parent node of the addr operand that is being matched.  It
1459 /// is always a load, store, atomic node, or null.  It is only null when
1460 /// checking memory operands for inline asm nodes.
1461 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
1462                                  SDValue &Scale, SDValue &Index,
1463                                  SDValue &Disp, SDValue &Segment) {
1464   X86ISelAddressMode AM;
1465 
1466   if (Parent &&
1467       // This list of opcodes are all the nodes that have an "addr:$ptr" operand
1468       // that are not a MemSDNode, and thus don't have proper addrspace info.
1469       Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
1470       Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
1471       Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
1472       Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
1473       Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
1474     unsigned AddrSpace =
1475       cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
1476     // AddrSpace 256 -> GS, 257 -> FS.
1477     if (AddrSpace == 256)
1478       AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1479     if (AddrSpace == 257)
1480       AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1481   }
1482 
1483   if (matchAddress(N, AM))
1484     return false;
1485 
1486   MVT VT = N.getSimpleValueType();
1487   if (AM.BaseType == X86ISelAddressMode::RegBase) {
1488     if (!AM.Base_Reg.getNode())
1489       AM.Base_Reg = CurDAG->getRegister(0, VT);
1490   }
1491 
1492   if (!AM.IndexReg.getNode())
1493     AM.IndexReg = CurDAG->getRegister(0, VT);
1494 
1495   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1496   return true;
1497 }
1498 
1499 /// Match a scalar SSE load. In particular, we want to match a load whose top
1500 /// elements are either undef or zeros. The load flavor is derived from the
1501 /// type of N, which is either v4f32 or v2f64.
1502 ///
1503 /// We also return:
1504 ///   PatternChainNode: this is the matched node that has a chain input and
1505 ///   output.
1506 bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root,
1507                                           SDValue N, SDValue &Base,
1508                                           SDValue &Scale, SDValue &Index,
1509                                           SDValue &Disp, SDValue &Segment,
1510                                           SDValue &PatternNodeWithChain) {
1511   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR) {
1512     PatternNodeWithChain = N.getOperand(0);
1513     if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
1514         PatternNodeWithChain.hasOneUse() &&
1515         IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1516         IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1517       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
1518       if (!selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1519         return false;
1520       return true;
1521     }
1522   }
1523 
1524   // Also handle the case where we explicitly require zeros in the top
1525   // elements.  This is a vector shuffle from the zero vector.
1526   if (N.getOpcode() == X86ISD::VZEXT_MOVL && N.getNode()->hasOneUse() &&
1527       // Check to see if the top elements are all zeros (or bitcast of zeros).
1528       N.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
1529       N.getOperand(0).getNode()->hasOneUse() &&
1530       ISD::isNON_EXTLoad(N.getOperand(0).getOperand(0).getNode()) &&
1531       N.getOperand(0).getOperand(0).hasOneUse() &&
1532       IsProfitableToFold(N.getOperand(0), N.getNode(), Root) &&
1533       IsLegalToFold(N.getOperand(0), N.getNode(), Root, OptLevel)) {
1534     // Okay, this is a zero extending load.  Fold it.
1535     LoadSDNode *LD = cast<LoadSDNode>(N.getOperand(0).getOperand(0));
1536     if (!selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp, Segment))
1537       return false;
1538     PatternNodeWithChain = SDValue(LD, 0);
1539     return true;
1540   }
1541   return false;
1542 }
1543 
1544 
1545 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
1546   if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1547     uint64_t ImmVal = CN->getZExtValue();
1548     if ((uint32_t)ImmVal != (uint64_t)ImmVal)
1549       return false;
1550 
1551     Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
1552     return true;
1553   }
1554 
1555   // In static codegen with small code model, we can get the address of a label
1556   // into a register with 'movl'. TableGen has already made sure we're looking
1557   // at a label of some kind.
1558   assert(N->getOpcode() == X86ISD::Wrapper &&
1559          "Unexpected node type for MOV32ri64");
1560   N = N.getOperand(0);
1561 
1562   if (N->getOpcode() != ISD::TargetConstantPool &&
1563       N->getOpcode() != ISD::TargetJumpTable &&
1564       N->getOpcode() != ISD::TargetGlobalAddress &&
1565       N->getOpcode() != ISD::TargetExternalSymbol &&
1566       N->getOpcode() != ISD::MCSymbol &&
1567       N->getOpcode() != ISD::TargetBlockAddress)
1568     return false;
1569 
1570   Imm = N;
1571   return TM.getCodeModel() == CodeModel::Small;
1572 }
1573 
1574 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
1575                                          SDValue &Scale, SDValue &Index,
1576                                          SDValue &Disp, SDValue &Segment) {
1577   if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
1578     return false;
1579 
1580   SDLoc DL(N);
1581   RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
1582   if (RN && RN->getReg() == 0)
1583     Base = CurDAG->getRegister(0, MVT::i64);
1584   else if (Base.getValueType() == MVT::i32 && !dyn_cast<FrameIndexSDNode>(Base)) {
1585     // Base could already be %rip, particularly in the x32 ABI.
1586     Base = SDValue(CurDAG->getMachineNode(
1587                        TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1588                        CurDAG->getTargetConstant(0, DL, MVT::i64),
1589                        Base,
1590                        CurDAG->getTargetConstant(X86::sub_32bit, DL, MVT::i32)),
1591                    0);
1592   }
1593 
1594   RN = dyn_cast<RegisterSDNode>(Index);
1595   if (RN && RN->getReg() == 0)
1596     Index = CurDAG->getRegister(0, MVT::i64);
1597   else {
1598     assert(Index.getValueType() == MVT::i32 &&
1599            "Expect to be extending 32-bit registers for use in LEA");
1600     Index = SDValue(CurDAG->getMachineNode(
1601                         TargetOpcode::SUBREG_TO_REG, DL, MVT::i64,
1602                         CurDAG->getTargetConstant(0, DL, MVT::i64),
1603                         Index,
1604                         CurDAG->getTargetConstant(X86::sub_32bit, DL,
1605                                                   MVT::i32)),
1606                     0);
1607   }
1608 
1609   return true;
1610 }
1611 
1612 /// Calls SelectAddr and determines if the maximal addressing
1613 /// mode it matches can be cost effectively emitted as an LEA instruction.
1614 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
1615                                     SDValue &Base, SDValue &Scale,
1616                                     SDValue &Index, SDValue &Disp,
1617                                     SDValue &Segment) {
1618   X86ISelAddressMode AM;
1619 
1620   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
1621   // segments.
1622   SDValue Copy = AM.Segment;
1623   SDValue T = CurDAG->getRegister(0, MVT::i32);
1624   AM.Segment = T;
1625   if (matchAddress(N, AM))
1626     return false;
1627   assert (T == AM.Segment);
1628   AM.Segment = Copy;
1629 
1630   MVT VT = N.getSimpleValueType();
1631   unsigned Complexity = 0;
1632   if (AM.BaseType == X86ISelAddressMode::RegBase)
1633     if (AM.Base_Reg.getNode())
1634       Complexity = 1;
1635     else
1636       AM.Base_Reg = CurDAG->getRegister(0, VT);
1637   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
1638     Complexity = 4;
1639 
1640   if (AM.IndexReg.getNode())
1641     Complexity++;
1642   else
1643     AM.IndexReg = CurDAG->getRegister(0, VT);
1644 
1645   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
1646   // a simple shift.
1647   if (AM.Scale > 1)
1648     Complexity++;
1649 
1650   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
1651   // to a LEA. This is determined with some experimentation but is by no means
1652   // optimal (especially for code size consideration). LEA is nice because of
1653   // its three-address nature. Tweak the cost function again when we can run
1654   // convertToThreeAddress() at register allocation time.
1655   if (AM.hasSymbolicDisplacement()) {
1656     // For X86-64, always use LEA to materialize RIP-relative addresses.
1657     if (Subtarget->is64Bit())
1658       Complexity = 4;
1659     else
1660       Complexity += 2;
1661   }
1662 
1663   if (AM.Disp && (AM.Base_Reg.getNode() || AM.IndexReg.getNode()))
1664     Complexity++;
1665 
1666   // If it isn't worth using an LEA, reject it.
1667   if (Complexity <= 2)
1668     return false;
1669 
1670   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1671   return true;
1672 }
1673 
1674 /// This is only run on TargetGlobalTLSAddress nodes.
1675 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
1676                                         SDValue &Scale, SDValue &Index,
1677                                         SDValue &Disp, SDValue &Segment) {
1678   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
1679   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1680 
1681   X86ISelAddressMode AM;
1682   AM.GV = GA->getGlobal();
1683   AM.Disp += GA->getOffset();
1684   AM.Base_Reg = CurDAG->getRegister(0, N.getValueType());
1685   AM.SymbolFlags = GA->getTargetFlags();
1686 
1687   if (N.getValueType() == MVT::i32) {
1688     AM.Scale = 1;
1689     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
1690   } else {
1691     AM.IndexReg = CurDAG->getRegister(0, MVT::i64);
1692   }
1693 
1694   getAddressOperands(AM, SDLoc(N), Base, Scale, Index, Disp, Segment);
1695   return true;
1696 }
1697 
1698 
1699 bool X86DAGToDAGISel::tryFoldLoad(SDNode *P, SDValue N,
1700                                   SDValue &Base, SDValue &Scale,
1701                                   SDValue &Index, SDValue &Disp,
1702                                   SDValue &Segment) {
1703   if (!ISD::isNON_EXTLoad(N.getNode()) ||
1704       !IsProfitableToFold(N, P, P) ||
1705       !IsLegalToFold(N, P, P, OptLevel))
1706     return false;
1707 
1708   return selectAddr(N.getNode(),
1709                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
1710 }
1711 
1712 /// Return an SDNode that returns the value of the global base register.
1713 /// Output instructions required to initialize the global base register,
1714 /// if necessary.
1715 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
1716   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
1717   auto &DL = MF->getDataLayout();
1718   return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
1719 }
1720 
1721 /// Test whether the given X86ISD::CMP node has any uses which require the SF
1722 /// or OF bits to be accurate.
1723 static bool hasNoSignedComparisonUses(SDNode *N) {
1724   // Examine each user of the node.
1725   for (SDNode::use_iterator UI = N->use_begin(),
1726          UE = N->use_end(); UI != UE; ++UI) {
1727     // Only examine CopyToReg uses.
1728     if (UI->getOpcode() != ISD::CopyToReg)
1729       return false;
1730     // Only examine CopyToReg uses that copy to EFLAGS.
1731     if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() !=
1732           X86::EFLAGS)
1733       return false;
1734     // Examine each user of the CopyToReg use.
1735     for (SDNode::use_iterator FlagUI = UI->use_begin(),
1736            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
1737       // Only examine the Flag result.
1738       if (FlagUI.getUse().getResNo() != 1) continue;
1739       // Anything unusual: assume conservatively.
1740       if (!FlagUI->isMachineOpcode()) return false;
1741       // Examine the opcode of the user.
1742       switch (FlagUI->getMachineOpcode()) {
1743       // These comparisons don't treat the most significant bit specially.
1744       case X86::SETAr: case X86::SETAEr: case X86::SETBr: case X86::SETBEr:
1745       case X86::SETEr: case X86::SETNEr: case X86::SETPr: case X86::SETNPr:
1746       case X86::SETAm: case X86::SETAEm: case X86::SETBm: case X86::SETBEm:
1747       case X86::SETEm: case X86::SETNEm: case X86::SETPm: case X86::SETNPm:
1748       case X86::JA_1: case X86::JAE_1: case X86::JB_1: case X86::JBE_1:
1749       case X86::JE_1: case X86::JNE_1: case X86::JP_1: case X86::JNP_1:
1750       case X86::CMOVA16rr: case X86::CMOVA16rm:
1751       case X86::CMOVA32rr: case X86::CMOVA32rm:
1752       case X86::CMOVA64rr: case X86::CMOVA64rm:
1753       case X86::CMOVAE16rr: case X86::CMOVAE16rm:
1754       case X86::CMOVAE32rr: case X86::CMOVAE32rm:
1755       case X86::CMOVAE64rr: case X86::CMOVAE64rm:
1756       case X86::CMOVB16rr: case X86::CMOVB16rm:
1757       case X86::CMOVB32rr: case X86::CMOVB32rm:
1758       case X86::CMOVB64rr: case X86::CMOVB64rm:
1759       case X86::CMOVBE16rr: case X86::CMOVBE16rm:
1760       case X86::CMOVBE32rr: case X86::CMOVBE32rm:
1761       case X86::CMOVBE64rr: case X86::CMOVBE64rm:
1762       case X86::CMOVE16rr: case X86::CMOVE16rm:
1763       case X86::CMOVE32rr: case X86::CMOVE32rm:
1764       case X86::CMOVE64rr: case X86::CMOVE64rm:
1765       case X86::CMOVNE16rr: case X86::CMOVNE16rm:
1766       case X86::CMOVNE32rr: case X86::CMOVNE32rm:
1767       case X86::CMOVNE64rr: case X86::CMOVNE64rm:
1768       case X86::CMOVNP16rr: case X86::CMOVNP16rm:
1769       case X86::CMOVNP32rr: case X86::CMOVNP32rm:
1770       case X86::CMOVNP64rr: case X86::CMOVNP64rm:
1771       case X86::CMOVP16rr: case X86::CMOVP16rm:
1772       case X86::CMOVP32rr: case X86::CMOVP32rm:
1773       case X86::CMOVP64rr: case X86::CMOVP64rm:
1774         continue;
1775       // Anything else: assume conservatively.
1776       default: return false;
1777       }
1778     }
1779   }
1780   return true;
1781 }
1782 
1783 /// Check whether or not the chain ending in StoreNode is suitable for doing
1784 /// the {load; increment or decrement; store} to modify transformation.
1785 static bool isLoadIncOrDecStore(StoreSDNode *StoreNode, unsigned Opc,
1786                                 SDValue StoredVal, SelectionDAG *CurDAG,
1787                                 LoadSDNode* &LoadNode, SDValue &InputChain) {
1788 
1789   // is the value stored the result of a DEC or INC?
1790   if (!(Opc == X86ISD::DEC || Opc == X86ISD::INC)) return false;
1791 
1792   // is the stored value result 0 of the load?
1793   if (StoredVal.getResNo() != 0) return false;
1794 
1795   // are there other uses of the loaded value than the inc or dec?
1796   if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
1797 
1798   // is the store non-extending and non-indexed?
1799   if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
1800     return false;
1801 
1802   SDValue Load = StoredVal->getOperand(0);
1803   // Is the stored value a non-extending and non-indexed load?
1804   if (!ISD::isNormalLoad(Load.getNode())) return false;
1805 
1806   // Return LoadNode by reference.
1807   LoadNode = cast<LoadSDNode>(Load);
1808   // is the size of the value one that we can handle? (i.e. 64, 32, 16, or 8)
1809   EVT LdVT = LoadNode->getMemoryVT();
1810   if (LdVT != MVT::i64 && LdVT != MVT::i32 && LdVT != MVT::i16 &&
1811       LdVT != MVT::i8)
1812     return false;
1813 
1814   // Is store the only read of the loaded value?
1815   if (!Load.hasOneUse())
1816     return false;
1817 
1818   // Is the address of the store the same as the load?
1819   if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
1820       LoadNode->getOffset() != StoreNode->getOffset())
1821     return false;
1822 
1823   // Check if the chain is produced by the load or is a TokenFactor with
1824   // the load output chain as an operand. Return InputChain by reference.
1825   SDValue Chain = StoreNode->getChain();
1826 
1827   bool ChainCheck = false;
1828   if (Chain == Load.getValue(1)) {
1829     ChainCheck = true;
1830     InputChain = LoadNode->getChain();
1831   } else if (Chain.getOpcode() == ISD::TokenFactor) {
1832     SmallVector<SDValue, 4> ChainOps;
1833     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
1834       SDValue Op = Chain.getOperand(i);
1835       if (Op == Load.getValue(1)) {
1836         ChainCheck = true;
1837         continue;
1838       }
1839 
1840       // Make sure using Op as part of the chain would not cause a cycle here.
1841       // In theory, we could check whether the chain node is a predecessor of
1842       // the load. But that can be very expensive. Instead visit the uses and
1843       // make sure they all have smaller node id than the load.
1844       int LoadId = LoadNode->getNodeId();
1845       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
1846              UE = UI->use_end(); UI != UE; ++UI) {
1847         if (UI.getUse().getResNo() != 0)
1848           continue;
1849         if (UI->getNodeId() > LoadId)
1850           return false;
1851       }
1852 
1853       ChainOps.push_back(Op);
1854     }
1855 
1856     if (ChainCheck)
1857       // Make a new TokenFactor with all the other input chains except
1858       // for the load.
1859       InputChain = CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain),
1860                                    MVT::Other, ChainOps);
1861   }
1862   if (!ChainCheck)
1863     return false;
1864 
1865   return true;
1866 }
1867 
1868 /// Get the appropriate X86 opcode for an in-memory increment or decrement.
1869 /// Opc should be X86ISD::DEC or X86ISD::INC.
1870 static unsigned getFusedLdStOpcode(EVT &LdVT, unsigned Opc) {
1871   if (Opc == X86ISD::DEC) {
1872     if (LdVT == MVT::i64) return X86::DEC64m;
1873     if (LdVT == MVT::i32) return X86::DEC32m;
1874     if (LdVT == MVT::i16) return X86::DEC16m;
1875     if (LdVT == MVT::i8)  return X86::DEC8m;
1876   } else {
1877     assert(Opc == X86ISD::INC && "unrecognized opcode");
1878     if (LdVT == MVT::i64) return X86::INC64m;
1879     if (LdVT == MVT::i32) return X86::INC32m;
1880     if (LdVT == MVT::i16) return X86::INC16m;
1881     if (LdVT == MVT::i8)  return X86::INC8m;
1882   }
1883   llvm_unreachable("unrecognized size for LdVT");
1884 }
1885 
1886 /// Customized ISel for GATHER operations.
1887 SDNode *X86DAGToDAGISel::selectGather(SDNode *Node, unsigned Opc) {
1888   // Operands of Gather: VSrc, Base, VIdx, VMask, Scale
1889   SDValue Chain = Node->getOperand(0);
1890   SDValue VSrc = Node->getOperand(2);
1891   SDValue Base = Node->getOperand(3);
1892   SDValue VIdx = Node->getOperand(4);
1893   SDValue VMask = Node->getOperand(5);
1894   ConstantSDNode *Scale = dyn_cast<ConstantSDNode>(Node->getOperand(6));
1895   if (!Scale)
1896     return nullptr;
1897 
1898   SDVTList VTs = CurDAG->getVTList(VSrc.getValueType(), VSrc.getValueType(),
1899                                    MVT::Other);
1900 
1901   SDLoc DL(Node);
1902 
1903   // Memory Operands: Base, Scale, Index, Disp, Segment
1904   SDValue Disp = CurDAG->getTargetConstant(0, DL, MVT::i32);
1905   SDValue Segment = CurDAG->getRegister(0, MVT::i32);
1906   const SDValue Ops[] = { VSrc, Base, getI8Imm(Scale->getSExtValue(), DL), VIdx,
1907                           Disp, Segment, VMask, Chain};
1908   SDNode *ResNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
1909   // Node has 2 outputs: VDst and MVT::Other.
1910   // ResNode has 3 outputs: VDst, VMask_wb, and MVT::Other.
1911   // We replace VDst of Node with VDst of ResNode, and Other of Node with Other
1912   // of ResNode.
1913   ReplaceUses(SDValue(Node, 0), SDValue(ResNode, 0));
1914   ReplaceUses(SDValue(Node, 1), SDValue(ResNode, 2));
1915   return ResNode;
1916 }
1917 
1918 SDNode *X86DAGToDAGISel::Select(SDNode *Node) {
1919   MVT NVT = Node->getSimpleValueType(0);
1920   unsigned Opc, MOpc;
1921   unsigned Opcode = Node->getOpcode();
1922   SDLoc dl(Node);
1923 
1924   DEBUG(dbgs() << "Selecting: "; Node->dump(CurDAG); dbgs() << '\n');
1925 
1926   if (Node->isMachineOpcode()) {
1927     DEBUG(dbgs() << "== ";  Node->dump(CurDAG); dbgs() << '\n');
1928     Node->setNodeId(-1);
1929     return nullptr;   // Already selected.
1930   }
1931 
1932   switch (Opcode) {
1933   default: break;
1934   case ISD::BRIND: {
1935     if (Subtarget->isTargetNaCl())
1936       // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
1937       // leave the instruction alone.
1938       break;
1939     if (Subtarget->isTarget64BitILP32()) {
1940       // Converts a 32-bit register to a 64-bit, zero-extended version of
1941       // it. This is needed because x86-64 can do many things, but jmp %r32
1942       // ain't one of them.
1943       const SDValue &Target = Node->getOperand(1);
1944       assert(Target.getSimpleValueType() == llvm::MVT::i32);
1945       SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, EVT(MVT::i64));
1946       SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
1947                                       Node->getOperand(0), ZextTarget);
1948       ReplaceUses(SDValue(Node, 0), Brind);
1949       SelectCode(ZextTarget.getNode());
1950       SelectCode(Brind.getNode());
1951       return nullptr;
1952     }
1953     break;
1954   }
1955   case ISD::INTRINSIC_W_CHAIN: {
1956     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
1957     switch (IntNo) {
1958     default: break;
1959     case Intrinsic::x86_avx2_gather_d_pd:
1960     case Intrinsic::x86_avx2_gather_d_pd_256:
1961     case Intrinsic::x86_avx2_gather_q_pd:
1962     case Intrinsic::x86_avx2_gather_q_pd_256:
1963     case Intrinsic::x86_avx2_gather_d_ps:
1964     case Intrinsic::x86_avx2_gather_d_ps_256:
1965     case Intrinsic::x86_avx2_gather_q_ps:
1966     case Intrinsic::x86_avx2_gather_q_ps_256:
1967     case Intrinsic::x86_avx2_gather_d_q:
1968     case Intrinsic::x86_avx2_gather_d_q_256:
1969     case Intrinsic::x86_avx2_gather_q_q:
1970     case Intrinsic::x86_avx2_gather_q_q_256:
1971     case Intrinsic::x86_avx2_gather_d_d:
1972     case Intrinsic::x86_avx2_gather_d_d_256:
1973     case Intrinsic::x86_avx2_gather_q_d:
1974     case Intrinsic::x86_avx2_gather_q_d_256: {
1975       if (!Subtarget->hasAVX2())
1976         break;
1977       unsigned Opc;
1978       switch (IntNo) {
1979       default: llvm_unreachable("Impossible intrinsic");
1980       case Intrinsic::x86_avx2_gather_d_pd:     Opc = X86::VGATHERDPDrm;  break;
1981       case Intrinsic::x86_avx2_gather_d_pd_256: Opc = X86::VGATHERDPDYrm; break;
1982       case Intrinsic::x86_avx2_gather_q_pd:     Opc = X86::VGATHERQPDrm;  break;
1983       case Intrinsic::x86_avx2_gather_q_pd_256: Opc = X86::VGATHERQPDYrm; break;
1984       case Intrinsic::x86_avx2_gather_d_ps:     Opc = X86::VGATHERDPSrm;  break;
1985       case Intrinsic::x86_avx2_gather_d_ps_256: Opc = X86::VGATHERDPSYrm; break;
1986       case Intrinsic::x86_avx2_gather_q_ps:     Opc = X86::VGATHERQPSrm;  break;
1987       case Intrinsic::x86_avx2_gather_q_ps_256: Opc = X86::VGATHERQPSYrm; break;
1988       case Intrinsic::x86_avx2_gather_d_q:      Opc = X86::VPGATHERDQrm;  break;
1989       case Intrinsic::x86_avx2_gather_d_q_256:  Opc = X86::VPGATHERDQYrm; break;
1990       case Intrinsic::x86_avx2_gather_q_q:      Opc = X86::VPGATHERQQrm;  break;
1991       case Intrinsic::x86_avx2_gather_q_q_256:  Opc = X86::VPGATHERQQYrm; break;
1992       case Intrinsic::x86_avx2_gather_d_d:      Opc = X86::VPGATHERDDrm;  break;
1993       case Intrinsic::x86_avx2_gather_d_d_256:  Opc = X86::VPGATHERDDYrm; break;
1994       case Intrinsic::x86_avx2_gather_q_d:      Opc = X86::VPGATHERQDrm;  break;
1995       case Intrinsic::x86_avx2_gather_q_d_256:  Opc = X86::VPGATHERQDYrm; break;
1996       }
1997       SDNode *RetVal = selectGather(Node, Opc);
1998       if (RetVal)
1999         // We already called ReplaceUses inside SelectGather.
2000         return nullptr;
2001       break;
2002     }
2003     }
2004     break;
2005   }
2006   case X86ISD::GlobalBaseReg:
2007     return getGlobalBaseReg();
2008 
2009   case X86ISD::SHRUNKBLEND: {
2010     // SHRUNKBLEND selects like a regular VSELECT.
2011     SDValue VSelect = CurDAG->getNode(
2012         ISD::VSELECT, SDLoc(Node), Node->getValueType(0), Node->getOperand(0),
2013         Node->getOperand(1), Node->getOperand(2));
2014     ReplaceUses(SDValue(Node, 0), VSelect);
2015     SelectCode(VSelect.getNode());
2016     // We already called ReplaceUses.
2017     return nullptr;
2018   }
2019 
2020   case ISD::AND:
2021   case ISD::OR:
2022   case ISD::XOR: {
2023     // For operations of the form (x << C1) op C2, check if we can use a smaller
2024     // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
2025     SDValue N0 = Node->getOperand(0);
2026     SDValue N1 = Node->getOperand(1);
2027 
2028     if (N0->getOpcode() != ISD::SHL || !N0->hasOneUse())
2029       break;
2030 
2031     // i8 is unshrinkable, i16 should be promoted to i32.
2032     if (NVT != MVT::i32 && NVT != MVT::i64)
2033       break;
2034 
2035     ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
2036     ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
2037     if (!Cst || !ShlCst)
2038       break;
2039 
2040     int64_t Val = Cst->getSExtValue();
2041     uint64_t ShlVal = ShlCst->getZExtValue();
2042 
2043     // Make sure that we don't change the operation by removing bits.
2044     // This only matters for OR and XOR, AND is unaffected.
2045     uint64_t RemovedBitsMask = (1ULL << ShlVal) - 1;
2046     if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
2047       break;
2048 
2049     unsigned ShlOp, AddOp, Op;
2050     MVT CstVT = NVT;
2051 
2052     // Check the minimum bitwidth for the new constant.
2053     // TODO: AND32ri is the same as AND64ri32 with zext imm.
2054     // TODO: MOV32ri+OR64r is cheaper than MOV64ri64+OR64rr
2055     // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
2056     if (!isInt<8>(Val) && isInt<8>(Val >> ShlVal))
2057       CstVT = MVT::i8;
2058     else if (!isInt<32>(Val) && isInt<32>(Val >> ShlVal))
2059       CstVT = MVT::i32;
2060 
2061     // Bail if there is no smaller encoding.
2062     if (NVT == CstVT)
2063       break;
2064 
2065     switch (NVT.SimpleTy) {
2066     default: llvm_unreachable("Unsupported VT!");
2067     case MVT::i32:
2068       assert(CstVT == MVT::i8);
2069       ShlOp = X86::SHL32ri;
2070       AddOp = X86::ADD32rr;
2071 
2072       switch (Opcode) {
2073       default: llvm_unreachable("Impossible opcode");
2074       case ISD::AND: Op = X86::AND32ri8; break;
2075       case ISD::OR:  Op =  X86::OR32ri8; break;
2076       case ISD::XOR: Op = X86::XOR32ri8; break;
2077       }
2078       break;
2079     case MVT::i64:
2080       assert(CstVT == MVT::i8 || CstVT == MVT::i32);
2081       ShlOp = X86::SHL64ri;
2082       AddOp = X86::ADD64rr;
2083 
2084       switch (Opcode) {
2085       default: llvm_unreachable("Impossible opcode");
2086       case ISD::AND: Op = CstVT==MVT::i8? X86::AND64ri8 : X86::AND64ri32; break;
2087       case ISD::OR:  Op = CstVT==MVT::i8?  X86::OR64ri8 :  X86::OR64ri32; break;
2088       case ISD::XOR: Op = CstVT==MVT::i8? X86::XOR64ri8 : X86::XOR64ri32; break;
2089       }
2090       break;
2091     }
2092 
2093     // Emit the smaller op and the shift.
2094     SDValue NewCst = CurDAG->getTargetConstant(Val >> ShlVal, dl, CstVT);
2095     SDNode *New = CurDAG->getMachineNode(Op, dl, NVT, N0->getOperand(0),NewCst);
2096     if (ShlVal == 1)
2097       return CurDAG->SelectNodeTo(Node, AddOp, NVT, SDValue(New, 0),
2098                                   SDValue(New, 0));
2099     return CurDAG->SelectNodeTo(Node, ShlOp, NVT, SDValue(New, 0),
2100                                 getI8Imm(ShlVal, dl));
2101   }
2102   case X86ISD::UMUL8:
2103   case X86ISD::SMUL8: {
2104     SDValue N0 = Node->getOperand(0);
2105     SDValue N1 = Node->getOperand(1);
2106 
2107     Opc = (Opcode == X86ISD::SMUL8 ? X86::IMUL8r : X86::MUL8r);
2108 
2109     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::AL,
2110                                           N0, SDValue()).getValue(1);
2111 
2112     SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32);
2113     SDValue Ops[] = {N1, InFlag};
2114     SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2115 
2116     ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2117     ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2118     return nullptr;
2119   }
2120 
2121   case X86ISD::UMUL: {
2122     SDValue N0 = Node->getOperand(0);
2123     SDValue N1 = Node->getOperand(1);
2124 
2125     unsigned LoReg;
2126     switch (NVT.SimpleTy) {
2127     default: llvm_unreachable("Unsupported VT!");
2128     case MVT::i8:  LoReg = X86::AL;  Opc = X86::MUL8r; break;
2129     case MVT::i16: LoReg = X86::AX;  Opc = X86::MUL16r; break;
2130     case MVT::i32: LoReg = X86::EAX; Opc = X86::MUL32r; break;
2131     case MVT::i64: LoReg = X86::RAX; Opc = X86::MUL64r; break;
2132     }
2133 
2134     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
2135                                           N0, SDValue()).getValue(1);
2136 
2137     SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
2138     SDValue Ops[] = {N1, InFlag};
2139     SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2140 
2141     ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
2142     ReplaceUses(SDValue(Node, 1), SDValue(CNode, 1));
2143     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 2));
2144     return nullptr;
2145   }
2146 
2147   case ISD::SMUL_LOHI:
2148   case ISD::UMUL_LOHI: {
2149     SDValue N0 = Node->getOperand(0);
2150     SDValue N1 = Node->getOperand(1);
2151 
2152     bool isSigned = Opcode == ISD::SMUL_LOHI;
2153     bool hasBMI2 = Subtarget->hasBMI2();
2154     if (!isSigned) {
2155       switch (NVT.SimpleTy) {
2156       default: llvm_unreachable("Unsupported VT!");
2157       case MVT::i8:  Opc = X86::MUL8r;  MOpc = X86::MUL8m;  break;
2158       case MVT::i16: Opc = X86::MUL16r; MOpc = X86::MUL16m; break;
2159       case MVT::i32: Opc = hasBMI2 ? X86::MULX32rr : X86::MUL32r;
2160                      MOpc = hasBMI2 ? X86::MULX32rm : X86::MUL32m; break;
2161       case MVT::i64: Opc = hasBMI2 ? X86::MULX64rr : X86::MUL64r;
2162                      MOpc = hasBMI2 ? X86::MULX64rm : X86::MUL64m; break;
2163       }
2164     } else {
2165       switch (NVT.SimpleTy) {
2166       default: llvm_unreachable("Unsupported VT!");
2167       case MVT::i8:  Opc = X86::IMUL8r;  MOpc = X86::IMUL8m;  break;
2168       case MVT::i16: Opc = X86::IMUL16r; MOpc = X86::IMUL16m; break;
2169       case MVT::i32: Opc = X86::IMUL32r; MOpc = X86::IMUL32m; break;
2170       case MVT::i64: Opc = X86::IMUL64r; MOpc = X86::IMUL64m; break;
2171       }
2172     }
2173 
2174     unsigned SrcReg, LoReg, HiReg;
2175     switch (Opc) {
2176     default: llvm_unreachable("Unknown MUL opcode!");
2177     case X86::IMUL8r:
2178     case X86::MUL8r:
2179       SrcReg = LoReg = X86::AL; HiReg = X86::AH;
2180       break;
2181     case X86::IMUL16r:
2182     case X86::MUL16r:
2183       SrcReg = LoReg = X86::AX; HiReg = X86::DX;
2184       break;
2185     case X86::IMUL32r:
2186     case X86::MUL32r:
2187       SrcReg = LoReg = X86::EAX; HiReg = X86::EDX;
2188       break;
2189     case X86::IMUL64r:
2190     case X86::MUL64r:
2191       SrcReg = LoReg = X86::RAX; HiReg = X86::RDX;
2192       break;
2193     case X86::MULX32rr:
2194       SrcReg = X86::EDX; LoReg = HiReg = 0;
2195       break;
2196     case X86::MULX64rr:
2197       SrcReg = X86::RDX; LoReg = HiReg = 0;
2198       break;
2199     }
2200 
2201     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2202     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2203     // Multiply is commmutative.
2204     if (!foldedLoad) {
2205       foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2206       if (foldedLoad)
2207         std::swap(N0, N1);
2208     }
2209 
2210     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, SrcReg,
2211                                           N0, SDValue()).getValue(1);
2212     SDValue ResHi, ResLo;
2213 
2214     if (foldedLoad) {
2215       SDValue Chain;
2216       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2217                         InFlag };
2218       if (MOpc == X86::MULX32rm || MOpc == X86::MULX64rm) {
2219         SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other, MVT::Glue);
2220         SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2221         ResHi = SDValue(CNode, 0);
2222         ResLo = SDValue(CNode, 1);
2223         Chain = SDValue(CNode, 2);
2224         InFlag = SDValue(CNode, 3);
2225       } else {
2226         SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
2227         SDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
2228         Chain = SDValue(CNode, 0);
2229         InFlag = SDValue(CNode, 1);
2230       }
2231 
2232       // Update the chain.
2233       ReplaceUses(N1.getValue(1), Chain);
2234     } else {
2235       SDValue Ops[] = { N1, InFlag };
2236       if (Opc == X86::MULX32rr || Opc == X86::MULX64rr) {
2237         SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Glue);
2238         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2239         ResHi = SDValue(CNode, 0);
2240         ResLo = SDValue(CNode, 1);
2241         InFlag = SDValue(CNode, 2);
2242       } else {
2243         SDVTList VTs = CurDAG->getVTList(MVT::Glue);
2244         SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
2245         InFlag = SDValue(CNode, 0);
2246       }
2247     }
2248 
2249     // Prevent use of AH in a REX instruction by referencing AX instead.
2250     if (HiReg == X86::AH && Subtarget->is64Bit() &&
2251         !SDValue(Node, 1).use_empty()) {
2252       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2253                                               X86::AX, MVT::i16, InFlag);
2254       InFlag = Result.getValue(2);
2255       // Get the low part if needed. Don't use getCopyFromReg for aliasing
2256       // registers.
2257       if (!SDValue(Node, 0).use_empty())
2258         ReplaceUses(SDValue(Node, 1),
2259           CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2260 
2261       // Shift AX down 8 bits.
2262       Result = SDValue(CurDAG->getMachineNode(X86::SHR16ri, dl, MVT::i16,
2263                                               Result,
2264                                      CurDAG->getTargetConstant(8, dl, MVT::i8)),
2265                        0);
2266       // Then truncate it down to i8.
2267       ReplaceUses(SDValue(Node, 1),
2268         CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result));
2269     }
2270     // Copy the low half of the result, if it is needed.
2271     if (!SDValue(Node, 0).use_empty()) {
2272       if (!ResLo.getNode()) {
2273         assert(LoReg && "Register for low half is not defined!");
2274         ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, NVT,
2275                                        InFlag);
2276         InFlag = ResLo.getValue(2);
2277       }
2278       ReplaceUses(SDValue(Node, 0), ResLo);
2279       DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); dbgs() << '\n');
2280     }
2281     // Copy the high half of the result, if it is needed.
2282     if (!SDValue(Node, 1).use_empty()) {
2283       if (!ResHi.getNode()) {
2284         assert(HiReg && "Register for high half is not defined!");
2285         ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, NVT,
2286                                        InFlag);
2287         InFlag = ResHi.getValue(2);
2288       }
2289       ReplaceUses(SDValue(Node, 1), ResHi);
2290       DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); dbgs() << '\n');
2291     }
2292 
2293     return nullptr;
2294   }
2295 
2296   case ISD::SDIVREM:
2297   case ISD::UDIVREM:
2298   case X86ISD::SDIVREM8_SEXT_HREG:
2299   case X86ISD::UDIVREM8_ZEXT_HREG: {
2300     SDValue N0 = Node->getOperand(0);
2301     SDValue N1 = Node->getOperand(1);
2302 
2303     bool isSigned = (Opcode == ISD::SDIVREM ||
2304                      Opcode == X86ISD::SDIVREM8_SEXT_HREG);
2305     if (!isSigned) {
2306       switch (NVT.SimpleTy) {
2307       default: llvm_unreachable("Unsupported VT!");
2308       case MVT::i8:  Opc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
2309       case MVT::i16: Opc = X86::DIV16r; MOpc = X86::DIV16m; break;
2310       case MVT::i32: Opc = X86::DIV32r; MOpc = X86::DIV32m; break;
2311       case MVT::i64: Opc = X86::DIV64r; MOpc = X86::DIV64m; break;
2312       }
2313     } else {
2314       switch (NVT.SimpleTy) {
2315       default: llvm_unreachable("Unsupported VT!");
2316       case MVT::i8:  Opc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
2317       case MVT::i16: Opc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
2318       case MVT::i32: Opc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
2319       case MVT::i64: Opc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
2320       }
2321     }
2322 
2323     unsigned LoReg, HiReg, ClrReg;
2324     unsigned SExtOpcode;
2325     switch (NVT.SimpleTy) {
2326     default: llvm_unreachable("Unsupported VT!");
2327     case MVT::i8:
2328       LoReg = X86::AL;  ClrReg = HiReg = X86::AH;
2329       SExtOpcode = X86::CBW;
2330       break;
2331     case MVT::i16:
2332       LoReg = X86::AX;  HiReg = X86::DX;
2333       ClrReg = X86::DX;
2334       SExtOpcode = X86::CWD;
2335       break;
2336     case MVT::i32:
2337       LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
2338       SExtOpcode = X86::CDQ;
2339       break;
2340     case MVT::i64:
2341       LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
2342       SExtOpcode = X86::CQO;
2343       break;
2344     }
2345 
2346     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
2347     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
2348     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
2349 
2350     SDValue InFlag;
2351     if (NVT == MVT::i8 && (!isSigned || signBitIsZero)) {
2352       // Special case for div8, just use a move with zero extension to AX to
2353       // clear the upper 8 bits (AH).
2354       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Move, Chain;
2355       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
2356         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
2357         Move =
2358           SDValue(CurDAG->getMachineNode(X86::MOVZX32rm8, dl, MVT::i32,
2359                                          MVT::Other, Ops), 0);
2360         Chain = Move.getValue(1);
2361         ReplaceUses(N0.getValue(1), Chain);
2362       } else {
2363         Move =
2364           SDValue(CurDAG->getMachineNode(X86::MOVZX32rr8, dl, MVT::i32, N0),0);
2365         Chain = CurDAG->getEntryNode();
2366       }
2367       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::EAX, Move, SDValue());
2368       InFlag = Chain.getValue(1);
2369     } else {
2370       InFlag =
2371         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
2372                              LoReg, N0, SDValue()).getValue(1);
2373       if (isSigned && !signBitIsZero) {
2374         // Sign extend the low part into the high part.
2375         InFlag =
2376           SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
2377       } else {
2378         // Zero out the high part, effectively zero extending the input.
2379         SDValue ClrNode = SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, NVT), 0);
2380         switch (NVT.SimpleTy) {
2381         case MVT::i16:
2382           ClrNode =
2383               SDValue(CurDAG->getMachineNode(
2384                           TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
2385                           CurDAG->getTargetConstant(X86::sub_16bit, dl,
2386                                                     MVT::i32)),
2387                       0);
2388           break;
2389         case MVT::i32:
2390           break;
2391         case MVT::i64:
2392           ClrNode =
2393               SDValue(CurDAG->getMachineNode(
2394                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2395                           CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
2396                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
2397                                                     MVT::i32)),
2398                       0);
2399           break;
2400         default:
2401           llvm_unreachable("Unexpected division source");
2402         }
2403 
2404         InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
2405                                       ClrNode, InFlag).getValue(1);
2406       }
2407     }
2408 
2409     if (foldedLoad) {
2410       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
2411                         InFlag };
2412       SDNode *CNode =
2413         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
2414       InFlag = SDValue(CNode, 1);
2415       // Update the chain.
2416       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
2417     } else {
2418       InFlag =
2419         SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N1, InFlag), 0);
2420     }
2421 
2422     // Prevent use of AH in a REX instruction by explicitly copying it to
2423     // an ABCD_L register.
2424     //
2425     // The current assumption of the register allocator is that isel
2426     // won't generate explicit references to the GR8_ABCD_H registers. If
2427     // the allocator and/or the backend get enhanced to be more robust in
2428     // that regard, this can be, and should be, removed.
2429     if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
2430       SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
2431       unsigned AHExtOpcode =
2432           isSigned ? X86::MOVSX32_NOREXrr8 : X86::MOVZX32_NOREXrr8;
2433 
2434       SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
2435                                              MVT::Glue, AHCopy, InFlag);
2436       SDValue Result(RNode, 0);
2437       InFlag = SDValue(RNode, 1);
2438 
2439       if (Opcode == X86ISD::UDIVREM8_ZEXT_HREG ||
2440           Opcode == X86ISD::SDIVREM8_SEXT_HREG) {
2441         if (Node->getValueType(1) == MVT::i64) {
2442           // It's not possible to directly movsx AH to a 64bit register, because
2443           // the latter needs the REX prefix, but the former can't have it.
2444           assert(Opcode != X86ISD::SDIVREM8_SEXT_HREG &&
2445                  "Unexpected i64 sext of h-register");
2446           Result =
2447               SDValue(CurDAG->getMachineNode(
2448                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
2449                           CurDAG->getTargetConstant(0, dl, MVT::i64), Result,
2450                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
2451                                                     MVT::i32)),
2452                       0);
2453         }
2454       } else {
2455         Result =
2456             CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
2457       }
2458       ReplaceUses(SDValue(Node, 1), Result);
2459       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2460     }
2461     // Copy the division (low) result, if it is needed.
2462     if (!SDValue(Node, 0).use_empty()) {
2463       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2464                                                 LoReg, NVT, InFlag);
2465       InFlag = Result.getValue(2);
2466       ReplaceUses(SDValue(Node, 0), Result);
2467       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2468     }
2469     // Copy the remainder (high) result, if it is needed.
2470     if (!SDValue(Node, 1).use_empty()) {
2471       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
2472                                               HiReg, NVT, InFlag);
2473       InFlag = Result.getValue(2);
2474       ReplaceUses(SDValue(Node, 1), Result);
2475       DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); dbgs() << '\n');
2476     }
2477     return nullptr;
2478   }
2479 
2480   case X86ISD::CMP:
2481   case X86ISD::SUB: {
2482     // Sometimes a SUB is used to perform comparison.
2483     if (Opcode == X86ISD::SUB && Node->hasAnyUseOfValue(0))
2484       // This node is not a CMP.
2485       break;
2486     SDValue N0 = Node->getOperand(0);
2487     SDValue N1 = Node->getOperand(1);
2488 
2489     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
2490         hasNoSignedComparisonUses(Node))
2491       N0 = N0.getOperand(0);
2492 
2493     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
2494     // use a smaller encoding.
2495     // Look past the truncate if CMP is the only use of it.
2496     if ((N0.getNode()->getOpcode() == ISD::AND ||
2497          (N0.getResNo() == 0 && N0.getNode()->getOpcode() == X86ISD::AND)) &&
2498         N0.getNode()->hasOneUse() &&
2499         N0.getValueType() != MVT::i8 &&
2500         X86::isZeroNode(N1)) {
2501       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getNode()->getOperand(1));
2502       if (!C) break;
2503 
2504       // For example, convert "testl %eax, $8" to "testb %al, $8"
2505       if ((C->getZExtValue() & ~UINT64_C(0xff)) == 0 &&
2506           (!(C->getZExtValue() & 0x80) ||
2507            hasNoSignedComparisonUses(Node))) {
2508         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl, MVT::i8);
2509         SDValue Reg = N0.getNode()->getOperand(0);
2510 
2511         // On x86-32, only the ABCD registers have 8-bit subregisters.
2512         if (!Subtarget->is64Bit()) {
2513           const TargetRegisterClass *TRC;
2514           switch (N0.getSimpleValueType().SimpleTy) {
2515           case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2516           case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2517           default: llvm_unreachable("Unsupported TEST operand type!");
2518           }
2519           SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2520           Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2521                                                Reg.getValueType(), Reg, RC), 0);
2522         }
2523 
2524         // Extract the l-register.
2525         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl,
2526                                                         MVT::i8, Reg);
2527 
2528         // Emit a testb.
2529         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri, dl, MVT::i32,
2530                                                  Subreg, Imm);
2531         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2532         // one, do not call ReplaceAllUsesWith.
2533         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2534                     SDValue(NewNode, 0));
2535         return nullptr;
2536       }
2537 
2538       // For example, "testl %eax, $2048" to "testb %ah, $8".
2539       if ((C->getZExtValue() & ~UINT64_C(0xff00)) == 0 &&
2540           (!(C->getZExtValue() & 0x8000) ||
2541            hasNoSignedComparisonUses(Node))) {
2542         // Shift the immediate right by 8 bits.
2543         SDValue ShiftedImm = CurDAG->getTargetConstant(C->getZExtValue() >> 8,
2544                                                        dl, MVT::i8);
2545         SDValue Reg = N0.getNode()->getOperand(0);
2546 
2547         // Put the value in an ABCD register.
2548         const TargetRegisterClass *TRC;
2549         switch (N0.getSimpleValueType().SimpleTy) {
2550         case MVT::i64: TRC = &X86::GR64_ABCDRegClass; break;
2551         case MVT::i32: TRC = &X86::GR32_ABCDRegClass; break;
2552         case MVT::i16: TRC = &X86::GR16_ABCDRegClass; break;
2553         default: llvm_unreachable("Unsupported TEST operand type!");
2554         }
2555         SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
2556         Reg = SDValue(CurDAG->getMachineNode(X86::COPY_TO_REGCLASS, dl,
2557                                              Reg.getValueType(), Reg, RC), 0);
2558 
2559         // Extract the h-register.
2560         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl,
2561                                                         MVT::i8, Reg);
2562 
2563         // Emit a testb.  The EXTRACT_SUBREG becomes a COPY that can only
2564         // target GR8_NOREX registers, so make sure the register class is
2565         // forced.
2566         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST8ri_NOREX, dl,
2567                                                  MVT::i32, Subreg, ShiftedImm);
2568         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2569         // one, do not call ReplaceAllUsesWith.
2570         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2571                     SDValue(NewNode, 0));
2572         return nullptr;
2573       }
2574 
2575       // For example, "testl %eax, $32776" to "testw %ax, $32776".
2576       if ((C->getZExtValue() & ~UINT64_C(0xffff)) == 0 &&
2577           N0.getValueType() != MVT::i16 &&
2578           (!(C->getZExtValue() & 0x8000) ||
2579            hasNoSignedComparisonUses(Node))) {
2580         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2581                                                 MVT::i16);
2582         SDValue Reg = N0.getNode()->getOperand(0);
2583 
2584         // Extract the 16-bit subregister.
2585         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_16bit, dl,
2586                                                         MVT::i16, Reg);
2587 
2588         // Emit a testw.
2589         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST16ri, dl, MVT::i32,
2590                                                  Subreg, Imm);
2591         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2592         // one, do not call ReplaceAllUsesWith.
2593         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2594                     SDValue(NewNode, 0));
2595         return nullptr;
2596       }
2597 
2598       // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
2599       if ((C->getZExtValue() & ~UINT64_C(0xffffffff)) == 0 &&
2600           N0.getValueType() == MVT::i64 &&
2601           (!(C->getZExtValue() & 0x80000000) ||
2602            hasNoSignedComparisonUses(Node))) {
2603         SDValue Imm = CurDAG->getTargetConstant(C->getZExtValue(), dl,
2604                                                 MVT::i32);
2605         SDValue Reg = N0.getNode()->getOperand(0);
2606 
2607         // Extract the 32-bit subregister.
2608         SDValue Subreg = CurDAG->getTargetExtractSubreg(X86::sub_32bit, dl,
2609                                                         MVT::i32, Reg);
2610 
2611         // Emit a testl.
2612         SDNode *NewNode = CurDAG->getMachineNode(X86::TEST32ri, dl, MVT::i32,
2613                                                  Subreg, Imm);
2614         // Replace SUB|CMP with TEST, since SUB has two outputs while TEST has
2615         // one, do not call ReplaceAllUsesWith.
2616         ReplaceUses(SDValue(Node, (Opcode == X86ISD::SUB ? 1 : 0)),
2617                     SDValue(NewNode, 0));
2618         return nullptr;
2619       }
2620     }
2621     break;
2622   }
2623   case ISD::STORE: {
2624     // Change a chain of {load; incr or dec; store} of the same value into
2625     // a simple increment or decrement through memory of that value, if the
2626     // uses of the modified value and its address are suitable.
2627     // The DEC64m tablegen pattern is currently not able to match the case where
2628     // the EFLAGS on the original DEC are used. (This also applies to
2629     // {INC,DEC}X{64,32,16,8}.)
2630     // We'll need to improve tablegen to allow flags to be transferred from a
2631     // node in the pattern to the result node.  probably with a new keyword
2632     // for example, we have this
2633     // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2634     //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2635     //   (implicit EFLAGS)]>;
2636     // but maybe need something like this
2637     // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
2638     //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
2639     //   (transferrable EFLAGS)]>;
2640 
2641     StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
2642     SDValue StoredVal = StoreNode->getOperand(1);
2643     unsigned Opc = StoredVal->getOpcode();
2644 
2645     LoadSDNode *LoadNode = nullptr;
2646     SDValue InputChain;
2647     if (!isLoadIncOrDecStore(StoreNode, Opc, StoredVal, CurDAG,
2648                              LoadNode, InputChain))
2649       break;
2650 
2651     SDValue Base, Scale, Index, Disp, Segment;
2652     if (!selectAddr(LoadNode, LoadNode->getBasePtr(),
2653                     Base, Scale, Index, Disp, Segment))
2654       break;
2655 
2656     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(2);
2657     MemOp[0] = StoreNode->getMemOperand();
2658     MemOp[1] = LoadNode->getMemOperand();
2659     const SDValue Ops[] = { Base, Scale, Index, Disp, Segment, InputChain };
2660     EVT LdVT = LoadNode->getMemoryVT();
2661     unsigned newOpc = getFusedLdStOpcode(LdVT, Opc);
2662     MachineSDNode *Result = CurDAG->getMachineNode(newOpc,
2663                                                    SDLoc(Node),
2664                                                    MVT::i32, MVT::Other, Ops);
2665     Result->setMemRefs(MemOp, MemOp + 2);
2666 
2667     ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
2668     ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
2669 
2670     return Result;
2671   }
2672   }
2673 
2674   SDNode *ResNode = SelectCode(Node);
2675 
2676   DEBUG(dbgs() << "=> ";
2677         if (ResNode == nullptr || ResNode == Node)
2678           Node->dump(CurDAG);
2679         else
2680           ResNode->dump(CurDAG);
2681         dbgs() << '\n');
2682 
2683   return ResNode;
2684 }
2685 
2686 bool X86DAGToDAGISel::
2687 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
2688                              std::vector<SDValue> &OutOps) {
2689   SDValue Op0, Op1, Op2, Op3, Op4;
2690   switch (ConstraintID) {
2691   default:
2692     llvm_unreachable("Unexpected asm memory constraint");
2693   case InlineAsm::Constraint_i:
2694     // FIXME: It seems strange that 'i' is needed here since it's supposed to
2695     //        be an immediate and not a memory constraint.
2696     // Fallthrough.
2697   case InlineAsm::Constraint_o: // offsetable        ??
2698   case InlineAsm::Constraint_v: // not offsetable    ??
2699   case InlineAsm::Constraint_m: // memory
2700   case InlineAsm::Constraint_X:
2701     if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
2702       return true;
2703     break;
2704   }
2705 
2706   OutOps.push_back(Op0);
2707   OutOps.push_back(Op1);
2708   OutOps.push_back(Op2);
2709   OutOps.push_back(Op3);
2710   OutOps.push_back(Op4);
2711   return false;
2712 }
2713 
2714 /// This pass converts a legalized DAG into a X86-specific DAG,
2715 /// ready for instruction scheduling.
2716 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
2717                                      CodeGenOpt::Level OptLevel) {
2718   return new X86DAGToDAGISel(TM, OptLevel);
2719 }
2720