1 //===- X86ISelDAGToDAG.cpp - A DAG pattern matching inst selector for X86 -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a DAG pattern matching instruction selector for X86,
10 // converting from a legalized dag to a X86 dag.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86.h"
15 #include "X86MachineFunctionInfo.h"
16 #include "X86RegisterInfo.h"
17 #include "X86Subtarget.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/SelectionDAGISel.h"
21 #include "llvm/Config/llvm-config.h"
22 #include "llvm/IR/ConstantRange.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/IntrinsicsX86.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <stdint.h>
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "x86-isel"
36 
37 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
38 
39 static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),
40     cl::desc("Enable setting constant bits to reduce size of mask immediates"),
41     cl::Hidden);
42 
43 //===----------------------------------------------------------------------===//
44 //                      Pattern Matcher Implementation
45 //===----------------------------------------------------------------------===//
46 
47 namespace {
48   /// This corresponds to X86AddressMode, but uses SDValue's instead of register
49   /// numbers for the leaves of the matched tree.
50   struct X86ISelAddressMode {
51     enum {
52       RegBase,
53       FrameIndexBase
54     } BaseType;
55 
56     // This is really a union, discriminated by BaseType!
57     SDValue Base_Reg;
58     int Base_FrameIndex;
59 
60     unsigned Scale;
61     SDValue IndexReg;
62     int32_t Disp;
63     SDValue Segment;
64     const GlobalValue *GV;
65     const Constant *CP;
66     const BlockAddress *BlockAddr;
67     const char *ES;
68     MCSymbol *MCSym;
69     int JT;
70     unsigned Align;    // CP alignment.
71     unsigned char SymbolFlags;  // X86II::MO_*
72     bool NegateIndex = false;
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(SelectionDAG *DAG = nullptr) {
105       dbgs() << "X86ISelAddressMode " << this << '\n';
106       dbgs() << "Base_Reg ";
107       if (Base_Reg.getNode())
108         Base_Reg.getNode()->dump(DAG);
109       else
110         dbgs() << "nul\n";
111       if (BaseType == FrameIndexBase)
112         dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
113       dbgs() << " Scale " << Scale << '\n'
114              << "IndexReg ";
115       if (NegateIndex)
116         dbgs() << "negate ";
117       if (IndexReg.getNode())
118         IndexReg.getNode()->dump(DAG);
119       else
120         dbgs() << "nul\n";
121       dbgs() << " Disp " << Disp << '\n'
122              << "GV ";
123       if (GV)
124         GV->dump();
125       else
126         dbgs() << "nul";
127       dbgs() << " CP ";
128       if (CP)
129         CP->dump();
130       else
131         dbgs() << "nul";
132       dbgs() << '\n'
133              << "ES ";
134       if (ES)
135         dbgs() << ES;
136       else
137         dbgs() << "nul";
138       dbgs() << " MCSym ";
139       if (MCSym)
140         dbgs() << MCSym;
141       else
142         dbgs() << "nul";
143       dbgs() << " JT" << JT << " Align" << Align << '\n';
144     }
145 #endif
146   };
147 }
148 
149 namespace {
150   //===--------------------------------------------------------------------===//
151   /// ISel - X86-specific code to select X86 machine instructions for
152   /// SelectionDAG operations.
153   ///
154   class X86DAGToDAGISel final : public SelectionDAGISel {
155     /// Keep a pointer to the X86Subtarget around so that we can
156     /// make the right decision when generating code for different targets.
157     const X86Subtarget *Subtarget;
158 
159     /// If true, selector should try to optimize for code size instead of
160     /// performance.
161     bool OptForSize;
162 
163     /// If true, selector should try to optimize for minimum code size.
164     bool OptForMinSize;
165 
166     /// Disable direct TLS access through segment registers.
167     bool IndirectTlsSegRefs;
168 
169   public:
170     explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
171         : SelectionDAGISel(tm, OptLevel), Subtarget(nullptr), OptForSize(false),
172           OptForMinSize(false), IndirectTlsSegRefs(false) {}
173 
174     StringRef getPassName() const override {
175       return "X86 DAG->DAG Instruction Selection";
176     }
177 
178     bool runOnMachineFunction(MachineFunction &MF) override {
179       // Reset the subtarget each time through.
180       Subtarget = &MF.getSubtarget<X86Subtarget>();
181       IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(
182                              "indirect-tls-seg-refs");
183 
184       // OptFor[Min]Size are used in pattern predicates that isel is matching.
185       OptForSize = MF.getFunction().hasOptSize();
186       OptForMinSize = MF.getFunction().hasMinSize();
187       assert((!OptForMinSize || OptForSize) &&
188              "OptForMinSize implies OptForSize");
189 
190       SelectionDAGISel::runOnMachineFunction(MF);
191       return true;
192     }
193 
194     void emitFunctionEntryCode() override;
195 
196     bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
197 
198     void PreprocessISelDAG() override;
199     void PostprocessISelDAG() override;
200 
201 // Include the pieces autogenerated from the target description.
202 #include "X86GenDAGISel.inc"
203 
204   private:
205     void Select(SDNode *N) override;
206 
207     bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
208     bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM);
209     bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
210     bool matchAddress(SDValue N, X86ISelAddressMode &AM);
211     bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
212     bool matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth);
213     bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
214                                  unsigned Depth);
215     bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
216     bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
217                     SDValue &Scale, SDValue &Index, SDValue &Disp,
218                     SDValue &Segment);
219     bool selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, SDValue IndexOp,
220                           SDValue ScaleOp, SDValue &Base, SDValue &Scale,
221                           SDValue &Index, SDValue &Disp, SDValue &Segment);
222     bool selectMOV64Imm32(SDValue N, SDValue &Imm);
223     bool selectLEAAddr(SDValue N, SDValue &Base,
224                        SDValue &Scale, SDValue &Index, SDValue &Disp,
225                        SDValue &Segment);
226     bool selectLEA64_32Addr(SDValue N, SDValue &Base,
227                             SDValue &Scale, SDValue &Index, SDValue &Disp,
228                             SDValue &Segment);
229     bool selectTLSADDRAddr(SDValue N, SDValue &Base,
230                            SDValue &Scale, SDValue &Index, SDValue &Disp,
231                            SDValue &Segment);
232     bool selectScalarSSELoad(SDNode *Root, SDNode *Parent, SDValue N,
233                              SDValue &Base, SDValue &Scale,
234                              SDValue &Index, SDValue &Disp,
235                              SDValue &Segment,
236                              SDValue &NodeWithChain);
237     bool selectRelocImm(SDValue N, SDValue &Op);
238 
239     bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
240                      SDValue &Base, SDValue &Scale,
241                      SDValue &Index, SDValue &Disp,
242                      SDValue &Segment);
243 
244     // Convenience method where P is also root.
245     bool tryFoldLoad(SDNode *P, SDValue N,
246                      SDValue &Base, SDValue &Scale,
247                      SDValue &Index, SDValue &Disp,
248                      SDValue &Segment) {
249       return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
250     }
251 
252     bool tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
253                           SDValue &Base, SDValue &Scale,
254                           SDValue &Index, SDValue &Disp,
255                           SDValue &Segment);
256 
257     bool isProfitableToFormMaskedOp(SDNode *N) const;
258 
259     /// Implement addressing mode selection for inline asm expressions.
260     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
261                                       unsigned ConstraintID,
262                                       std::vector<SDValue> &OutOps) override;
263 
264     void emitSpecialCodeForMain();
265 
266     inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
267                                    MVT VT, SDValue &Base, SDValue &Scale,
268                                    SDValue &Index, SDValue &Disp,
269                                    SDValue &Segment) {
270       if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
271         Base = CurDAG->getTargetFrameIndex(
272             AM.Base_FrameIndex, TLI->getPointerTy(CurDAG->getDataLayout()));
273       else if (AM.Base_Reg.getNode())
274         Base = AM.Base_Reg;
275       else
276         Base = CurDAG->getRegister(0, VT);
277 
278       Scale = getI8Imm(AM.Scale, DL);
279 
280       // Negate the index if needed.
281       if (AM.NegateIndex) {
282         unsigned NegOpc = VT == MVT::i64 ? X86::NEG64r : X86::NEG32r;
283         SDValue Neg = SDValue(CurDAG->getMachineNode(NegOpc, DL, VT, MVT::i32,
284                                                      AM.IndexReg), 0);
285         AM.IndexReg = Neg;
286       }
287 
288       if (AM.IndexReg.getNode())
289         Index = AM.IndexReg;
290       else
291         Index = CurDAG->getRegister(0, VT);
292 
293       // These are 32-bit even in 64-bit mode since RIP-relative offset
294       // is 32-bit.
295       if (AM.GV)
296         Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
297                                               MVT::i32, AM.Disp,
298                                               AM.SymbolFlags);
299       else if (AM.CP)
300         Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32,
301                                              AM.Align, AM.Disp, AM.SymbolFlags);
302       else if (AM.ES) {
303         assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
304         Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
305       } else if (AM.MCSym) {
306         assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
307         assert(AM.SymbolFlags == 0 && "oo");
308         Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
309       } else if (AM.JT != -1) {
310         assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
311         Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
312       } else if (AM.BlockAddr)
313         Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
314                                              AM.SymbolFlags);
315       else
316         Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
317 
318       if (AM.Segment.getNode())
319         Segment = AM.Segment;
320       else
321         Segment = CurDAG->getRegister(0, MVT::i16);
322     }
323 
324     // Utility function to determine whether we should avoid selecting
325     // immediate forms of instructions for better code size or not.
326     // At a high level, we'd like to avoid such instructions when
327     // we have similar constants used within the same basic block
328     // that can be kept in a register.
329     //
330     bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
331       uint32_t UseCount = 0;
332 
333       // Do not want to hoist if we're not optimizing for size.
334       // TODO: We'd like to remove this restriction.
335       // See the comment in X86InstrInfo.td for more info.
336       if (!CurDAG->shouldOptForSize())
337         return false;
338 
339       // Walk all the users of the immediate.
340       for (SDNode::use_iterator UI = N->use_begin(),
341            UE = N->use_end(); (UI != UE) && (UseCount < 2); ++UI) {
342 
343         SDNode *User = *UI;
344 
345         // This user is already selected. Count it as a legitimate use and
346         // move on.
347         if (User->isMachineOpcode()) {
348           UseCount++;
349           continue;
350         }
351 
352         // We want to count stores of immediates as real uses.
353         if (User->getOpcode() == ISD::STORE &&
354             User->getOperand(1).getNode() == N) {
355           UseCount++;
356           continue;
357         }
358 
359         // We don't currently match users that have > 2 operands (except
360         // for stores, which are handled above)
361         // Those instruction won't match in ISEL, for now, and would
362         // be counted incorrectly.
363         // This may change in the future as we add additional instruction
364         // types.
365         if (User->getNumOperands() != 2)
366           continue;
367 
368         // If this can match to INC/DEC, don't count it as a use.
369         if (User->getOpcode() == ISD::ADD &&
370             (isOneConstant(SDValue(N, 0)) || isAllOnesConstant(SDValue(N, 0))))
371           continue;
372 
373         // Immediates that are used for offsets as part of stack
374         // manipulation should be left alone. These are typically
375         // used to indicate SP offsets for argument passing and
376         // will get pulled into stores/pushes (implicitly).
377         if (User->getOpcode() == X86ISD::ADD ||
378             User->getOpcode() == ISD::ADD    ||
379             User->getOpcode() == X86ISD::SUB ||
380             User->getOpcode() == ISD::SUB) {
381 
382           // Find the other operand of the add/sub.
383           SDValue OtherOp = User->getOperand(0);
384           if (OtherOp.getNode() == N)
385             OtherOp = User->getOperand(1);
386 
387           // Don't count if the other operand is SP.
388           RegisterSDNode *RegNode;
389           if (OtherOp->getOpcode() == ISD::CopyFromReg &&
390               (RegNode = dyn_cast_or_null<RegisterSDNode>(
391                  OtherOp->getOperand(1).getNode())))
392             if ((RegNode->getReg() == X86::ESP) ||
393                 (RegNode->getReg() == X86::RSP))
394               continue;
395         }
396 
397         // ... otherwise, count this and move on.
398         UseCount++;
399       }
400 
401       // If we have more than 1 use, then recommend for hoisting.
402       return (UseCount > 1);
403     }
404 
405     /// Return a target constant with the specified value of type i8.
406     inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
407       return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
408     }
409 
410     /// Return a target constant with the specified value, of type i32.
411     inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
412       return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
413     }
414 
415     /// Return a target constant with the specified value, of type i64.
416     inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
417       return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
418     }
419 
420     SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
421                                         const SDLoc &DL) {
422       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
423       uint64_t Index = N->getConstantOperandVal(1);
424       MVT VecVT = N->getOperand(0).getSimpleValueType();
425       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
426     }
427 
428     SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
429                                       const SDLoc &DL) {
430       assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
431       uint64_t Index = N->getConstantOperandVal(2);
432       MVT VecVT = N->getSimpleValueType(0);
433       return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
434     }
435 
436     // Helper to detect unneeded and instructions on shift amounts. Called
437     // from PatFrags in tablegen.
438     bool isUnneededShiftMask(SDNode *N, unsigned Width) const {
439       assert(N->getOpcode() == ISD::AND && "Unexpected opcode");
440       const APInt &Val = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
441 
442       if (Val.countTrailingOnes() >= Width)
443         return true;
444 
445       APInt Mask = Val | CurDAG->computeKnownBits(N->getOperand(0)).Zero;
446       return Mask.countTrailingOnes() >= Width;
447     }
448 
449     /// Return an SDNode that returns the value of the global base register.
450     /// Output instructions required to initialize the global base register,
451     /// if necessary.
452     SDNode *getGlobalBaseReg();
453 
454     /// Return a reference to the TargetMachine, casted to the target-specific
455     /// type.
456     const X86TargetMachine &getTargetMachine() const {
457       return static_cast<const X86TargetMachine &>(TM);
458     }
459 
460     /// Return a reference to the TargetInstrInfo, casted to the target-specific
461     /// type.
462     const X86InstrInfo *getInstrInfo() const {
463       return Subtarget->getInstrInfo();
464     }
465 
466     /// Address-mode matching performs shift-of-and to and-of-shift
467     /// reassociation in order to expose more scaled addressing
468     /// opportunities.
469     bool ComplexPatternFuncMutatesDAG() const override {
470       return true;
471     }
472 
473     bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
474 
475     /// Returns whether this is a relocatable immediate in the range
476     /// [-2^Width .. 2^Width-1].
477     template <unsigned Width> bool isSExtRelocImm(SDNode *N) const {
478       if (auto *CN = dyn_cast<ConstantSDNode>(N))
479         return isInt<Width>(CN->getSExtValue());
480       return isSExtAbsoluteSymbolRef(Width, N);
481     }
482 
483     // Indicates we should prefer to use a non-temporal load for this load.
484     bool useNonTemporalLoad(LoadSDNode *N) const {
485       if (!N->isNonTemporal())
486         return false;
487 
488       unsigned StoreSize = N->getMemoryVT().getStoreSize();
489 
490       if (N->getAlignment() < StoreSize)
491         return false;
492 
493       switch (StoreSize) {
494       default: llvm_unreachable("Unsupported store size");
495       case 4:
496       case 8:
497         return false;
498       case 16:
499         return Subtarget->hasSSE41();
500       case 32:
501         return Subtarget->hasAVX2();
502       case 64:
503         return Subtarget->hasAVX512();
504       }
505     }
506 
507     bool foldLoadStoreIntoMemOperand(SDNode *Node);
508     MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);
509     bool matchBitExtract(SDNode *Node);
510     bool shrinkAndImmediate(SDNode *N);
511     bool isMaskZeroExtended(SDNode *N) const;
512     bool tryShiftAmountMod(SDNode *N);
513     bool tryShrinkShlLogicImm(SDNode *N);
514     bool tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue Mask);
515     bool tryMatchBitSelect(SDNode *N);
516 
517     MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
518                                 const SDLoc &dl, MVT VT, SDNode *Node);
519     MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
520                                 const SDLoc &dl, MVT VT, SDNode *Node,
521                                 SDValue &InFlag);
522 
523     bool tryOptimizeRem8Extend(SDNode *N);
524 
525     bool onlyUsesZeroFlag(SDValue Flags) const;
526     bool hasNoSignFlagUses(SDValue Flags) const;
527     bool hasNoCarryFlagUses(SDValue Flags) const;
528   };
529 }
530 
531 
532 // Returns true if this masked compare can be implemented legally with this
533 // type.
534 static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
535   unsigned Opcode = N->getOpcode();
536   if (Opcode == X86ISD::CMPM || Opcode == X86ISD::STRICT_CMPM ||
537       Opcode == ISD::SETCC || Opcode == X86ISD::CMPM_SAE ||
538       Opcode == X86ISD::VFPCLASS) {
539     // We can get 256-bit 8 element types here without VLX being enabled. When
540     // this happens we will use 512-bit operations and the mask will not be
541     // zero extended.
542     EVT OpVT = N->getOperand(0).getValueType();
543     // The first operand of X86ISD::STRICT_CMPM is chain, so we need to get the
544     // second operand.
545     if (Opcode == X86ISD::STRICT_CMPM)
546       OpVT = N->getOperand(1).getValueType();
547     if (OpVT.is256BitVector() || OpVT.is128BitVector())
548       return Subtarget->hasVLX();
549 
550     return true;
551   }
552   // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
553   if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
554       Opcode == X86ISD::FSETCCM_SAE)
555     return true;
556 
557   return false;
558 }
559 
560 // Returns true if we can assume the writer of the mask has zero extended it
561 // for us.
562 bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
563   // If this is an AND, check if we have a compare on either side. As long as
564   // one side guarantees the mask is zero extended, the AND will preserve those
565   // zeros.
566   if (N->getOpcode() == ISD::AND)
567     return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
568            isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
569 
570   return isLegalMaskCompare(N, Subtarget);
571 }
572 
573 bool
574 X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
575   if (OptLevel == CodeGenOpt::None) return false;
576 
577   if (!N.hasOneUse())
578     return false;
579 
580   if (N.getOpcode() != ISD::LOAD)
581     return true;
582 
583   // Don't fold non-temporal loads if we have an instruction for them.
584   if (useNonTemporalLoad(cast<LoadSDNode>(N)))
585     return false;
586 
587   // If N is a load, do additional profitability checks.
588   if (U == Root) {
589     switch (U->getOpcode()) {
590     default: break;
591     case X86ISD::ADD:
592     case X86ISD::ADC:
593     case X86ISD::SUB:
594     case X86ISD::SBB:
595     case X86ISD::AND:
596     case X86ISD::XOR:
597     case X86ISD::OR:
598     case ISD::ADD:
599     case ISD::ADDCARRY:
600     case ISD::AND:
601     case ISD::OR:
602     case ISD::XOR: {
603       SDValue Op1 = U->getOperand(1);
604 
605       // If the other operand is a 8-bit immediate we should fold the immediate
606       // instead. This reduces code size.
607       // e.g.
608       // movl 4(%esp), %eax
609       // addl $4, %eax
610       // vs.
611       // movl $4, %eax
612       // addl 4(%esp), %eax
613       // The former is 2 bytes shorter. In case where the increment is 1, then
614       // the saving can be 4 bytes (by using incl %eax).
615       if (ConstantSDNode *Imm = dyn_cast<ConstantSDNode>(Op1)) {
616         if (Imm->getAPIntValue().isSignedIntN(8))
617           return false;
618 
619         // If this is a 64-bit AND with an immediate that fits in 32-bits,
620         // prefer using the smaller and over folding the load. This is needed to
621         // make sure immediates created by shrinkAndImmediate are always folded.
622         // Ideally we would narrow the load during DAG combine and get the
623         // best of both worlds.
624         if (U->getOpcode() == ISD::AND &&
625             Imm->getAPIntValue().getBitWidth() == 64 &&
626             Imm->getAPIntValue().isIntN(32))
627           return false;
628 
629         // If this really a zext_inreg that can be represented with a movzx
630         // instruction, prefer that.
631         // TODO: We could shrink the load and fold if it is non-volatile.
632         if (U->getOpcode() == ISD::AND &&
633             (Imm->getAPIntValue() == UINT8_MAX ||
634              Imm->getAPIntValue() == UINT16_MAX ||
635              Imm->getAPIntValue() == UINT32_MAX))
636           return false;
637 
638         // ADD/SUB with can negate the immediate and use the opposite operation
639         // to fit 128 into a sign extended 8 bit immediate.
640         if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB) &&
641             (-Imm->getAPIntValue()).isSignedIntN(8))
642           return false;
643 
644         if ((U->getOpcode() == X86ISD::ADD || U->getOpcode() == X86ISD::SUB) &&
645             (-Imm->getAPIntValue()).isSignedIntN(8) &&
646             hasNoCarryFlagUses(SDValue(U, 1)))
647           return false;
648       }
649 
650       // If the other operand is a TLS address, we should fold it instead.
651       // This produces
652       // movl    %gs:0, %eax
653       // leal    i@NTPOFF(%eax), %eax
654       // instead of
655       // movl    $i@NTPOFF, %eax
656       // addl    %gs:0, %eax
657       // if the block also has an access to a second TLS address this will save
658       // a load.
659       // FIXME: This is probably also true for non-TLS addresses.
660       if (Op1.getOpcode() == X86ISD::Wrapper) {
661         SDValue Val = Op1.getOperand(0);
662         if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
663           return false;
664       }
665 
666       // Don't fold load if this matches the BTS/BTR/BTC patterns.
667       // BTS: (or X, (shl 1, n))
668       // BTR: (and X, (rotl -2, n))
669       // BTC: (xor X, (shl 1, n))
670       if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
671         if (U->getOperand(0).getOpcode() == ISD::SHL &&
672             isOneConstant(U->getOperand(0).getOperand(0)))
673           return false;
674 
675         if (U->getOperand(1).getOpcode() == ISD::SHL &&
676             isOneConstant(U->getOperand(1).getOperand(0)))
677           return false;
678       }
679       if (U->getOpcode() == ISD::AND) {
680         SDValue U0 = U->getOperand(0);
681         SDValue U1 = U->getOperand(1);
682         if (U0.getOpcode() == ISD::ROTL) {
683           auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
684           if (C && C->getSExtValue() == -2)
685             return false;
686         }
687 
688         if (U1.getOpcode() == ISD::ROTL) {
689           auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
690           if (C && C->getSExtValue() == -2)
691             return false;
692         }
693       }
694 
695       break;
696     }
697     case ISD::SHL:
698     case ISD::SRA:
699     case ISD::SRL:
700       // Don't fold a load into a shift by immediate. The BMI2 instructions
701       // support folding a load, but not an immediate. The legacy instructions
702       // support folding an immediate, but can't fold a load. Folding an
703       // immediate is preferable to folding a load.
704       if (isa<ConstantSDNode>(U->getOperand(1)))
705         return false;
706 
707       break;
708     }
709   }
710 
711   // Prevent folding a load if this can implemented with an insert_subreg or
712   // a move that implicitly zeroes.
713   if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
714       isNullConstant(Root->getOperand(2)) &&
715       (Root->getOperand(0).isUndef() ||
716        ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode())))
717     return false;
718 
719   return true;
720 }
721 
722 // Indicates it is profitable to form an AVX512 masked operation. Returning
723 // false will favor a masked register-register masked move or vblendm and the
724 // operation will be selected separately.
725 bool X86DAGToDAGISel::isProfitableToFormMaskedOp(SDNode *N) const {
726   assert(
727       (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::SELECTS) &&
728       "Unexpected opcode!");
729 
730   // If the operation has additional users, the operation will be duplicated.
731   // Check the use count to prevent that.
732   // FIXME: Are there cheap opcodes we might want to duplicate?
733   return N->getOperand(1).hasOneUse();
734 }
735 
736 /// Replace the original chain operand of the call with
737 /// load's chain operand and move load below the call's chain operand.
738 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
739                                SDValue Call, SDValue OrigChain) {
740   SmallVector<SDValue, 8> Ops;
741   SDValue Chain = OrigChain.getOperand(0);
742   if (Chain.getNode() == Load.getNode())
743     Ops.push_back(Load.getOperand(0));
744   else {
745     assert(Chain.getOpcode() == ISD::TokenFactor &&
746            "Unexpected chain operand");
747     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
748       if (Chain.getOperand(i).getNode() == Load.getNode())
749         Ops.push_back(Load.getOperand(0));
750       else
751         Ops.push_back(Chain.getOperand(i));
752     SDValue NewChain =
753       CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
754     Ops.clear();
755     Ops.push_back(NewChain);
756   }
757   Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
758   CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
759   CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
760                              Load.getOperand(1), Load.getOperand(2));
761 
762   Ops.clear();
763   Ops.push_back(SDValue(Load.getNode(), 1));
764   Ops.append(Call->op_begin() + 1, Call->op_end());
765   CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
766 }
767 
768 /// Return true if call address is a load and it can be
769 /// moved below CALLSEQ_START and the chains leading up to the call.
770 /// Return the CALLSEQ_START by reference as a second output.
771 /// In the case of a tail call, there isn't a callseq node between the call
772 /// chain and the load.
773 static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
774   // The transformation is somewhat dangerous if the call's chain was glued to
775   // the call. After MoveBelowOrigChain the load is moved between the call and
776   // the chain, this can create a cycle if the load is not folded. So it is
777   // *really* important that we are sure the load will be folded.
778   if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
779     return false;
780   LoadSDNode *LD = dyn_cast<LoadSDNode>(Callee.getNode());
781   if (!LD ||
782       !LD->isSimple() ||
783       LD->getAddressingMode() != ISD::UNINDEXED ||
784       LD->getExtensionType() != ISD::NON_EXTLOAD)
785     return false;
786 
787   // Now let's find the callseq_start.
788   while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
789     if (!Chain.hasOneUse())
790       return false;
791     Chain = Chain.getOperand(0);
792   }
793 
794   if (!Chain.getNumOperands())
795     return false;
796   // Since we are not checking for AA here, conservatively abort if the chain
797   // writes to memory. It's not safe to move the callee (a load) across a store.
798   if (isa<MemSDNode>(Chain.getNode()) &&
799       cast<MemSDNode>(Chain.getNode())->writeMem())
800     return false;
801   if (Chain.getOperand(0).getNode() == Callee.getNode())
802     return true;
803   if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
804       Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
805       Callee.getValue(1).hasOneUse())
806     return true;
807   return false;
808 }
809 
810 void X86DAGToDAGISel::PreprocessISelDAG() {
811   for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
812        E = CurDAG->allnodes_end(); I != E; ) {
813     SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
814 
815     // If this is a target specific AND node with no flag usages, turn it back
816     // into ISD::AND to enable test instruction matching.
817     if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
818       SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
819                                     N->getOperand(0), N->getOperand(1));
820       --I;
821       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
822       ++I;
823       CurDAG->DeleteNode(N);
824       continue;
825     }
826 
827     /// Convert vector increment or decrement to sub/add with an all-ones
828     /// constant:
829     /// add X, <1, 1...> --> sub X, <-1, -1...>
830     /// sub X, <1, 1...> --> add X, <-1, -1...>
831     /// The all-ones vector constant can be materialized using a pcmpeq
832     /// instruction that is commonly recognized as an idiom (has no register
833     /// dependency), so that's better/smaller than loading a splat 1 constant.
834     if ((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
835         N->getSimpleValueType(0).isVector()) {
836 
837       APInt SplatVal;
838       if (X86::isConstantSplat(N->getOperand(1), SplatVal) &&
839           SplatVal.isOneValue()) {
840         SDLoc DL(N);
841 
842         MVT VT = N->getSimpleValueType(0);
843         unsigned NumElts = VT.getSizeInBits() / 32;
844         SDValue AllOnes =
845             CurDAG->getAllOnesConstant(DL, MVT::getVectorVT(MVT::i32, NumElts));
846         AllOnes = CurDAG->getBitcast(VT, AllOnes);
847 
848         unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD;
849         SDValue Res =
850             CurDAG->getNode(NewOpcode, DL, VT, N->getOperand(0), AllOnes);
851         --I;
852         CurDAG->ReplaceAllUsesWith(N, Res.getNode());
853         ++I;
854         CurDAG->DeleteNode(N);
855         continue;
856       }
857     }
858 
859     switch (N->getOpcode()) {
860     case X86ISD::VBROADCAST: {
861       MVT VT = N->getSimpleValueType(0);
862       // Emulate v32i16/v64i8 broadcast without BWI.
863       if (!Subtarget->hasBWI() && (VT == MVT::v32i16 || VT == MVT::v64i8)) {
864         MVT NarrowVT = VT == MVT::v32i16 ? MVT::v16i16 : MVT::v32i8;
865         SDLoc dl(N);
866         SDValue NarrowBCast =
867             CurDAG->getNode(X86ISD::VBROADCAST, dl, NarrowVT, N->getOperand(0));
868         SDValue Res =
869             CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
870                             NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
871         unsigned Index = VT == MVT::v32i16 ? 16 : 32;
872         Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
873                               CurDAG->getIntPtrConstant(Index, dl));
874 
875         --I;
876         CurDAG->ReplaceAllUsesWith(N, Res.getNode());
877         ++I;
878         CurDAG->DeleteNode(N);
879       }
880 
881       break;
882     }
883     case X86ISD::VBROADCAST_LOAD: {
884       MVT VT = N->getSimpleValueType(0);
885       // Emulate v32i16/v64i8 broadcast without BWI.
886       if (!Subtarget->hasBWI() && (VT == MVT::v32i16 || VT == MVT::v64i8)) {
887         MVT NarrowVT = VT == MVT::v32i16 ? MVT::v16i16 : MVT::v32i8;
888         auto *MemNode = cast<MemSDNode>(N);
889         SDLoc dl(N);
890         SDVTList VTs = CurDAG->getVTList(NarrowVT, MVT::Other);
891         SDValue Ops[] = {MemNode->getChain(), MemNode->getBasePtr()};
892         SDValue NarrowBCast = CurDAG->getMemIntrinsicNode(
893             X86ISD::VBROADCAST_LOAD, dl, VTs, Ops, MemNode->getMemoryVT(),
894             MemNode->getMemOperand());
895         SDValue Res =
896             CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
897                             NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
898         unsigned Index = VT == MVT::v32i16 ? 16 : 32;
899         Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
900                               CurDAG->getIntPtrConstant(Index, dl));
901 
902         --I;
903         SDValue To[] = {Res, NarrowBCast.getValue(1)};
904         CurDAG->ReplaceAllUsesWith(N, To);
905         ++I;
906         CurDAG->DeleteNode(N);
907       }
908 
909       break;
910     }
911     case ISD::VSELECT: {
912       // Replace VSELECT with non-mask conditions with with BLENDV.
913       if (N->getOperand(0).getValueType().getVectorElementType() == MVT::i1)
914         break;
915 
916       assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!");
917       SDValue Blendv =
918           CurDAG->getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0),
919                           N->getOperand(0), N->getOperand(1), N->getOperand(2));
920       --I;
921       CurDAG->ReplaceAllUsesWith(N, Blendv.getNode());
922       ++I;
923       CurDAG->DeleteNode(N);
924       continue;
925     }
926     case ISD::FP_ROUND:
927     case ISD::STRICT_FP_ROUND:
928     case ISD::FP_TO_SINT:
929     case ISD::FP_TO_UINT:
930     case ISD::STRICT_FP_TO_SINT:
931     case ISD::STRICT_FP_TO_UINT: {
932       // Replace vector fp_to_s/uint with their X86 specific equivalent so we
933       // don't need 2 sets of patterns.
934       if (!N->getSimpleValueType(0).isVector())
935         break;
936 
937       unsigned NewOpc;
938       switch (N->getOpcode()) {
939       default: llvm_unreachable("Unexpected opcode!");
940       case ISD::FP_ROUND:          NewOpc = X86ISD::VFPROUND;        break;
941       case ISD::STRICT_FP_ROUND:   NewOpc = X86ISD::STRICT_VFPROUND; break;
942       case ISD::STRICT_FP_TO_SINT: NewOpc = X86ISD::STRICT_CVTTP2SI; break;
943       case ISD::FP_TO_SINT:        NewOpc = X86ISD::CVTTP2SI;        break;
944       case ISD::STRICT_FP_TO_UINT: NewOpc = X86ISD::STRICT_CVTTP2UI; break;
945       case ISD::FP_TO_UINT:        NewOpc = X86ISD::CVTTP2UI;        break;
946       }
947       SDValue Res;
948       if (N->isStrictFPOpcode())
949         Res =
950             CurDAG->getNode(NewOpc, SDLoc(N), {N->getValueType(0), MVT::Other},
951                             {N->getOperand(0), N->getOperand(1)});
952       else
953         Res =
954             CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
955                             N->getOperand(0));
956       --I;
957       CurDAG->ReplaceAllUsesWith(N, Res.getNode());
958       ++I;
959       CurDAG->DeleteNode(N);
960       continue;
961     }
962     case ISD::SHL:
963     case ISD::SRA:
964     case ISD::SRL: {
965       // Replace vector shifts with their X86 specific equivalent so we don't
966       // need 2 sets of patterns.
967       if (!N->getValueType(0).isVector())
968         break;
969 
970       unsigned NewOpc;
971       switch (N->getOpcode()) {
972       default: llvm_unreachable("Unexpected opcode!");
973       case ISD::SHL: NewOpc = X86ISD::VSHLV; break;
974       case ISD::SRA: NewOpc = X86ISD::VSRAV; break;
975       case ISD::SRL: NewOpc = X86ISD::VSRLV; break;
976       }
977       SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
978                                     N->getOperand(0), N->getOperand(1));
979       --I;
980       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
981       ++I;
982       CurDAG->DeleteNode(N);
983       continue;
984     }
985     case ISD::ANY_EXTEND:
986     case ISD::ANY_EXTEND_VECTOR_INREG: {
987       // Replace vector any extend with the zero extend equivalents so we don't
988       // need 2 sets of patterns. Ignore vXi1 extensions.
989       if (!N->getValueType(0).isVector())
990         break;
991 
992       unsigned NewOpc;
993       if (N->getOperand(0).getScalarValueSizeInBits() == 1) {
994         assert(N->getOpcode() == ISD::ANY_EXTEND &&
995                "Unexpected opcode for mask vector!");
996         NewOpc = ISD::SIGN_EXTEND;
997       } else {
998         NewOpc = N->getOpcode() == ISD::ANY_EXTEND
999                               ? ISD::ZERO_EXTEND
1000                               : ISD::ZERO_EXTEND_VECTOR_INREG;
1001       }
1002 
1003       SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
1004                                     N->getOperand(0));
1005       --I;
1006       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1007       ++I;
1008       CurDAG->DeleteNode(N);
1009       continue;
1010     }
1011     case ISD::FCEIL:
1012     case ISD::STRICT_FCEIL:
1013     case ISD::FFLOOR:
1014     case ISD::STRICT_FFLOOR:
1015     case ISD::FTRUNC:
1016     case ISD::STRICT_FTRUNC:
1017     case ISD::FNEARBYINT:
1018     case ISD::STRICT_FNEARBYINT:
1019     case ISD::FRINT:
1020     case ISD::STRICT_FRINT: {
1021       // Replace fp rounding with their X86 specific equivalent so we don't
1022       // need 2 sets of patterns.
1023       unsigned Imm;
1024       switch (N->getOpcode()) {
1025       default: llvm_unreachable("Unexpected opcode!");
1026       case ISD::STRICT_FCEIL:
1027       case ISD::FCEIL:      Imm = 0xA; break;
1028       case ISD::STRICT_FFLOOR:
1029       case ISD::FFLOOR:     Imm = 0x9; break;
1030       case ISD::STRICT_FTRUNC:
1031       case ISD::FTRUNC:     Imm = 0xB; break;
1032       case ISD::STRICT_FNEARBYINT:
1033       case ISD::FNEARBYINT: Imm = 0xC; break;
1034       case ISD::STRICT_FRINT:
1035       case ISD::FRINT:      Imm = 0x4; break;
1036       }
1037       SDLoc dl(N);
1038       bool IsStrict = N->isStrictFPOpcode();
1039       SDValue Res;
1040       if (IsStrict)
1041         Res = CurDAG->getNode(X86ISD::STRICT_VRNDSCALE, dl,
1042                               {N->getValueType(0), MVT::Other},
1043                               {N->getOperand(0), N->getOperand(1),
1044                                CurDAG->getTargetConstant(Imm, dl, MVT::i8)});
1045       else
1046         Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl, N->getValueType(0),
1047                               N->getOperand(0),
1048                               CurDAG->getTargetConstant(Imm, dl, MVT::i8));
1049       --I;
1050       CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1051       ++I;
1052       CurDAG->DeleteNode(N);
1053       continue;
1054     }
1055     case X86ISD::FANDN:
1056     case X86ISD::FAND:
1057     case X86ISD::FOR:
1058     case X86ISD::FXOR: {
1059       // Widen scalar fp logic ops to vector to reduce isel patterns.
1060       // FIXME: Can we do this during lowering/combine.
1061       MVT VT = N->getSimpleValueType(0);
1062       if (VT.isVector() || VT == MVT::f128)
1063         break;
1064 
1065       MVT VecVT = VT == MVT::f64 ? MVT::v2f64 : MVT::v4f32;
1066       SDLoc dl(N);
1067       SDValue Op0 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
1068                                     N->getOperand(0));
1069       SDValue Op1 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
1070                                     N->getOperand(1));
1071 
1072       SDValue Res;
1073       if (Subtarget->hasSSE2()) {
1074         EVT IntVT = EVT(VecVT).changeVectorElementTypeToInteger();
1075         Op0 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op0);
1076         Op1 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op1);
1077         unsigned Opc;
1078         switch (N->getOpcode()) {
1079         default: llvm_unreachable("Unexpected opcode!");
1080         case X86ISD::FANDN: Opc = X86ISD::ANDNP; break;
1081         case X86ISD::FAND:  Opc = ISD::AND;      break;
1082         case X86ISD::FOR:   Opc = ISD::OR;       break;
1083         case X86ISD::FXOR:  Opc = ISD::XOR;      break;
1084         }
1085         Res = CurDAG->getNode(Opc, dl, IntVT, Op0, Op1);
1086         Res = CurDAG->getNode(ISD::BITCAST, dl, VecVT, Res);
1087       } else {
1088         Res = CurDAG->getNode(N->getOpcode(), dl, VecVT, Op0, Op1);
1089       }
1090       Res = CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res,
1091                             CurDAG->getIntPtrConstant(0, dl));
1092       --I;
1093       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1094       ++I;
1095       CurDAG->DeleteNode(N);
1096       continue;
1097     }
1098     }
1099 
1100     if (OptLevel != CodeGenOpt::None &&
1101         // Only do this when the target can fold the load into the call or
1102         // jmp.
1103         !Subtarget->useIndirectThunkCalls() &&
1104         ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
1105          (N->getOpcode() == X86ISD::TC_RETURN &&
1106           (Subtarget->is64Bit() ||
1107            !getTargetMachine().isPositionIndependent())))) {
1108       /// Also try moving call address load from outside callseq_start to just
1109       /// before the call to allow it to be folded.
1110       ///
1111       ///     [Load chain]
1112       ///         ^
1113       ///         |
1114       ///       [Load]
1115       ///       ^    ^
1116       ///       |    |
1117       ///      /      \--
1118       ///     /          |
1119       ///[CALLSEQ_START] |
1120       ///     ^          |
1121       ///     |          |
1122       /// [LOAD/C2Reg]   |
1123       ///     |          |
1124       ///      \        /
1125       ///       \      /
1126       ///       [CALL]
1127       bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
1128       SDValue Chain = N->getOperand(0);
1129       SDValue Load  = N->getOperand(1);
1130       if (!isCalleeLoad(Load, Chain, HasCallSeq))
1131         continue;
1132       moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
1133       ++NumLoadMoved;
1134       continue;
1135     }
1136 
1137     // Lower fpround and fpextend nodes that target the FP stack to be store and
1138     // load to the stack.  This is a gross hack.  We would like to simply mark
1139     // these as being illegal, but when we do that, legalize produces these when
1140     // it expands calls, then expands these in the same legalize pass.  We would
1141     // like dag combine to be able to hack on these between the call expansion
1142     // and the node legalization.  As such this pass basically does "really
1143     // late" legalization of these inline with the X86 isel pass.
1144     // FIXME: This should only happen when not compiled with -O0.
1145     switch (N->getOpcode()) {
1146     default: continue;
1147     case ISD::FP_ROUND:
1148     case ISD::FP_EXTEND:
1149     {
1150       MVT SrcVT = N->getOperand(0).getSimpleValueType();
1151       MVT DstVT = N->getSimpleValueType(0);
1152 
1153       // If any of the sources are vectors, no fp stack involved.
1154       if (SrcVT.isVector() || DstVT.isVector())
1155         continue;
1156 
1157       // If the source and destination are SSE registers, then this is a legal
1158       // conversion that should not be lowered.
1159       const X86TargetLowering *X86Lowering =
1160           static_cast<const X86TargetLowering *>(TLI);
1161       bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
1162       bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
1163       if (SrcIsSSE && DstIsSSE)
1164         continue;
1165 
1166       if (!SrcIsSSE && !DstIsSSE) {
1167         // If this is an FPStack extension, it is a noop.
1168         if (N->getOpcode() == ISD::FP_EXTEND)
1169           continue;
1170         // If this is a value-preserving FPStack truncation, it is a noop.
1171         if (N->getConstantOperandVal(1))
1172           continue;
1173       }
1174 
1175       // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
1176       // FPStack has extload and truncstore.  SSE can fold direct loads into other
1177       // operations.  Based on this, decide what we want to do.
1178       MVT MemVT = (N->getOpcode() == ISD::FP_ROUND) ? DstVT : SrcVT;
1179       SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
1180       int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
1181       MachinePointerInfo MPI =
1182           MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
1183       SDLoc dl(N);
1184 
1185       // FIXME: optimize the case where the src/dest is a load or store?
1186 
1187       SDValue Store = CurDAG->getTruncStore(
1188           CurDAG->getEntryNode(), dl, N->getOperand(0), MemTmp, MPI, MemVT);
1189       SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store,
1190                                           MemTmp, MPI, MemVT);
1191 
1192       // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
1193       // extload we created.  This will cause general havok on the dag because
1194       // anything below the conversion could be folded into other existing nodes.
1195       // To avoid invalidating 'I', back it up to the convert node.
1196       --I;
1197       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1198       break;
1199     }
1200 
1201     //The sequence of events for lowering STRICT_FP versions of these nodes requires
1202     //dealing with the chain differently, as there is already a preexisting chain.
1203     case ISD::STRICT_FP_ROUND:
1204     case ISD::STRICT_FP_EXTEND:
1205     {
1206       MVT SrcVT = N->getOperand(1).getSimpleValueType();
1207       MVT DstVT = N->getSimpleValueType(0);
1208 
1209       // If any of the sources are vectors, no fp stack involved.
1210       if (SrcVT.isVector() || DstVT.isVector())
1211         continue;
1212 
1213       // If the source and destination are SSE registers, then this is a legal
1214       // conversion that should not be lowered.
1215       const X86TargetLowering *X86Lowering =
1216           static_cast<const X86TargetLowering *>(TLI);
1217       bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
1218       bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
1219       if (SrcIsSSE && DstIsSSE)
1220         continue;
1221 
1222       if (!SrcIsSSE && !DstIsSSE) {
1223         // If this is an FPStack extension, it is a noop.
1224         if (N->getOpcode() == ISD::STRICT_FP_EXTEND)
1225           continue;
1226         // If this is a value-preserving FPStack truncation, it is a noop.
1227         if (N->getConstantOperandVal(2))
1228           continue;
1229       }
1230 
1231       // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
1232       // FPStack has extload and truncstore.  SSE can fold direct loads into other
1233       // operations.  Based on this, decide what we want to do.
1234       MVT MemVT = (N->getOpcode() == ISD::STRICT_FP_ROUND) ? DstVT : SrcVT;
1235       SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
1236       int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
1237       MachinePointerInfo MPI =
1238           MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
1239       SDLoc dl(N);
1240 
1241       // FIXME: optimize the case where the src/dest is a load or store?
1242 
1243       //Since the operation is StrictFP, use the preexisting chain.
1244       SDValue Store, Result;
1245       if (!SrcIsSSE) {
1246         SDVTList VTs = CurDAG->getVTList(MVT::Other);
1247         SDValue Ops[] = {N->getOperand(0), N->getOperand(1), MemTmp};
1248         Store = CurDAG->getMemIntrinsicNode(X86ISD::FST, dl, VTs, Ops, MemVT,
1249                                             MPI, /*Align*/ None,
1250                                             MachineMemOperand::MOStore);
1251         if (N->getFlags().hasNoFPExcept()) {
1252           SDNodeFlags Flags = Store->getFlags();
1253           Flags.setNoFPExcept(true);
1254           Store->setFlags(Flags);
1255         }
1256       } else {
1257         assert(SrcVT == MemVT && "Unexpected VT!");
1258         Store = CurDAG->getStore(N->getOperand(0), dl, N->getOperand(1), MemTmp,
1259                                  MPI);
1260       }
1261 
1262       if (!DstIsSSE) {
1263         SDVTList VTs = CurDAG->getVTList(DstVT, MVT::Other);
1264         SDValue Ops[] = {Store, MemTmp};
1265         Result = CurDAG->getMemIntrinsicNode(
1266             X86ISD::FLD, dl, VTs, Ops, MemVT, MPI,
1267             /*Align*/ None, MachineMemOperand::MOLoad);
1268         if (N->getFlags().hasNoFPExcept()) {
1269           SDNodeFlags Flags = Result->getFlags();
1270           Flags.setNoFPExcept(true);
1271           Result->setFlags(Flags);
1272         }
1273       } else {
1274         assert(DstVT == MemVT && "Unexpected VT!");
1275         Result = CurDAG->getLoad(DstVT, dl, Store, MemTmp, MPI);
1276       }
1277 
1278       // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
1279       // extload we created.  This will cause general havok on the dag because
1280       // anything below the conversion could be folded into other existing nodes.
1281       // To avoid invalidating 'I', back it up to the convert node.
1282       --I;
1283       CurDAG->ReplaceAllUsesWith(N, Result.getNode());
1284       break;
1285     }
1286     }
1287 
1288 
1289     // Now that we did that, the node is dead.  Increment the iterator to the
1290     // next node to process, then delete N.
1291     ++I;
1292     CurDAG->DeleteNode(N);
1293   }
1294 
1295   // The load+call transform above can leave some dead nodes in the graph. Make
1296   // sure we remove them. Its possible some of the other transforms do to so
1297   // just remove dead nodes unconditionally.
1298   CurDAG->RemoveDeadNodes();
1299 }
1300 
1301 // Look for a redundant movzx/movsx that can occur after an 8-bit divrem.
1302 bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {
1303   unsigned Opc = N->getMachineOpcode();
1304   if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&
1305       Opc != X86::MOVSX64rr8)
1306     return false;
1307 
1308   SDValue N0 = N->getOperand(0);
1309 
1310   // We need to be extracting the lower bit of an extend.
1311   if (!N0.isMachineOpcode() ||
1312       N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||
1313       N0.getConstantOperandVal(1) != X86::sub_8bit)
1314     return false;
1315 
1316   // We're looking for either a movsx or movzx to match the original opcode.
1317   unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX
1318                                                 : X86::MOVSX32rr8_NOREX;
1319   SDValue N00 = N0.getOperand(0);
1320   if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)
1321     return false;
1322 
1323   if (Opc == X86::MOVSX64rr8) {
1324     // If we had a sign extend from 8 to 64 bits. We still need to go from 32
1325     // to 64.
1326     MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),
1327                                                    MVT::i64, N00);
1328     ReplaceUses(N, Extend);
1329   } else {
1330     // Ok we can drop this extend and just use the original extend.
1331     ReplaceUses(N, N00.getNode());
1332   }
1333 
1334   return true;
1335 }
1336 
1337 void X86DAGToDAGISel::PostprocessISelDAG() {
1338   // Skip peepholes at -O0.
1339   if (TM.getOptLevel() == CodeGenOpt::None)
1340     return;
1341 
1342   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
1343 
1344   bool MadeChange = false;
1345   while (Position != CurDAG->allnodes_begin()) {
1346     SDNode *N = &*--Position;
1347     // Skip dead nodes and any non-machine opcodes.
1348     if (N->use_empty() || !N->isMachineOpcode())
1349       continue;
1350 
1351     if (tryOptimizeRem8Extend(N)) {
1352       MadeChange = true;
1353       continue;
1354     }
1355 
1356     // Look for a TESTrr+ANDrr pattern where both operands of the test are
1357     // the same. Rewrite to remove the AND.
1358     unsigned Opc = N->getMachineOpcode();
1359     if ((Opc == X86::TEST8rr || Opc == X86::TEST16rr ||
1360          Opc == X86::TEST32rr || Opc == X86::TEST64rr) &&
1361         N->getOperand(0) == N->getOperand(1) &&
1362         N->isOnlyUserOf(N->getOperand(0).getNode()) &&
1363         N->getOperand(0).isMachineOpcode()) {
1364       SDValue And = N->getOperand(0);
1365       unsigned N0Opc = And.getMachineOpcode();
1366       if (N0Opc == X86::AND8rr || N0Opc == X86::AND16rr ||
1367           N0Opc == X86::AND32rr || N0Opc == X86::AND64rr) {
1368         MachineSDNode *Test = CurDAG->getMachineNode(Opc, SDLoc(N),
1369                                                      MVT::i32,
1370                                                      And.getOperand(0),
1371                                                      And.getOperand(1));
1372         ReplaceUses(N, Test);
1373         MadeChange = true;
1374         continue;
1375       }
1376       if (N0Opc == X86::AND8rm || N0Opc == X86::AND16rm ||
1377           N0Opc == X86::AND32rm || N0Opc == X86::AND64rm) {
1378         unsigned NewOpc;
1379         switch (N0Opc) {
1380         case X86::AND8rm:  NewOpc = X86::TEST8mr; break;
1381         case X86::AND16rm: NewOpc = X86::TEST16mr; break;
1382         case X86::AND32rm: NewOpc = X86::TEST32mr; break;
1383         case X86::AND64rm: NewOpc = X86::TEST64mr; break;
1384         }
1385 
1386         // Need to swap the memory and register operand.
1387         SDValue Ops[] = { And.getOperand(1),
1388                           And.getOperand(2),
1389                           And.getOperand(3),
1390                           And.getOperand(4),
1391                           And.getOperand(5),
1392                           And.getOperand(0),
1393                           And.getOperand(6)  /* Chain */ };
1394         MachineSDNode *Test = CurDAG->getMachineNode(NewOpc, SDLoc(N),
1395                                                      MVT::i32, MVT::Other, Ops);
1396         ReplaceUses(N, Test);
1397         MadeChange = true;
1398         continue;
1399       }
1400     }
1401 
1402     // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is
1403     // used. We're doing this late so we can prefer to fold the AND into masked
1404     // comparisons. Doing that can be better for the live range of the mask
1405     // register.
1406     if ((Opc == X86::KORTESTBrr || Opc == X86::KORTESTWrr ||
1407          Opc == X86::KORTESTDrr || Opc == X86::KORTESTQrr) &&
1408         N->getOperand(0) == N->getOperand(1) &&
1409         N->isOnlyUserOf(N->getOperand(0).getNode()) &&
1410         N->getOperand(0).isMachineOpcode() &&
1411         onlyUsesZeroFlag(SDValue(N, 0))) {
1412       SDValue And = N->getOperand(0);
1413       unsigned N0Opc = And.getMachineOpcode();
1414       // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other
1415       // KAND instructions and KTEST use the same ISA feature.
1416       if (N0Opc == X86::KANDBrr ||
1417           (N0Opc == X86::KANDWrr && Subtarget->hasDQI()) ||
1418           N0Opc == X86::KANDDrr || N0Opc == X86::KANDQrr) {
1419         unsigned NewOpc;
1420         switch (Opc) {
1421         default: llvm_unreachable("Unexpected opcode!");
1422         case X86::KORTESTBrr: NewOpc = X86::KTESTBrr; break;
1423         case X86::KORTESTWrr: NewOpc = X86::KTESTWrr; break;
1424         case X86::KORTESTDrr: NewOpc = X86::KTESTDrr; break;
1425         case X86::KORTESTQrr: NewOpc = X86::KTESTQrr; break;
1426         }
1427         MachineSDNode *KTest = CurDAG->getMachineNode(NewOpc, SDLoc(N),
1428                                                       MVT::i32,
1429                                                       And.getOperand(0),
1430                                                       And.getOperand(1));
1431         ReplaceUses(N, KTest);
1432         MadeChange = true;
1433         continue;
1434       }
1435     }
1436 
1437     // Attempt to remove vectors moves that were inserted to zero upper bits.
1438     if (Opc != TargetOpcode::SUBREG_TO_REG)
1439       continue;
1440 
1441     unsigned SubRegIdx = N->getConstantOperandVal(2);
1442     if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
1443       continue;
1444 
1445     SDValue Move = N->getOperand(1);
1446     if (!Move.isMachineOpcode())
1447       continue;
1448 
1449     // Make sure its one of the move opcodes we recognize.
1450     switch (Move.getMachineOpcode()) {
1451     default:
1452       continue;
1453     case X86::VMOVAPDrr:       case X86::VMOVUPDrr:
1454     case X86::VMOVAPSrr:       case X86::VMOVUPSrr:
1455     case X86::VMOVDQArr:       case X86::VMOVDQUrr:
1456     case X86::VMOVAPDYrr:      case X86::VMOVUPDYrr:
1457     case X86::VMOVAPSYrr:      case X86::VMOVUPSYrr:
1458     case X86::VMOVDQAYrr:      case X86::VMOVDQUYrr:
1459     case X86::VMOVAPDZ128rr:   case X86::VMOVUPDZ128rr:
1460     case X86::VMOVAPSZ128rr:   case X86::VMOVUPSZ128rr:
1461     case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
1462     case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
1463     case X86::VMOVAPDZ256rr:   case X86::VMOVUPDZ256rr:
1464     case X86::VMOVAPSZ256rr:   case X86::VMOVUPSZ256rr:
1465     case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
1466     case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
1467       break;
1468     }
1469 
1470     SDValue In = Move.getOperand(0);
1471     if (!In.isMachineOpcode() ||
1472         In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
1473       continue;
1474 
1475     // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
1476     // the SHA instructions which use a legacy encoding.
1477     uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
1478     if ((TSFlags & X86II::EncodingMask) != X86II::VEX &&
1479         (TSFlags & X86II::EncodingMask) != X86II::EVEX &&
1480         (TSFlags & X86II::EncodingMask) != X86II::XOP)
1481       continue;
1482 
1483     // Producing instruction is another vector instruction. We can drop the
1484     // move.
1485     CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
1486     MadeChange = true;
1487   }
1488 
1489   if (MadeChange)
1490     CurDAG->RemoveDeadNodes();
1491 }
1492 
1493 
1494 /// Emit any code that needs to be executed only in the main function.
1495 void X86DAGToDAGISel::emitSpecialCodeForMain() {
1496   if (Subtarget->isTargetCygMing()) {
1497     TargetLowering::ArgListTy Args;
1498     auto &DL = CurDAG->getDataLayout();
1499 
1500     TargetLowering::CallLoweringInfo CLI(*CurDAG);
1501     CLI.setChain(CurDAG->getRoot())
1502         .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
1503                    CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
1504                    std::move(Args));
1505     const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
1506     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
1507     CurDAG->setRoot(Result.second);
1508   }
1509 }
1510 
1511 void X86DAGToDAGISel::emitFunctionEntryCode() {
1512   // If this is main, emit special code for main.
1513   const Function &F = MF->getFunction();
1514   if (F.hasExternalLinkage() && F.getName() == "main")
1515     emitSpecialCodeForMain();
1516 }
1517 
1518 static bool isDispSafeForFrameIndex(int64_t Val) {
1519   // On 64-bit platforms, we can run into an issue where a frame index
1520   // includes a displacement that, when added to the explicit displacement,
1521   // will overflow the displacement field. Assuming that the frame index
1522   // displacement fits into a 31-bit integer  (which is only slightly more
1523   // aggressive than the current fundamental assumption that it fits into
1524   // a 32-bit integer), a 31-bit disp should always be safe.
1525   return isInt<31>(Val);
1526 }
1527 
1528 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
1529                                             X86ISelAddressMode &AM) {
1530   // We may have already matched a displacement and the caller just added the
1531   // symbolic displacement. So we still need to do the checks even if Offset
1532   // is zero.
1533 
1534   int64_t Val = AM.Disp + Offset;
1535 
1536   // Cannot combine ExternalSymbol displacements with integer offsets.
1537   if (Val != 0 && (AM.ES || AM.MCSym))
1538     return true;
1539 
1540   CodeModel::Model M = TM.getCodeModel();
1541   if (Subtarget->is64Bit()) {
1542     if (Val != 0 &&
1543         !X86::isOffsetSuitableForCodeModel(Val, M,
1544                                            AM.hasSymbolicDisplacement()))
1545       return true;
1546     // In addition to the checks required for a register base, check that
1547     // we do not try to use an unsafe Disp with a frame index.
1548     if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
1549         !isDispSafeForFrameIndex(Val))
1550       return true;
1551   }
1552   AM.Disp = Val;
1553   return false;
1554 
1555 }
1556 
1557 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM){
1558   SDValue Address = N->getOperand(1);
1559 
1560   // load gs:0 -> GS segment register.
1561   // load fs:0 -> FS segment register.
1562   //
1563   // This optimization is valid because the GNU TLS model defines that
1564   // gs:0 (or fs:0 on X86-64) contains its own address.
1565   // For more information see http://people.redhat.com/drepper/tls.pdf
1566   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Address))
1567     if (C->getSExtValue() == 0 && AM.Segment.getNode() == nullptr &&
1568         !IndirectTlsSegRefs &&
1569         (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
1570          Subtarget->isTargetFuchsia()))
1571       switch (N->getPointerInfo().getAddrSpace()) {
1572       case 256:
1573         AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1574         return false;
1575       case 257:
1576         AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1577         return false;
1578       // Address space 258 is not handled here, because it is not used to
1579       // address TLS areas.
1580       }
1581 
1582   return true;
1583 }
1584 
1585 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
1586 /// mode. These wrap things that will resolve down into a symbol reference.
1587 /// If no match is possible, this returns true, otherwise it returns false.
1588 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
1589   // If the addressing mode already has a symbol as the displacement, we can
1590   // never match another symbol.
1591   if (AM.hasSymbolicDisplacement())
1592     return true;
1593 
1594   bool IsRIPRelTLS = false;
1595   bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
1596   if (IsRIPRel) {
1597     SDValue Val = N.getOperand(0);
1598     if (Val.getOpcode() == ISD::TargetGlobalTLSAddress)
1599       IsRIPRelTLS = true;
1600   }
1601 
1602   // We can't use an addressing mode in the 64-bit large code model.
1603   // Global TLS addressing is an exception. In the medium code model,
1604   // we use can use a mode when RIP wrappers are present.
1605   // That signifies access to globals that are known to be "near",
1606   // such as the GOT itself.
1607   CodeModel::Model M = TM.getCodeModel();
1608   if (Subtarget->is64Bit() &&
1609       ((M == CodeModel::Large && !IsRIPRelTLS) ||
1610        (M == CodeModel::Medium && !IsRIPRel)))
1611     return true;
1612 
1613   // Base and index reg must be 0 in order to use %rip as base.
1614   if (IsRIPRel && AM.hasBaseOrIndexReg())
1615     return true;
1616 
1617   // Make a local copy in case we can't do this fold.
1618   X86ISelAddressMode Backup = AM;
1619 
1620   int64_t Offset = 0;
1621   SDValue N0 = N.getOperand(0);
1622   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1623     AM.GV = G->getGlobal();
1624     AM.SymbolFlags = G->getTargetFlags();
1625     Offset = G->getOffset();
1626   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1627     AM.CP = CP->getConstVal();
1628     AM.Align = CP->getAlignment();
1629     AM.SymbolFlags = CP->getTargetFlags();
1630     Offset = CP->getOffset();
1631   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1632     AM.ES = S->getSymbol();
1633     AM.SymbolFlags = S->getTargetFlags();
1634   } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1635     AM.MCSym = S->getMCSymbol();
1636   } else if (JumpTableSDNode *J = dyn_cast<JumpTableSDNode>(N0)) {
1637     AM.JT = J->getIndex();
1638     AM.SymbolFlags = J->getTargetFlags();
1639   } else if (BlockAddressSDNode *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1640     AM.BlockAddr = BA->getBlockAddress();
1641     AM.SymbolFlags = BA->getTargetFlags();
1642     Offset = BA->getOffset();
1643   } else
1644     llvm_unreachable("Unhandled symbol reference node.");
1645 
1646   if (foldOffsetIntoAddress(Offset, AM)) {
1647     AM = Backup;
1648     return true;
1649   }
1650 
1651   if (IsRIPRel)
1652     AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
1653 
1654   // Commit the changes now that we know this fold is safe.
1655   return false;
1656 }
1657 
1658 /// Add the specified node to the specified addressing mode, returning true if
1659 /// it cannot be done. This just pattern matches for the addressing mode.
1660 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1661   if (matchAddressRecursively(N, AM, 0))
1662     return true;
1663 
1664   // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1665   // a smaller encoding and avoids a scaled-index.
1666   if (AM.Scale == 2 &&
1667       AM.BaseType == X86ISelAddressMode::RegBase &&
1668       AM.Base_Reg.getNode() == nullptr) {
1669     AM.Base_Reg = AM.IndexReg;
1670     AM.Scale = 1;
1671   }
1672 
1673   // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1674   // because it has a smaller encoding.
1675   // TODO: Which other code models can use this?
1676   switch (TM.getCodeModel()) {
1677     default: break;
1678     case CodeModel::Small:
1679     case CodeModel::Kernel:
1680       if (Subtarget->is64Bit() &&
1681           AM.Scale == 1 &&
1682           AM.BaseType == X86ISelAddressMode::RegBase &&
1683           AM.Base_Reg.getNode() == nullptr &&
1684           AM.IndexReg.getNode() == nullptr &&
1685           AM.SymbolFlags == X86II::MO_NO_FLAG &&
1686           AM.hasSymbolicDisplacement())
1687         AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
1688       break;
1689   }
1690 
1691   return false;
1692 }
1693 
1694 bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM,
1695                                unsigned Depth) {
1696   // Add an artificial use to this node so that we can keep track of
1697   // it if it gets CSE'd with a different node.
1698   HandleSDNode Handle(N);
1699 
1700   X86ISelAddressMode Backup = AM;
1701   if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1702       !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1703     return false;
1704   AM = Backup;
1705 
1706   // Try again after commutating the operands.
1707   if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM,
1708                                Depth + 1) &&
1709       !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth + 1))
1710     return false;
1711   AM = Backup;
1712 
1713   // If we couldn't fold both operands into the address at the same time,
1714   // see if we can just put each operand into a register and fold at least
1715   // the add.
1716   if (AM.BaseType == X86ISelAddressMode::RegBase &&
1717       !AM.Base_Reg.getNode() &&
1718       !AM.IndexReg.getNode()) {
1719     N = Handle.getValue();
1720     AM.Base_Reg = N.getOperand(0);
1721     AM.IndexReg = N.getOperand(1);
1722     AM.Scale = 1;
1723     return false;
1724   }
1725   N = Handle.getValue();
1726   return true;
1727 }
1728 
1729 // Insert a node into the DAG at least before the Pos node's position. This
1730 // will reposition the node as needed, and will assign it a node ID that is <=
1731 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1732 // IDs! The selection DAG must no longer depend on their uniqueness when this
1733 // is used.
1734 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
1735   if (N->getNodeId() == -1 ||
1736       (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) >
1737        SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) {
1738     DAG.RepositionNode(Pos->getIterator(), N.getNode());
1739     // Mark Node as invalid for pruning as after this it may be a successor to a
1740     // selected node but otherwise be in the same position of Pos.
1741     // Conservatively mark it with the same -abs(Id) to assure node id
1742     // invariant is preserved.
1743     N->setNodeId(Pos->getNodeId());
1744     SelectionDAGISel::InvalidateNodeId(N.getNode());
1745   }
1746 }
1747 
1748 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1749 // safe. This allows us to convert the shift and and into an h-register
1750 // extract and a scaled index. Returns false if the simplification is
1751 // performed.
1752 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N,
1753                                       uint64_t Mask,
1754                                       SDValue Shift, SDValue X,
1755                                       X86ISelAddressMode &AM) {
1756   if (Shift.getOpcode() != ISD::SRL ||
1757       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1758       !Shift.hasOneUse())
1759     return true;
1760 
1761   int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1762   if (ScaleLog <= 0 || ScaleLog >= 4 ||
1763       Mask != (0xffu << ScaleLog))
1764     return true;
1765 
1766   MVT VT = N.getSimpleValueType();
1767   SDLoc DL(N);
1768   SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1769   SDValue NewMask = DAG.getConstant(0xff, DL, VT);
1770   SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1771   SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
1772   SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
1773   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1774 
1775   // Insert the new nodes into the topological ordering. We must do this in
1776   // a valid topological ordering as nothing is going to go back and re-sort
1777   // these nodes. We continually insert before 'N' in sequence as this is
1778   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1779   // hierarchy left to express.
1780   insertDAGNode(DAG, N, Eight);
1781   insertDAGNode(DAG, N, Srl);
1782   insertDAGNode(DAG, N, NewMask);
1783   insertDAGNode(DAG, N, And);
1784   insertDAGNode(DAG, N, ShlCount);
1785   insertDAGNode(DAG, N, Shl);
1786   DAG.ReplaceAllUsesWith(N, Shl);
1787   DAG.RemoveDeadNode(N.getNode());
1788   AM.IndexReg = And;
1789   AM.Scale = (1 << ScaleLog);
1790   return false;
1791 }
1792 
1793 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1794 // allows us to fold the shift into this addressing mode. Returns false if the
1795 // transform succeeded.
1796 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N,
1797                                         X86ISelAddressMode &AM) {
1798   SDValue Shift = N.getOperand(0);
1799 
1800   // Use a signed mask so that shifting right will insert sign bits. These
1801   // bits will be removed when we shift the result left so it doesn't matter
1802   // what we use. This might allow a smaller immediate encoding.
1803   int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue();
1804 
1805   // If we have an any_extend feeding the AND, look through it to see if there
1806   // is a shift behind it. But only if the AND doesn't use the extended bits.
1807   // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
1808   bool FoundAnyExtend = false;
1809   if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
1810       Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
1811       isUInt<32>(Mask)) {
1812     FoundAnyExtend = true;
1813     Shift = Shift.getOperand(0);
1814   }
1815 
1816   if (Shift.getOpcode() != ISD::SHL ||
1817       !isa<ConstantSDNode>(Shift.getOperand(1)))
1818     return true;
1819 
1820   SDValue X = Shift.getOperand(0);
1821 
1822   // Not likely to be profitable if either the AND or SHIFT node has more
1823   // than one use (unless all uses are for address computation). Besides,
1824   // isel mechanism requires their node ids to be reused.
1825   if (!N.hasOneUse() || !Shift.hasOneUse())
1826     return true;
1827 
1828   // Verify that the shift amount is something we can fold.
1829   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1830   if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
1831     return true;
1832 
1833   MVT VT = N.getSimpleValueType();
1834   SDLoc DL(N);
1835   if (FoundAnyExtend) {
1836     SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
1837     insertDAGNode(DAG, N, NewX);
1838     X = NewX;
1839   }
1840 
1841   SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
1842   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
1843   SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
1844 
1845   // Insert the new nodes into the topological ordering. We must do this in
1846   // a valid topological ordering as nothing is going to go back and re-sort
1847   // these nodes. We continually insert before 'N' in sequence as this is
1848   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1849   // hierarchy left to express.
1850   insertDAGNode(DAG, N, NewMask);
1851   insertDAGNode(DAG, N, NewAnd);
1852   insertDAGNode(DAG, N, NewShift);
1853   DAG.ReplaceAllUsesWith(N, NewShift);
1854   DAG.RemoveDeadNode(N.getNode());
1855 
1856   AM.Scale = 1 << ShiftAmt;
1857   AM.IndexReg = NewAnd;
1858   return false;
1859 }
1860 
1861 // Implement some heroics to detect shifts of masked values where the mask can
1862 // be replaced by extending the shift and undoing that in the addressing mode
1863 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
1864 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
1865 // the addressing mode. This results in code such as:
1866 //
1867 //   int f(short *y, int *lookup_table) {
1868 //     ...
1869 //     return *y + lookup_table[*y >> 11];
1870 //   }
1871 //
1872 // Turning into:
1873 //   movzwl (%rdi), %eax
1874 //   movl %eax, %ecx
1875 //   shrl $11, %ecx
1876 //   addl (%rsi,%rcx,4), %eax
1877 //
1878 // Instead of:
1879 //   movzwl (%rdi), %eax
1880 //   movl %eax, %ecx
1881 //   shrl $9, %ecx
1882 //   andl $124, %rcx
1883 //   addl (%rsi,%rcx), %eax
1884 //
1885 // Note that this function assumes the mask is provided as a mask *after* the
1886 // value is shifted. The input chain may or may not match that, but computing
1887 // such a mask is trivial.
1888 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N,
1889                                     uint64_t Mask,
1890                                     SDValue Shift, SDValue X,
1891                                     X86ISelAddressMode &AM) {
1892   if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
1893       !isa<ConstantSDNode>(Shift.getOperand(1)))
1894     return true;
1895 
1896   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1897   unsigned MaskLZ = countLeadingZeros(Mask);
1898   unsigned MaskTZ = countTrailingZeros(Mask);
1899 
1900   // The amount of shift we're trying to fit into the addressing mode is taken
1901   // from the trailing zeros of the mask.
1902   unsigned AMShiftAmt = MaskTZ;
1903 
1904   // There is nothing we can do here unless the mask is removing some bits.
1905   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
1906   if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
1907 
1908   // We also need to ensure that mask is a continuous run of bits.
1909   if (countTrailingOnes(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64) return true;
1910 
1911   // Scale the leading zero count down based on the actual size of the value.
1912   // Also scale it down based on the size of the shift.
1913   unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
1914   if (MaskLZ < ScaleDown)
1915     return true;
1916   MaskLZ -= ScaleDown;
1917 
1918   // The final check is to ensure that any masked out high bits of X are
1919   // already known to be zero. Otherwise, the mask has a semantic impact
1920   // other than masking out a couple of low bits. Unfortunately, because of
1921   // the mask, zero extensions will be removed from operands in some cases.
1922   // This code works extra hard to look through extensions because we can
1923   // replace them with zero extensions cheaply if necessary.
1924   bool ReplacingAnyExtend = false;
1925   if (X.getOpcode() == ISD::ANY_EXTEND) {
1926     unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
1927                           X.getOperand(0).getSimpleValueType().getSizeInBits();
1928     // Assume that we'll replace the any-extend with a zero-extend, and
1929     // narrow the search to the extended value.
1930     X = X.getOperand(0);
1931     MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
1932     ReplacingAnyExtend = true;
1933   }
1934   APInt MaskedHighBits =
1935     APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
1936   KnownBits Known = DAG.computeKnownBits(X);
1937   if (MaskedHighBits != Known.Zero) return true;
1938 
1939   // We've identified a pattern that can be transformed into a single shift
1940   // and an addressing mode. Make it so.
1941   MVT VT = N.getSimpleValueType();
1942   if (ReplacingAnyExtend) {
1943     assert(X.getValueType() != VT);
1944     // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
1945     SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
1946     insertDAGNode(DAG, N, NewX);
1947     X = NewX;
1948   }
1949   SDLoc DL(N);
1950   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
1951   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
1952   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
1953   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
1954 
1955   // Insert the new nodes into the topological ordering. We must do this in
1956   // a valid topological ordering as nothing is going to go back and re-sort
1957   // these nodes. We continually insert before 'N' in sequence as this is
1958   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1959   // hierarchy left to express.
1960   insertDAGNode(DAG, N, NewSRLAmt);
1961   insertDAGNode(DAG, N, NewSRL);
1962   insertDAGNode(DAG, N, NewSHLAmt);
1963   insertDAGNode(DAG, N, NewSHL);
1964   DAG.ReplaceAllUsesWith(N, NewSHL);
1965   DAG.RemoveDeadNode(N.getNode());
1966 
1967   AM.Scale = 1 << AMShiftAmt;
1968   AM.IndexReg = NewSRL;
1969   return false;
1970 }
1971 
1972 // Transform "(X >> SHIFT) & (MASK << C1)" to
1973 // "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be
1974 // matched to a BEXTR later. Returns false if the simplification is performed.
1975 static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N,
1976                                    uint64_t Mask,
1977                                    SDValue Shift, SDValue X,
1978                                    X86ISelAddressMode &AM,
1979                                    const X86Subtarget &Subtarget) {
1980   if (Shift.getOpcode() != ISD::SRL ||
1981       !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1982       !Shift.hasOneUse() || !N.hasOneUse())
1983     return true;
1984 
1985   // Only do this if BEXTR will be matched by matchBEXTRFromAndImm.
1986   if (!Subtarget.hasTBM() &&
1987       !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))
1988     return true;
1989 
1990   // We need to ensure that mask is a continuous run of bits.
1991   if (!isShiftedMask_64(Mask)) return true;
1992 
1993   unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1994 
1995   // The amount of shift we're trying to fit into the addressing mode is taken
1996   // from the trailing zeros of the mask.
1997   unsigned AMShiftAmt = countTrailingZeros(Mask);
1998 
1999   // There is nothing we can do here unless the mask is removing some bits.
2000   // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
2001   if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
2002 
2003   MVT VT = N.getSimpleValueType();
2004   SDLoc DL(N);
2005   SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
2006   SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
2007   SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, VT);
2008   SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, NewSRL, NewMask);
2009   SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
2010   SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewAnd, NewSHLAmt);
2011 
2012   // Insert the new nodes into the topological ordering. We must do this in
2013   // a valid topological ordering as nothing is going to go back and re-sort
2014   // these nodes. We continually insert before 'N' in sequence as this is
2015   // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2016   // hierarchy left to express.
2017   insertDAGNode(DAG, N, NewSRLAmt);
2018   insertDAGNode(DAG, N, NewSRL);
2019   insertDAGNode(DAG, N, NewMask);
2020   insertDAGNode(DAG, N, NewAnd);
2021   insertDAGNode(DAG, N, NewSHLAmt);
2022   insertDAGNode(DAG, N, NewSHL);
2023   DAG.ReplaceAllUsesWith(N, NewSHL);
2024   DAG.RemoveDeadNode(N.getNode());
2025 
2026   AM.Scale = 1 << AMShiftAmt;
2027   AM.IndexReg = NewAnd;
2028   return false;
2029 }
2030 
2031 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
2032                                               unsigned Depth) {
2033   SDLoc dl(N);
2034   LLVM_DEBUG({
2035     dbgs() << "MatchAddress: ";
2036     AM.dump(CurDAG);
2037   });
2038   // Limit recursion.
2039   if (Depth > 5)
2040     return matchAddressBase(N, AM);
2041 
2042   // If this is already a %rip relative address, we can only merge immediates
2043   // into it.  Instead of handling this in every case, we handle it here.
2044   // RIP relative addressing: %rip + 32-bit displacement!
2045   if (AM.isRIPRelative()) {
2046     // FIXME: JumpTable and ExternalSymbol address currently don't like
2047     // displacements.  It isn't very important, but this should be fixed for
2048     // consistency.
2049     if (!(AM.ES || AM.MCSym) && AM.JT != -1)
2050       return true;
2051 
2052     if (ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N))
2053       if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
2054         return false;
2055     return true;
2056   }
2057 
2058   switch (N.getOpcode()) {
2059   default: break;
2060   case ISD::LOCAL_RECOVER: {
2061     if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
2062       if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
2063         // Use the symbol and don't prefix it.
2064         AM.MCSym = ESNode->getMCSymbol();
2065         return false;
2066       }
2067     break;
2068   }
2069   case ISD::Constant: {
2070     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
2071     if (!foldOffsetIntoAddress(Val, AM))
2072       return false;
2073     break;
2074   }
2075 
2076   case X86ISD::Wrapper:
2077   case X86ISD::WrapperRIP:
2078     if (!matchWrapper(N, AM))
2079       return false;
2080     break;
2081 
2082   case ISD::LOAD:
2083     if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
2084       return false;
2085     break;
2086 
2087   case ISD::FrameIndex:
2088     if (AM.BaseType == X86ISelAddressMode::RegBase &&
2089         AM.Base_Reg.getNode() == nullptr &&
2090         (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
2091       AM.BaseType = X86ISelAddressMode::FrameIndexBase;
2092       AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
2093       return false;
2094     }
2095     break;
2096 
2097   case ISD::SHL:
2098     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
2099       break;
2100 
2101     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2102       unsigned Val = CN->getZExtValue();
2103       // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
2104       // that the base operand remains free for further matching. If
2105       // the base doesn't end up getting used, a post-processing step
2106       // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
2107       if (Val == 1 || Val == 2 || Val == 3) {
2108         AM.Scale = 1 << Val;
2109         SDValue ShVal = N.getOperand(0);
2110 
2111         // Okay, we know that we have a scale by now.  However, if the scaled
2112         // value is an add of something and a constant, we can fold the
2113         // constant into the disp field here.
2114         if (CurDAG->isBaseWithConstantOffset(ShVal)) {
2115           AM.IndexReg = ShVal.getOperand(0);
2116           ConstantSDNode *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
2117           uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
2118           if (!foldOffsetIntoAddress(Disp, AM))
2119             return false;
2120         }
2121 
2122         AM.IndexReg = ShVal;
2123         return false;
2124       }
2125     }
2126     break;
2127 
2128   case ISD::SRL: {
2129     // Scale must not be used already.
2130     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
2131 
2132     // We only handle up to 64-bit values here as those are what matter for
2133     // addressing mode optimizations.
2134     assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
2135            "Unexpected value size!");
2136 
2137     SDValue And = N.getOperand(0);
2138     if (And.getOpcode() != ISD::AND) break;
2139     SDValue X = And.getOperand(0);
2140 
2141     // The mask used for the transform is expected to be post-shift, but we
2142     // found the shift first so just apply the shift to the mask before passing
2143     // it down.
2144     if (!isa<ConstantSDNode>(N.getOperand(1)) ||
2145         !isa<ConstantSDNode>(And.getOperand(1)))
2146       break;
2147     uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
2148 
2149     // Try to fold the mask and shift into the scale, and return false if we
2150     // succeed.
2151     if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
2152       return false;
2153     break;
2154   }
2155 
2156   case ISD::SMUL_LOHI:
2157   case ISD::UMUL_LOHI:
2158     // A mul_lohi where we need the low part can be folded as a plain multiply.
2159     if (N.getResNo() != 0) break;
2160     LLVM_FALLTHROUGH;
2161   case ISD::MUL:
2162   case X86ISD::MUL_IMM:
2163     // X*[3,5,9] -> X+X*[2,4,8]
2164     if (AM.BaseType == X86ISelAddressMode::RegBase &&
2165         AM.Base_Reg.getNode() == nullptr &&
2166         AM.IndexReg.getNode() == nullptr) {
2167       if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
2168         if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
2169             CN->getZExtValue() == 9) {
2170           AM.Scale = unsigned(CN->getZExtValue())-1;
2171 
2172           SDValue MulVal = N.getOperand(0);
2173           SDValue Reg;
2174 
2175           // Okay, we know that we have a scale by now.  However, if the scaled
2176           // value is an add of something and a constant, we can fold the
2177           // constant into the disp field here.
2178           if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
2179               isa<ConstantSDNode>(MulVal.getOperand(1))) {
2180             Reg = MulVal.getOperand(0);
2181             ConstantSDNode *AddVal =
2182               cast<ConstantSDNode>(MulVal.getOperand(1));
2183             uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
2184             if (foldOffsetIntoAddress(Disp, AM))
2185               Reg = N.getOperand(0);
2186           } else {
2187             Reg = N.getOperand(0);
2188           }
2189 
2190           AM.IndexReg = AM.Base_Reg = Reg;
2191           return false;
2192         }
2193     }
2194     break;
2195 
2196   case ISD::SUB: {
2197     // Given A-B, if A can be completely folded into the address and
2198     // the index field with the index field unused, use -B as the index.
2199     // This is a win if a has multiple parts that can be folded into
2200     // the address. Also, this saves a mov if the base register has
2201     // other uses, since it avoids a two-address sub instruction, however
2202     // it costs an additional mov if the index register has other uses.
2203 
2204     // Add an artificial use to this node so that we can keep track of
2205     // it if it gets CSE'd with a different node.
2206     HandleSDNode Handle(N);
2207 
2208     // Test if the LHS of the sub can be folded.
2209     X86ISelAddressMode Backup = AM;
2210     if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
2211       N = Handle.getValue();
2212       AM = Backup;
2213       break;
2214     }
2215     N = Handle.getValue();
2216     // Test if the index field is free for use.
2217     if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
2218       AM = Backup;
2219       break;
2220     }
2221 
2222     int Cost = 0;
2223     SDValue RHS = N.getOperand(1);
2224     // If the RHS involves a register with multiple uses, this
2225     // transformation incurs an extra mov, due to the neg instruction
2226     // clobbering its operand.
2227     if (!RHS.getNode()->hasOneUse() ||
2228         RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
2229         RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
2230         RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
2231         (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
2232          RHS.getOperand(0).getValueType() == MVT::i32))
2233       ++Cost;
2234     // If the base is a register with multiple uses, this
2235     // transformation may save a mov.
2236     if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
2237          !AM.Base_Reg.getNode()->hasOneUse()) ||
2238         AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2239       --Cost;
2240     // If the folded LHS was interesting, this transformation saves
2241     // address arithmetic.
2242     if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
2243         ((AM.Disp != 0) && (Backup.Disp == 0)) +
2244         (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
2245       --Cost;
2246     // If it doesn't look like it may be an overall win, don't do it.
2247     if (Cost >= 0) {
2248       AM = Backup;
2249       break;
2250     }
2251 
2252     // Ok, the transformation is legal and appears profitable. Go for it.
2253     // Negation will be emitted later to avoid creating dangling nodes if this
2254     // was an unprofitable LEA.
2255     AM.IndexReg = RHS;
2256     AM.NegateIndex = true;
2257     AM.Scale = 1;
2258     return false;
2259   }
2260 
2261   case ISD::ADD:
2262     if (!matchAdd(N, AM, Depth))
2263       return false;
2264     break;
2265 
2266   case ISD::OR:
2267     // We want to look through a transform in InstCombine and DAGCombiner that
2268     // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
2269     // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
2270     // An 'lea' can then be used to match the shift (multiply) and add:
2271     // and $1, %esi
2272     // lea (%rsi, %rdi, 8), %rax
2273     if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
2274         !matchAdd(N, AM, Depth))
2275       return false;
2276     break;
2277 
2278   case ISD::AND: {
2279     // Perform some heroic transforms on an and of a constant-count shift
2280     // with a constant to enable use of the scaled offset field.
2281 
2282     // Scale must not be used already.
2283     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
2284 
2285     // We only handle up to 64-bit values here as those are what matter for
2286     // addressing mode optimizations.
2287     assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
2288            "Unexpected value size!");
2289 
2290     if (!isa<ConstantSDNode>(N.getOperand(1)))
2291       break;
2292 
2293     if (N.getOperand(0).getOpcode() == ISD::SRL) {
2294       SDValue Shift = N.getOperand(0);
2295       SDValue X = Shift.getOperand(0);
2296 
2297       uint64_t Mask = N.getConstantOperandVal(1);
2298 
2299       // Try to fold the mask and shift into an extract and scale.
2300       if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
2301         return false;
2302 
2303       // Try to fold the mask and shift directly into the scale.
2304       if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
2305         return false;
2306 
2307       // Try to fold the mask and shift into BEXTR and scale.
2308       if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))
2309         return false;
2310     }
2311 
2312     // Try to swap the mask and shift to place shifts which can be done as
2313     // a scale on the outside of the mask.
2314     if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM))
2315       return false;
2316 
2317     break;
2318   }
2319   case ISD::ZERO_EXTEND: {
2320     // Try to widen a zexted shift left to the same size as its use, so we can
2321     // match the shift as a scale factor.
2322     if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
2323       break;
2324     if (N.getOperand(0).getOpcode() != ISD::SHL || !N.getOperand(0).hasOneUse())
2325       break;
2326 
2327     // Give up if the shift is not a valid scale factor [1,2,3].
2328     SDValue Shl = N.getOperand(0);
2329     auto *ShAmtC = dyn_cast<ConstantSDNode>(Shl.getOperand(1));
2330     if (!ShAmtC || ShAmtC->getZExtValue() > 3)
2331       break;
2332 
2333     // The narrow shift must only shift out zero bits (it must be 'nuw').
2334     // That makes it safe to widen to the destination type.
2335     APInt HighZeros = APInt::getHighBitsSet(Shl.getValueSizeInBits(),
2336                                             ShAmtC->getZExtValue());
2337     if (!CurDAG->MaskedValueIsZero(Shl.getOperand(0), HighZeros))
2338       break;
2339 
2340     // zext (shl nuw i8 %x, C) to i32 --> shl (zext i8 %x to i32), (zext C)
2341     MVT VT = N.getSimpleValueType();
2342     SDLoc DL(N);
2343     SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Shl.getOperand(0));
2344     SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, Shl.getOperand(1));
2345 
2346     // Convert the shift to scale factor.
2347     AM.Scale = 1 << ShAmtC->getZExtValue();
2348     AM.IndexReg = Zext;
2349 
2350     insertDAGNode(*CurDAG, N, Zext);
2351     insertDAGNode(*CurDAG, N, NewShl);
2352     CurDAG->ReplaceAllUsesWith(N, NewShl);
2353     CurDAG->RemoveDeadNode(N.getNode());
2354     return false;
2355   }
2356   }
2357 
2358   return matchAddressBase(N, AM);
2359 }
2360 
2361 /// Helper for MatchAddress. Add the specified node to the
2362 /// specified addressing mode without any further recursion.
2363 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
2364   // Is the base register already occupied?
2365   if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
2366     // If so, check to see if the scale index register is set.
2367     if (!AM.IndexReg.getNode()) {
2368       AM.IndexReg = N;
2369       AM.Scale = 1;
2370       return false;
2371     }
2372 
2373     // Otherwise, we cannot select it.
2374     return true;
2375   }
2376 
2377   // Default, generate it as a register.
2378   AM.BaseType = X86ISelAddressMode::RegBase;
2379   AM.Base_Reg = N;
2380   return false;
2381 }
2382 
2383 /// Helper for selectVectorAddr. Handles things that can be folded into a
2384 /// gather scatter address. The index register and scale should have already
2385 /// been handled.
2386 bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
2387   // TODO: Support other operations.
2388   switch (N.getOpcode()) {
2389   case ISD::Constant: {
2390     uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
2391     if (!foldOffsetIntoAddress(Val, AM))
2392       return false;
2393     break;
2394   }
2395   case X86ISD::Wrapper:
2396     if (!matchWrapper(N, AM))
2397       return false;
2398     break;
2399   }
2400 
2401   return matchAddressBase(N, AM);
2402 }
2403 
2404 bool X86DAGToDAGISel::selectVectorAddr(MemSDNode *Parent, SDValue BasePtr,
2405                                        SDValue IndexOp, SDValue ScaleOp,
2406                                        SDValue &Base, SDValue &Scale,
2407                                        SDValue &Index, SDValue &Disp,
2408                                        SDValue &Segment) {
2409   X86ISelAddressMode AM;
2410   AM.IndexReg = IndexOp;
2411   AM.Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
2412 
2413   unsigned AddrSpace = Parent->getPointerInfo().getAddrSpace();
2414   if (AddrSpace == X86AS::GS)
2415     AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2416   if (AddrSpace == X86AS::FS)
2417     AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2418   if (AddrSpace == X86AS::SS)
2419     AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
2420 
2421   SDLoc DL(BasePtr);
2422   MVT VT = BasePtr.getSimpleValueType();
2423 
2424   // Try to match into the base and displacement fields.
2425   if (matchVectorAddress(BasePtr, AM))
2426     return false;
2427 
2428   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2429   return true;
2430 }
2431 
2432 /// Returns true if it is able to pattern match an addressing mode.
2433 /// It returns the operands which make up the maximal addressing mode it can
2434 /// match by reference.
2435 ///
2436 /// Parent is the parent node of the addr operand that is being matched.  It
2437 /// is always a load, store, atomic node, or null.  It is only null when
2438 /// checking memory operands for inline asm nodes.
2439 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
2440                                  SDValue &Scale, SDValue &Index,
2441                                  SDValue &Disp, SDValue &Segment) {
2442   X86ISelAddressMode AM;
2443 
2444   if (Parent &&
2445       // This list of opcodes are all the nodes that have an "addr:$ptr" operand
2446       // that are not a MemSDNode, and thus don't have proper addrspace info.
2447       Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
2448       Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
2449       Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
2450       Parent->getOpcode() != X86ISD::ENQCMD && // Fixme
2451       Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme
2452       Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
2453       Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
2454     unsigned AddrSpace =
2455       cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
2456     // AddrSpace 256 -> GS, 257 -> FS, 258 -> SS.
2457     if (AddrSpace == 256)
2458       AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2459     if (AddrSpace == 257)
2460       AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2461     if (AddrSpace == 258)
2462       AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
2463   }
2464 
2465   // Save the DL and VT before calling matchAddress, it can invalidate N.
2466   SDLoc DL(N);
2467   MVT VT = N.getSimpleValueType();
2468 
2469   if (matchAddress(N, AM))
2470     return false;
2471 
2472   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2473   return true;
2474 }
2475 
2476 // We can only fold a load if all nodes between it and the root node have a
2477 // single use. If there are additional uses, we could end up duplicating the
2478 // load.
2479 static bool hasSingleUsesFromRoot(SDNode *Root, SDNode *User) {
2480   while (User != Root) {
2481     if (!User->hasOneUse())
2482       return false;
2483     User = *User->use_begin();
2484   }
2485 
2486   return true;
2487 }
2488 
2489 /// Match a scalar SSE load. In particular, we want to match a load whose top
2490 /// elements are either undef or zeros. The load flavor is derived from the
2491 /// type of N, which is either v4f32 or v2f64.
2492 ///
2493 /// We also return:
2494 ///   PatternChainNode: this is the matched node that has a chain input and
2495 ///   output.
2496 bool X86DAGToDAGISel::selectScalarSSELoad(SDNode *Root, SDNode *Parent,
2497                                           SDValue N, SDValue &Base,
2498                                           SDValue &Scale, SDValue &Index,
2499                                           SDValue &Disp, SDValue &Segment,
2500                                           SDValue &PatternNodeWithChain) {
2501   if (!hasSingleUsesFromRoot(Root, Parent))
2502     return false;
2503 
2504   // We can allow a full vector load here since narrowing a load is ok unless
2505   // it's volatile or atomic.
2506   if (ISD::isNON_EXTLoad(N.getNode())) {
2507     LoadSDNode *LD = cast<LoadSDNode>(N);
2508     if (LD->isSimple() &&
2509         IsProfitableToFold(N, LD, Root) &&
2510         IsLegalToFold(N, Parent, Root, OptLevel)) {
2511       PatternNodeWithChain = N;
2512       return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
2513                         Segment);
2514     }
2515   }
2516 
2517   // We can also match the special zero extended load opcode.
2518   if (N.getOpcode() == X86ISD::VZEXT_LOAD) {
2519     PatternNodeWithChain = N;
2520     if (IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
2521         IsLegalToFold(PatternNodeWithChain, Parent, Root, OptLevel)) {
2522       auto *MI = cast<MemIntrinsicSDNode>(PatternNodeWithChain);
2523       return selectAddr(MI, MI->getBasePtr(), Base, Scale, Index, Disp,
2524                         Segment);
2525     }
2526   }
2527 
2528   // Need to make sure that the SCALAR_TO_VECTOR and load are both only used
2529   // once. Otherwise the load might get duplicated and the chain output of the
2530   // duplicate load will not be observed by all dependencies.
2531   if (N.getOpcode() == ISD::SCALAR_TO_VECTOR && N.getNode()->hasOneUse()) {
2532     PatternNodeWithChain = N.getOperand(0);
2533     if (ISD::isNON_EXTLoad(PatternNodeWithChain.getNode()) &&
2534         IsProfitableToFold(PatternNodeWithChain, N.getNode(), Root) &&
2535         IsLegalToFold(PatternNodeWithChain, N.getNode(), Root, OptLevel)) {
2536       LoadSDNode *LD = cast<LoadSDNode>(PatternNodeWithChain);
2537       return selectAddr(LD, LD->getBasePtr(), Base, Scale, Index, Disp,
2538                         Segment);
2539     }
2540   }
2541 
2542   return false;
2543 }
2544 
2545 
2546 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
2547   if (const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2548     uint64_t ImmVal = CN->getZExtValue();
2549     if (!isUInt<32>(ImmVal))
2550       return false;
2551 
2552     Imm = CurDAG->getTargetConstant(ImmVal, SDLoc(N), MVT::i64);
2553     return true;
2554   }
2555 
2556   // In static codegen with small code model, we can get the address of a label
2557   // into a register with 'movl'
2558   if (N->getOpcode() != X86ISD::Wrapper)
2559     return false;
2560 
2561   N = N.getOperand(0);
2562 
2563   // At least GNU as does not accept 'movl' for TPOFF relocations.
2564   // FIXME: We could use 'movl' when we know we are targeting MC.
2565   if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
2566     return false;
2567 
2568   Imm = N;
2569   if (N->getOpcode() != ISD::TargetGlobalAddress)
2570     return TM.getCodeModel() == CodeModel::Small;
2571 
2572   Optional<ConstantRange> CR =
2573       cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
2574   if (!CR)
2575     return TM.getCodeModel() == CodeModel::Small;
2576 
2577   return CR->getUnsignedMax().ult(1ull << 32);
2578 }
2579 
2580 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
2581                                          SDValue &Scale, SDValue &Index,
2582                                          SDValue &Disp, SDValue &Segment) {
2583   // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
2584   SDLoc DL(N);
2585 
2586   if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
2587     return false;
2588 
2589   RegisterSDNode *RN = dyn_cast<RegisterSDNode>(Base);
2590   if (RN && RN->getReg() == 0)
2591     Base = CurDAG->getRegister(0, MVT::i64);
2592   else if (Base.getValueType() == MVT::i32 && !isa<FrameIndexSDNode>(Base)) {
2593     // Base could already be %rip, particularly in the x32 ABI.
2594     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
2595                                                      MVT::i64), 0);
2596     Base = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
2597                                          Base);
2598   }
2599 
2600   RN = dyn_cast<RegisterSDNode>(Index);
2601   if (RN && RN->getReg() == 0)
2602     Index = CurDAG->getRegister(0, MVT::i64);
2603   else {
2604     assert(Index.getValueType() == MVT::i32 &&
2605            "Expect to be extending 32-bit registers for use in LEA");
2606     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
2607                                                      MVT::i64), 0);
2608     Index = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
2609                                           Index);
2610   }
2611 
2612   return true;
2613 }
2614 
2615 /// Calls SelectAddr and determines if the maximal addressing
2616 /// mode it matches can be cost effectively emitted as an LEA instruction.
2617 bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
2618                                     SDValue &Base, SDValue &Scale,
2619                                     SDValue &Index, SDValue &Disp,
2620                                     SDValue &Segment) {
2621   X86ISelAddressMode AM;
2622 
2623   // Save the DL and VT before calling matchAddress, it can invalidate N.
2624   SDLoc DL(N);
2625   MVT VT = N.getSimpleValueType();
2626 
2627   // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
2628   // segments.
2629   SDValue Copy = AM.Segment;
2630   SDValue T = CurDAG->getRegister(0, MVT::i32);
2631   AM.Segment = T;
2632   if (matchAddress(N, AM))
2633     return false;
2634   assert (T == AM.Segment);
2635   AM.Segment = Copy;
2636 
2637   unsigned Complexity = 0;
2638   if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode())
2639     Complexity = 1;
2640   else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2641     Complexity = 4;
2642 
2643   if (AM.IndexReg.getNode())
2644     Complexity++;
2645 
2646   // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
2647   // a simple shift.
2648   if (AM.Scale > 1)
2649     Complexity++;
2650 
2651   // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
2652   // to a LEA. This is determined with some experimentation but is by no means
2653   // optimal (especially for code size consideration). LEA is nice because of
2654   // its three-address nature. Tweak the cost function again when we can run
2655   // convertToThreeAddress() at register allocation time.
2656   if (AM.hasSymbolicDisplacement()) {
2657     // For X86-64, always use LEA to materialize RIP-relative addresses.
2658     if (Subtarget->is64Bit())
2659       Complexity = 4;
2660     else
2661       Complexity += 2;
2662   }
2663 
2664   // Heuristic: try harder to form an LEA from ADD if the operands set flags.
2665   // Unlike ADD, LEA does not affect flags, so we will be less likely to require
2666   // duplicating flag-producing instructions later in the pipeline.
2667   if (N.getOpcode() == ISD::ADD) {
2668     auto isMathWithFlags = [](SDValue V) {
2669       switch (V.getOpcode()) {
2670       case X86ISD::ADD:
2671       case X86ISD::SUB:
2672       case X86ISD::ADC:
2673       case X86ISD::SBB:
2674       /* TODO: These opcodes can be added safely, but we may want to justify
2675                their inclusion for different reasons (better for reg-alloc).
2676       case X86ISD::SMUL:
2677       case X86ISD::UMUL:
2678       case X86ISD::OR:
2679       case X86ISD::XOR:
2680       case X86ISD::AND:
2681       */
2682         // Value 1 is the flag output of the node - verify it's not dead.
2683         return !SDValue(V.getNode(), 1).use_empty();
2684       default:
2685         return false;
2686       }
2687     };
2688     // TODO: This could be an 'or' rather than 'and' to make the transform more
2689     //       likely to happen. We might want to factor in whether there's a
2690     //       load folding opportunity for the math op that disappears with LEA.
2691     if (isMathWithFlags(N.getOperand(0)) && isMathWithFlags(N.getOperand(1)))
2692       Complexity++;
2693   }
2694 
2695   if (AM.Disp)
2696     Complexity++;
2697 
2698   // If it isn't worth using an LEA, reject it.
2699   if (Complexity <= 2)
2700     return false;
2701 
2702   getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2703   return true;
2704 }
2705 
2706 /// This is only run on TargetGlobalTLSAddress nodes.
2707 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
2708                                         SDValue &Scale, SDValue &Index,
2709                                         SDValue &Disp, SDValue &Segment) {
2710   assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
2711   const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
2712 
2713   X86ISelAddressMode AM;
2714   AM.GV = GA->getGlobal();
2715   AM.Disp += GA->getOffset();
2716   AM.SymbolFlags = GA->getTargetFlags();
2717 
2718   MVT VT = N.getSimpleValueType();
2719   if (VT == MVT::i32) {
2720     AM.Scale = 1;
2721     AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
2722   }
2723 
2724   getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment);
2725   return true;
2726 }
2727 
2728 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
2729   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2730     Op = CurDAG->getTargetConstant(CN->getAPIntValue(), SDLoc(CN),
2731                                    N.getValueType());
2732     return true;
2733   }
2734 
2735   // Keep track of the original value type and whether this value was
2736   // truncated. If we see a truncation from pointer type to VT that truncates
2737   // bits that are known to be zero, we can use a narrow reference.
2738   EVT VT = N.getValueType();
2739   bool WasTruncated = false;
2740   if (N.getOpcode() == ISD::TRUNCATE) {
2741     WasTruncated = true;
2742     N = N.getOperand(0);
2743   }
2744 
2745   if (N.getOpcode() != X86ISD::Wrapper)
2746     return false;
2747 
2748   // We can only use non-GlobalValues as immediates if they were not truncated,
2749   // as we do not have any range information. If we have a GlobalValue and the
2750   // address was not truncated, we can select it as an operand directly.
2751   unsigned Opc = N.getOperand(0)->getOpcode();
2752   if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
2753     Op = N.getOperand(0);
2754     // We can only select the operand directly if we didn't have to look past a
2755     // truncate.
2756     return !WasTruncated;
2757   }
2758 
2759   // Check that the global's range fits into VT.
2760   auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
2761   Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2762   if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2763     return false;
2764 
2765   // Okay, we can use a narrow reference.
2766   Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2767                                       GA->getOffset(), GA->getTargetFlags());
2768   return true;
2769 }
2770 
2771 bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
2772                                   SDValue &Base, SDValue &Scale,
2773                                   SDValue &Index, SDValue &Disp,
2774                                   SDValue &Segment) {
2775   assert(Root && P && "Unknown root/parent nodes");
2776   if (!ISD::isNON_EXTLoad(N.getNode()) ||
2777       !IsProfitableToFold(N, P, Root) ||
2778       !IsLegalToFold(N, P, Root, OptLevel))
2779     return false;
2780 
2781   return selectAddr(N.getNode(),
2782                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
2783 }
2784 
2785 bool X86DAGToDAGISel::tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
2786                                        SDValue &Base, SDValue &Scale,
2787                                        SDValue &Index, SDValue &Disp,
2788                                        SDValue &Segment) {
2789   assert(Root && P && "Unknown root/parent nodes");
2790   if (N->getOpcode() != X86ISD::VBROADCAST_LOAD ||
2791       !IsProfitableToFold(N, P, Root) ||
2792       !IsLegalToFold(N, P, Root, OptLevel))
2793     return false;
2794 
2795   return selectAddr(N.getNode(),
2796                     N.getOperand(1), Base, Scale, Index, Disp, Segment);
2797 }
2798 
2799 /// Return an SDNode that returns the value of the global base register.
2800 /// Output instructions required to initialize the global base register,
2801 /// if necessary.
2802 SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
2803   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
2804   auto &DL = MF->getDataLayout();
2805   return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
2806 }
2807 
2808 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2809   if (N->getOpcode() == ISD::TRUNCATE)
2810     N = N->getOperand(0).getNode();
2811   if (N->getOpcode() != X86ISD::Wrapper)
2812     return false;
2813 
2814   auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2815   if (!GA)
2816     return false;
2817 
2818   Optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2819   return CR && CR->getSignedMin().sge(-1ull << Width) &&
2820          CR->getSignedMax().slt(1ull << Width);
2821 }
2822 
2823 static X86::CondCode getCondFromNode(SDNode *N) {
2824   assert(N->isMachineOpcode() && "Unexpected node");
2825   X86::CondCode CC = X86::COND_INVALID;
2826   unsigned Opc = N->getMachineOpcode();
2827   if (Opc == X86::JCC_1)
2828     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(1));
2829   else if (Opc == X86::SETCCr)
2830     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(0));
2831   else if (Opc == X86::SETCCm)
2832     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(5));
2833   else if (Opc == X86::CMOV16rr || Opc == X86::CMOV32rr ||
2834            Opc == X86::CMOV64rr)
2835     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(2));
2836   else if (Opc == X86::CMOV16rm || Opc == X86::CMOV32rm ||
2837            Opc == X86::CMOV64rm)
2838     CC = static_cast<X86::CondCode>(N->getConstantOperandVal(6));
2839 
2840   return CC;
2841 }
2842 
2843 /// Test whether the given X86ISD::CMP node has any users that use a flag
2844 /// other than ZF.
2845 bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const {
2846   // Examine each user of the node.
2847   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2848          UI != UE; ++UI) {
2849     // Only check things that use the flags.
2850     if (UI.getUse().getResNo() != Flags.getResNo())
2851       continue;
2852     // Only examine CopyToReg uses that copy to EFLAGS.
2853     if (UI->getOpcode() != ISD::CopyToReg ||
2854         cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2855       return false;
2856     // Examine each user of the CopyToReg use.
2857     for (SDNode::use_iterator FlagUI = UI->use_begin(),
2858            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2859       // Only examine the Flag result.
2860       if (FlagUI.getUse().getResNo() != 1) continue;
2861       // Anything unusual: assume conservatively.
2862       if (!FlagUI->isMachineOpcode()) return false;
2863       // Examine the condition code of the user.
2864       X86::CondCode CC = getCondFromNode(*FlagUI);
2865 
2866       switch (CC) {
2867       // Comparisons which only use the zero flag.
2868       case X86::COND_E: case X86::COND_NE:
2869         continue;
2870       // Anything else: assume conservatively.
2871       default:
2872         return false;
2873       }
2874     }
2875   }
2876   return true;
2877 }
2878 
2879 /// Test whether the given X86ISD::CMP node has any uses which require the SF
2880 /// flag to be accurate.
2881 bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const {
2882   // Examine each user of the node.
2883   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2884          UI != UE; ++UI) {
2885     // Only check things that use the flags.
2886     if (UI.getUse().getResNo() != Flags.getResNo())
2887       continue;
2888     // Only examine CopyToReg uses that copy to EFLAGS.
2889     if (UI->getOpcode() != ISD::CopyToReg ||
2890         cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2891       return false;
2892     // Examine each user of the CopyToReg use.
2893     for (SDNode::use_iterator FlagUI = UI->use_begin(),
2894            FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
2895       // Only examine the Flag result.
2896       if (FlagUI.getUse().getResNo() != 1) continue;
2897       // Anything unusual: assume conservatively.
2898       if (!FlagUI->isMachineOpcode()) return false;
2899       // Examine the condition code of the user.
2900       X86::CondCode CC = getCondFromNode(*FlagUI);
2901 
2902       switch (CC) {
2903       // Comparisons which don't examine the SF flag.
2904       case X86::COND_A: case X86::COND_AE:
2905       case X86::COND_B: case X86::COND_BE:
2906       case X86::COND_E: case X86::COND_NE:
2907       case X86::COND_O: case X86::COND_NO:
2908       case X86::COND_P: case X86::COND_NP:
2909         continue;
2910       // Anything else: assume conservatively.
2911       default:
2912         return false;
2913       }
2914     }
2915   }
2916   return true;
2917 }
2918 
2919 static bool mayUseCarryFlag(X86::CondCode CC) {
2920   switch (CC) {
2921   // Comparisons which don't examine the CF flag.
2922   case X86::COND_O: case X86::COND_NO:
2923   case X86::COND_E: case X86::COND_NE:
2924   case X86::COND_S: case X86::COND_NS:
2925   case X86::COND_P: case X86::COND_NP:
2926   case X86::COND_L: case X86::COND_GE:
2927   case X86::COND_G: case X86::COND_LE:
2928     return false;
2929   // Anything else: assume conservatively.
2930   default:
2931     return true;
2932   }
2933 }
2934 
2935 /// Test whether the given node which sets flags has any uses which require the
2936 /// CF flag to be accurate.
2937  bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const {
2938   // Examine each user of the node.
2939   for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2940          UI != UE; ++UI) {
2941     // Only check things that use the flags.
2942     if (UI.getUse().getResNo() != Flags.getResNo())
2943       continue;
2944 
2945     unsigned UIOpc = UI->getOpcode();
2946 
2947     if (UIOpc == ISD::CopyToReg) {
2948       // Only examine CopyToReg uses that copy to EFLAGS.
2949       if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
2950         return false;
2951       // Examine each user of the CopyToReg use.
2952       for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
2953            FlagUI != FlagUE; ++FlagUI) {
2954         // Only examine the Flag result.
2955         if (FlagUI.getUse().getResNo() != 1)
2956           continue;
2957         // Anything unusual: assume conservatively.
2958         if (!FlagUI->isMachineOpcode())
2959           return false;
2960         // Examine the condition code of the user.
2961         X86::CondCode CC = getCondFromNode(*FlagUI);
2962 
2963         if (mayUseCarryFlag(CC))
2964           return false;
2965       }
2966 
2967       // This CopyToReg is ok. Move on to the next user.
2968       continue;
2969     }
2970 
2971     // This might be an unselected node. So look for the pre-isel opcodes that
2972     // use flags.
2973     unsigned CCOpNo;
2974     switch (UIOpc) {
2975     default:
2976       // Something unusual. Be conservative.
2977       return false;
2978     case X86ISD::SETCC:       CCOpNo = 0; break;
2979     case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
2980     case X86ISD::CMOV:        CCOpNo = 2; break;
2981     case X86ISD::BRCOND:      CCOpNo = 2; break;
2982     }
2983 
2984     X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo);
2985     if (mayUseCarryFlag(CC))
2986       return false;
2987   }
2988   return true;
2989 }
2990 
2991 /// Check whether or not the chain ending in StoreNode is suitable for doing
2992 /// the {load; op; store} to modify transformation.
2993 static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode,
2994                                         SDValue StoredVal, SelectionDAG *CurDAG,
2995                                         unsigned LoadOpNo,
2996                                         LoadSDNode *&LoadNode,
2997                                         SDValue &InputChain) {
2998   // Is the stored value result 0 of the operation?
2999   if (StoredVal.getResNo() != 0) return false;
3000 
3001   // Are there other uses of the operation other than the store?
3002   if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
3003 
3004   // Is the store non-extending and non-indexed?
3005   if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
3006     return false;
3007 
3008   SDValue Load = StoredVal->getOperand(LoadOpNo);
3009   // Is the stored value a non-extending and non-indexed load?
3010   if (!ISD::isNormalLoad(Load.getNode())) return false;
3011 
3012   // Return LoadNode by reference.
3013   LoadNode = cast<LoadSDNode>(Load);
3014 
3015   // Is store the only read of the loaded value?
3016   if (!Load.hasOneUse())
3017     return false;
3018 
3019   // Is the address of the store the same as the load?
3020   if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
3021       LoadNode->getOffset() != StoreNode->getOffset())
3022     return false;
3023 
3024   bool FoundLoad = false;
3025   SmallVector<SDValue, 4> ChainOps;
3026   SmallVector<const SDNode *, 4> LoopWorklist;
3027   SmallPtrSet<const SDNode *, 16> Visited;
3028   const unsigned int Max = 1024;
3029 
3030   //  Visualization of Load-Op-Store fusion:
3031   // -------------------------
3032   // Legend:
3033   //    *-lines = Chain operand dependencies.
3034   //    |-lines = Normal operand dependencies.
3035   //    Dependencies flow down and right. n-suffix references multiple nodes.
3036   //
3037   //        C                        Xn  C
3038   //        *                         *  *
3039   //        *                          * *
3040   //  Xn  A-LD    Yn                    TF         Yn
3041   //   *    * \   |                       *        |
3042   //    *   *  \  |                        *       |
3043   //     *  *   \ |             =>       A--LD_OP_ST
3044   //      * *    \|                                 \
3045   //       TF    OP                                  \
3046   //         *   | \                                  Zn
3047   //          *  |  \
3048   //         A-ST    Zn
3049   //
3050 
3051   // This merge induced dependences from: #1: Xn -> LD, OP, Zn
3052   //                                      #2: Yn -> LD
3053   //                                      #3: ST -> Zn
3054 
3055   // Ensure the transform is safe by checking for the dual
3056   // dependencies to make sure we do not induce a loop.
3057 
3058   // As LD is a predecessor to both OP and ST we can do this by checking:
3059   //  a). if LD is a predecessor to a member of Xn or Yn.
3060   //  b). if a Zn is a predecessor to ST.
3061 
3062   // However, (b) can only occur through being a chain predecessor to
3063   // ST, which is the same as Zn being a member or predecessor of Xn,
3064   // which is a subset of LD being a predecessor of Xn. So it's
3065   // subsumed by check (a).
3066 
3067   SDValue Chain = StoreNode->getChain();
3068 
3069   // Gather X elements in ChainOps.
3070   if (Chain == Load.getValue(1)) {
3071     FoundLoad = true;
3072     ChainOps.push_back(Load.getOperand(0));
3073   } else if (Chain.getOpcode() == ISD::TokenFactor) {
3074     for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
3075       SDValue Op = Chain.getOperand(i);
3076       if (Op == Load.getValue(1)) {
3077         FoundLoad = true;
3078         // Drop Load, but keep its chain. No cycle check necessary.
3079         ChainOps.push_back(Load.getOperand(0));
3080         continue;
3081       }
3082       LoopWorklist.push_back(Op.getNode());
3083       ChainOps.push_back(Op);
3084     }
3085   }
3086 
3087   if (!FoundLoad)
3088     return false;
3089 
3090   // Worklist is currently Xn. Add Yn to worklist.
3091   for (SDValue Op : StoredVal->ops())
3092     if (Op.getNode() != LoadNode)
3093       LoopWorklist.push_back(Op.getNode());
3094 
3095   // Check (a) if Load is a predecessor to Xn + Yn
3096   if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
3097                                    true))
3098     return false;
3099 
3100   InputChain =
3101       CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
3102   return true;
3103 }
3104 
3105 // Change a chain of {load; op; store} of the same value into a simple op
3106 // through memory of that value, if the uses of the modified value and its
3107 // address are suitable.
3108 //
3109 // The tablegen pattern memory operand pattern is currently not able to match
3110 // the case where the EFLAGS on the original operation are used.
3111 //
3112 // To move this to tablegen, we'll need to improve tablegen to allow flags to
3113 // be transferred from a node in the pattern to the result node, probably with
3114 // a new keyword. For example, we have this
3115 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
3116 //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
3117 //   (implicit EFLAGS)]>;
3118 // but maybe need something like this
3119 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
3120 //  [(store (add (loadi64 addr:$dst), -1), addr:$dst),
3121 //   (transferrable EFLAGS)]>;
3122 //
3123 // Until then, we manually fold these and instruction select the operation
3124 // here.
3125 bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
3126   StoreSDNode *StoreNode = cast<StoreSDNode>(Node);
3127   SDValue StoredVal = StoreNode->getOperand(1);
3128   unsigned Opc = StoredVal->getOpcode();
3129 
3130   // Before we try to select anything, make sure this is memory operand size
3131   // and opcode we can handle. Note that this must match the code below that
3132   // actually lowers the opcodes.
3133   EVT MemVT = StoreNode->getMemoryVT();
3134   if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
3135       MemVT != MVT::i8)
3136     return false;
3137 
3138   bool IsCommutable = false;
3139   bool IsNegate = false;
3140   switch (Opc) {
3141   default:
3142     return false;
3143   case X86ISD::SUB:
3144     IsNegate = isNullConstant(StoredVal.getOperand(0));
3145     break;
3146   case X86ISD::SBB:
3147     break;
3148   case X86ISD::ADD:
3149   case X86ISD::ADC:
3150   case X86ISD::AND:
3151   case X86ISD::OR:
3152   case X86ISD::XOR:
3153     IsCommutable = true;
3154     break;
3155   }
3156 
3157   unsigned LoadOpNo = IsNegate ? 1 : 0;
3158   LoadSDNode *LoadNode = nullptr;
3159   SDValue InputChain;
3160   if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
3161                                    LoadNode, InputChain)) {
3162     if (!IsCommutable)
3163       return false;
3164 
3165     // This operation is commutable, try the other operand.
3166     LoadOpNo = 1;
3167     if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
3168                                      LoadNode, InputChain))
3169       return false;
3170   }
3171 
3172   SDValue Base, Scale, Index, Disp, Segment;
3173   if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
3174                   Segment))
3175     return false;
3176 
3177   auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
3178                           unsigned Opc8) {
3179     switch (MemVT.getSimpleVT().SimpleTy) {
3180     case MVT::i64:
3181       return Opc64;
3182     case MVT::i32:
3183       return Opc32;
3184     case MVT::i16:
3185       return Opc16;
3186     case MVT::i8:
3187       return Opc8;
3188     default:
3189       llvm_unreachable("Invalid size!");
3190     }
3191   };
3192 
3193   MachineSDNode *Result;
3194   switch (Opc) {
3195   case X86ISD::SUB:
3196     // Handle negate.
3197     if (IsNegate) {
3198       unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m,
3199                                      X86::NEG8m);
3200       const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
3201       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
3202                                       MVT::Other, Ops);
3203       break;
3204     }
3205    LLVM_FALLTHROUGH;
3206   case X86ISD::ADD:
3207     // Try to match inc/dec.
3208     if (!Subtarget->slowIncDec() || CurDAG->shouldOptForSize()) {
3209       bool IsOne = isOneConstant(StoredVal.getOperand(1));
3210       bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1));
3211       // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec.
3212       if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) {
3213         unsigned NewOpc =
3214           ((Opc == X86ISD::ADD) == IsOne)
3215               ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
3216               : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
3217         const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
3218         Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
3219                                         MVT::Other, Ops);
3220         break;
3221       }
3222     }
3223     LLVM_FALLTHROUGH;
3224   case X86ISD::ADC:
3225   case X86ISD::SBB:
3226   case X86ISD::AND:
3227   case X86ISD::OR:
3228   case X86ISD::XOR: {
3229     auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
3230       switch (Opc) {
3231       case X86ISD::ADD:
3232         return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
3233                             X86::ADD8mr);
3234       case X86ISD::ADC:
3235         return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
3236                             X86::ADC8mr);
3237       case X86ISD::SUB:
3238         return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
3239                             X86::SUB8mr);
3240       case X86ISD::SBB:
3241         return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
3242                             X86::SBB8mr);
3243       case X86ISD::AND:
3244         return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
3245                             X86::AND8mr);
3246       case X86ISD::OR:
3247         return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
3248       case X86ISD::XOR:
3249         return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
3250                             X86::XOR8mr);
3251       default:
3252         llvm_unreachable("Invalid opcode!");
3253       }
3254     };
3255     auto SelectImm8Opcode = [SelectOpcode](unsigned Opc) {
3256       switch (Opc) {
3257       case X86ISD::ADD:
3258         return SelectOpcode(X86::ADD64mi8, X86::ADD32mi8, X86::ADD16mi8, 0);
3259       case X86ISD::ADC:
3260         return SelectOpcode(X86::ADC64mi8, X86::ADC32mi8, X86::ADC16mi8, 0);
3261       case X86ISD::SUB:
3262         return SelectOpcode(X86::SUB64mi8, X86::SUB32mi8, X86::SUB16mi8, 0);
3263       case X86ISD::SBB:
3264         return SelectOpcode(X86::SBB64mi8, X86::SBB32mi8, X86::SBB16mi8, 0);
3265       case X86ISD::AND:
3266         return SelectOpcode(X86::AND64mi8, X86::AND32mi8, X86::AND16mi8, 0);
3267       case X86ISD::OR:
3268         return SelectOpcode(X86::OR64mi8, X86::OR32mi8, X86::OR16mi8, 0);
3269       case X86ISD::XOR:
3270         return SelectOpcode(X86::XOR64mi8, X86::XOR32mi8, X86::XOR16mi8, 0);
3271       default:
3272         llvm_unreachable("Invalid opcode!");
3273       }
3274     };
3275     auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
3276       switch (Opc) {
3277       case X86ISD::ADD:
3278         return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
3279                             X86::ADD8mi);
3280       case X86ISD::ADC:
3281         return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
3282                             X86::ADC8mi);
3283       case X86ISD::SUB:
3284         return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
3285                             X86::SUB8mi);
3286       case X86ISD::SBB:
3287         return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
3288                             X86::SBB8mi);
3289       case X86ISD::AND:
3290         return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
3291                             X86::AND8mi);
3292       case X86ISD::OR:
3293         return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
3294                             X86::OR8mi);
3295       case X86ISD::XOR:
3296         return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
3297                             X86::XOR8mi);
3298       default:
3299         llvm_unreachable("Invalid opcode!");
3300       }
3301     };
3302 
3303     unsigned NewOpc = SelectRegOpcode(Opc);
3304     SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
3305 
3306     // See if the operand is a constant that we can fold into an immediate
3307     // operand.
3308     if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
3309       int64_t OperandV = OperandC->getSExtValue();
3310 
3311       // Check if we can shrink the operand enough to fit in an immediate (or
3312       // fit into a smaller immediate) by negating it and switching the
3313       // operation.
3314       if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
3315           ((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) ||
3316            (MemVT == MVT::i64 && !isInt<32>(OperandV) &&
3317             isInt<32>(-OperandV))) &&
3318           hasNoCarryFlagUses(StoredVal.getValue(1))) {
3319         OperandV = -OperandV;
3320         Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
3321       }
3322 
3323       // First try to fit this into an Imm8 operand. If it doesn't fit, then try
3324       // the larger immediate operand.
3325       if (MemVT != MVT::i8 && isInt<8>(OperandV)) {
3326         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
3327         NewOpc = SelectImm8Opcode(Opc);
3328       } else if (MemVT != MVT::i64 || isInt<32>(OperandV)) {
3329         Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
3330         NewOpc = SelectImmOpcode(Opc);
3331       }
3332     }
3333 
3334     if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
3335       SDValue CopyTo =
3336           CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
3337                                StoredVal.getOperand(2), SDValue());
3338 
3339       const SDValue Ops[] = {Base,    Scale,   Index,  Disp,
3340                              Segment, Operand, CopyTo, CopyTo.getValue(1)};
3341       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
3342                                       Ops);
3343     } else {
3344       const SDValue Ops[] = {Base,    Scale,   Index,     Disp,
3345                              Segment, Operand, InputChain};
3346       Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
3347                                       Ops);
3348     }
3349     break;
3350   }
3351   default:
3352     llvm_unreachable("Invalid opcode!");
3353   }
3354 
3355   MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
3356                                  LoadNode->getMemOperand()};
3357   CurDAG->setNodeMemRefs(Result, MemOps);
3358 
3359   // Update Load Chain uses as well.
3360   ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
3361   ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
3362   ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
3363   CurDAG->RemoveDeadNode(Node);
3364   return true;
3365 }
3366 
3367 // See if this is an  X & Mask  that we can match to BEXTR/BZHI.
3368 // Where Mask is one of the following patterns:
3369 //   a) x &  (1 << nbits) - 1
3370 //   b) x & ~(-1 << nbits)
3371 //   c) x &  (-1 >> (32 - y))
3372 //   d) x << (32 - y) >> (32 - y)
3373 bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {
3374   assert(
3375       (Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) &&
3376       "Should be either an and-mask, or right-shift after clearing high bits.");
3377 
3378   // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.
3379   if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())
3380     return false;
3381 
3382   MVT NVT = Node->getSimpleValueType(0);
3383 
3384   // Only supported for 32 and 64 bits.
3385   if (NVT != MVT::i32 && NVT != MVT::i64)
3386     return false;
3387 
3388   SDValue NBits;
3389 
3390   // If we have BMI2's BZHI, we are ok with muti-use patterns.
3391   // Else, if we only have BMI1's BEXTR, we require one-use.
3392   const bool CanHaveExtraUses = Subtarget->hasBMI2();
3393   auto checkUses = [CanHaveExtraUses](SDValue Op, unsigned NUses) {
3394     return CanHaveExtraUses ||
3395            Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());
3396   };
3397   auto checkOneUse = [checkUses](SDValue Op) { return checkUses(Op, 1); };
3398   auto checkTwoUse = [checkUses](SDValue Op) { return checkUses(Op, 2); };
3399 
3400   auto peekThroughOneUseTruncation = [checkOneUse](SDValue V) {
3401     if (V->getOpcode() == ISD::TRUNCATE && checkOneUse(V)) {
3402       assert(V.getSimpleValueType() == MVT::i32 &&
3403              V.getOperand(0).getSimpleValueType() == MVT::i64 &&
3404              "Expected i64 -> i32 truncation");
3405       V = V.getOperand(0);
3406     }
3407     return V;
3408   };
3409 
3410   // a) x & ((1 << nbits) + (-1))
3411   auto matchPatternA = [checkOneUse, peekThroughOneUseTruncation,
3412                         &NBits](SDValue Mask) -> bool {
3413     // Match `add`. Must only have one use!
3414     if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))
3415       return false;
3416     // We should be adding all-ones constant (i.e. subtracting one.)
3417     if (!isAllOnesConstant(Mask->getOperand(1)))
3418       return false;
3419     // Match `1 << nbits`. Might be truncated. Must only have one use!
3420     SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
3421     if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
3422       return false;
3423     if (!isOneConstant(M0->getOperand(0)))
3424       return false;
3425     NBits = M0->getOperand(1);
3426     return true;
3427   };
3428 
3429   auto isAllOnes = [this, peekThroughOneUseTruncation, NVT](SDValue V) {
3430     V = peekThroughOneUseTruncation(V);
3431     return CurDAG->MaskedValueIsAllOnes(
3432         V, APInt::getLowBitsSet(V.getSimpleValueType().getSizeInBits(),
3433                                 NVT.getSizeInBits()));
3434   };
3435 
3436   // b) x & ~(-1 << nbits)
3437   auto matchPatternB = [checkOneUse, isAllOnes, peekThroughOneUseTruncation,
3438                         &NBits](SDValue Mask) -> bool {
3439     // Match `~()`. Must only have one use!
3440     if (Mask.getOpcode() != ISD::XOR || !checkOneUse(Mask))
3441       return false;
3442     // The -1 only has to be all-ones for the final Node's NVT.
3443     if (!isAllOnes(Mask->getOperand(1)))
3444       return false;
3445     // Match `-1 << nbits`. Might be truncated. Must only have one use!
3446     SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
3447     if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
3448       return false;
3449     // The -1 only has to be all-ones for the final Node's NVT.
3450     if (!isAllOnes(M0->getOperand(0)))
3451       return false;
3452     NBits = M0->getOperand(1);
3453     return true;
3454   };
3455 
3456   // Match potentially-truncated (bitwidth - y)
3457   auto matchShiftAmt = [checkOneUse, &NBits](SDValue ShiftAmt,
3458                                              unsigned Bitwidth) {
3459     // Skip over a truncate of the shift amount.
3460     if (ShiftAmt.getOpcode() == ISD::TRUNCATE) {
3461       ShiftAmt = ShiftAmt.getOperand(0);
3462       // The trunc should have been the only user of the real shift amount.
3463       if (!checkOneUse(ShiftAmt))
3464         return false;
3465     }
3466     // Match the shift amount as: (bitwidth - y). It should go away, too.
3467     if (ShiftAmt.getOpcode() != ISD::SUB)
3468       return false;
3469     auto V0 = dyn_cast<ConstantSDNode>(ShiftAmt.getOperand(0));
3470     if (!V0 || V0->getZExtValue() != Bitwidth)
3471       return false;
3472     NBits = ShiftAmt.getOperand(1);
3473     return true;
3474   };
3475 
3476   // c) x &  (-1 >> (32 - y))
3477   auto matchPatternC = [checkOneUse, peekThroughOneUseTruncation,
3478                         matchShiftAmt](SDValue Mask) -> bool {
3479     // The mask itself may be truncated.
3480     Mask = peekThroughOneUseTruncation(Mask);
3481     unsigned Bitwidth = Mask.getSimpleValueType().getSizeInBits();
3482     // Match `l>>`. Must only have one use!
3483     if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))
3484       return false;
3485     // We should be shifting truly all-ones constant.
3486     if (!isAllOnesConstant(Mask.getOperand(0)))
3487       return false;
3488     SDValue M1 = Mask.getOperand(1);
3489     // The shift amount should not be used externally.
3490     if (!checkOneUse(M1))
3491       return false;
3492     return matchShiftAmt(M1, Bitwidth);
3493   };
3494 
3495   SDValue X;
3496 
3497   // d) x << (32 - y) >> (32 - y)
3498   auto matchPatternD = [checkOneUse, checkTwoUse, matchShiftAmt,
3499                         &X](SDNode *Node) -> bool {
3500     if (Node->getOpcode() != ISD::SRL)
3501       return false;
3502     SDValue N0 = Node->getOperand(0);
3503     if (N0->getOpcode() != ISD::SHL || !checkOneUse(N0))
3504       return false;
3505     unsigned Bitwidth = N0.getSimpleValueType().getSizeInBits();
3506     SDValue N1 = Node->getOperand(1);
3507     SDValue N01 = N0->getOperand(1);
3508     // Both of the shifts must be by the exact same value.
3509     // There should not be any uses of the shift amount outside of the pattern.
3510     if (N1 != N01 || !checkTwoUse(N1))
3511       return false;
3512     if (!matchShiftAmt(N1, Bitwidth))
3513       return false;
3514     X = N0->getOperand(0);
3515     return true;
3516   };
3517 
3518   auto matchLowBitMask = [matchPatternA, matchPatternB,
3519                           matchPatternC](SDValue Mask) -> bool {
3520     return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);
3521   };
3522 
3523   if (Node->getOpcode() == ISD::AND) {
3524     X = Node->getOperand(0);
3525     SDValue Mask = Node->getOperand(1);
3526 
3527     if (matchLowBitMask(Mask)) {
3528       // Great.
3529     } else {
3530       std::swap(X, Mask);
3531       if (!matchLowBitMask(Mask))
3532         return false;
3533     }
3534   } else if (!matchPatternD(Node))
3535     return false;
3536 
3537   SDLoc DL(Node);
3538 
3539   // Truncate the shift amount.
3540   NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);
3541   insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3542 
3543   // Insert 8-bit NBits into lowest 8 bits of 32-bit register.
3544   // All the other bits are undefined, we do not care about them.
3545   SDValue ImplDef = SDValue(
3546       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0);
3547   insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef);
3548 
3549   SDValue SRIdxVal = CurDAG->getTargetConstant(X86::sub_8bit, DL, MVT::i32);
3550   insertDAGNode(*CurDAG, SDValue(Node, 0), SRIdxVal);
3551   NBits = SDValue(
3552       CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::i32, ImplDef,
3553                              NBits, SRIdxVal), 0);
3554   insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3555 
3556   if (Subtarget->hasBMI2()) {
3557     // Great, just emit the the BZHI..
3558     if (NVT != MVT::i32) {
3559       // But have to place the bit count into the wide-enough register first.
3560       NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, NVT, NBits);
3561       insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3562     }
3563 
3564     SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits);
3565     ReplaceNode(Node, Extract.getNode());
3566     SelectCode(Extract.getNode());
3567     return true;
3568   }
3569 
3570   // Else, if we do *NOT* have BMI2, let's find out if the if the 'X' is
3571   // *logically* shifted (potentially with one-use trunc inbetween),
3572   // and the truncation was the only use of the shift,
3573   // and if so look past one-use truncation.
3574   {
3575     SDValue RealX = peekThroughOneUseTruncation(X);
3576     // FIXME: only if the shift is one-use?
3577     if (RealX != X && RealX.getOpcode() == ISD::SRL)
3578       X = RealX;
3579   }
3580 
3581   MVT XVT = X.getSimpleValueType();
3582 
3583   // Else, emitting BEXTR requires one more step.
3584   // The 'control' of BEXTR has the pattern of:
3585   // [15...8 bit][ 7...0 bit] location
3586   // [ bit count][     shift] name
3587   // I.e. 0b000000011'00000001 means  (x >> 0b1) & 0b11
3588 
3589   // Shift NBits left by 8 bits, thus producing 'control'.
3590   // This makes the low 8 bits to be zero.
3591   SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);
3592   SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8);
3593   insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3594 
3595   // If the 'X' is *logically* shifted, we can fold that shift into 'control'.
3596   // FIXME: only if the shift is one-use?
3597   if (X.getOpcode() == ISD::SRL) {
3598     SDValue ShiftAmt = X.getOperand(1);
3599     X = X.getOperand(0);
3600 
3601     assert(ShiftAmt.getValueType() == MVT::i8 &&
3602            "Expected shift amount to be i8");
3603 
3604     // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!
3605     // We could zext to i16 in some form, but we intentionally don't do that.
3606     SDValue OrigShiftAmt = ShiftAmt;
3607     ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt);
3608     insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);
3609 
3610     // And now 'or' these low 8 bits of shift amount into the 'control'.
3611     Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt);
3612     insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3613   }
3614 
3615   // But have to place the 'control' into the wide-enough register first.
3616   if (XVT != MVT::i32) {
3617     Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control);
3618     insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3619   }
3620 
3621   // And finally, form the BEXTR itself.
3622   SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control);
3623 
3624   // The 'X' was originally truncated. Do that now.
3625   if (XVT != NVT) {
3626     insertDAGNode(*CurDAG, SDValue(Node, 0), Extract);
3627     Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract);
3628   }
3629 
3630   ReplaceNode(Node, Extract.getNode());
3631   SelectCode(Extract.getNode());
3632 
3633   return true;
3634 }
3635 
3636 // See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
3637 MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {
3638   MVT NVT = Node->getSimpleValueType(0);
3639   SDLoc dl(Node);
3640 
3641   SDValue N0 = Node->getOperand(0);
3642   SDValue N1 = Node->getOperand(1);
3643 
3644   // If we have TBM we can use an immediate for the control. If we have BMI
3645   // we should only do this if the BEXTR instruction is implemented well.
3646   // Otherwise moving the control into a register makes this more costly.
3647   // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
3648   // hoisting the move immediate would make it worthwhile with a less optimal
3649   // BEXTR?
3650   bool PreferBEXTR =
3651       Subtarget->hasTBM() || (Subtarget->hasBMI() && Subtarget->hasFastBEXTR());
3652   if (!PreferBEXTR && !Subtarget->hasBMI2())
3653     return nullptr;
3654 
3655   // Must have a shift right.
3656   if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
3657     return nullptr;
3658 
3659   // Shift can't have additional users.
3660   if (!N0->hasOneUse())
3661     return nullptr;
3662 
3663   // Only supported for 32 and 64 bits.
3664   if (NVT != MVT::i32 && NVT != MVT::i64)
3665     return nullptr;
3666 
3667   // Shift amount and RHS of and must be constant.
3668   ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(N1);
3669   ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
3670   if (!MaskCst || !ShiftCst)
3671     return nullptr;
3672 
3673   // And RHS must be a mask.
3674   uint64_t Mask = MaskCst->getZExtValue();
3675   if (!isMask_64(Mask))
3676     return nullptr;
3677 
3678   uint64_t Shift = ShiftCst->getZExtValue();
3679   uint64_t MaskSize = countPopulation(Mask);
3680 
3681   // Don't interfere with something that can be handled by extracting AH.
3682   // TODO: If we are able to fold a load, BEXTR might still be better than AH.
3683   if (Shift == 8 && MaskSize == 8)
3684     return nullptr;
3685 
3686   // Make sure we are only using bits that were in the original value, not
3687   // shifted in.
3688   if (Shift + MaskSize > NVT.getSizeInBits())
3689     return nullptr;
3690 
3691   // BZHI, if available, is always fast, unlike BEXTR. But even if we decide
3692   // that we can't use BEXTR, it is only worthwhile using BZHI if the mask
3693   // does not fit into 32 bits. Load folding is not a sufficient reason.
3694   if (!PreferBEXTR && MaskSize <= 32)
3695     return nullptr;
3696 
3697   SDValue Control;
3698   unsigned ROpc, MOpc;
3699 
3700   if (!PreferBEXTR) {
3701     assert(Subtarget->hasBMI2() && "We must have BMI2's BZHI then.");
3702     // If we can't make use of BEXTR then we can't fuse shift+mask stages.
3703     // Let's perform the mask first, and apply shift later. Note that we need to
3704     // widen the mask to account for the fact that we'll apply shift afterwards!
3705     Control = CurDAG->getTargetConstant(Shift + MaskSize, dl, NVT);
3706     ROpc = NVT == MVT::i64 ? X86::BZHI64rr : X86::BZHI32rr;
3707     MOpc = NVT == MVT::i64 ? X86::BZHI64rm : X86::BZHI32rm;
3708     unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
3709     Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
3710   } else {
3711     // The 'control' of BEXTR has the pattern of:
3712     // [15...8 bit][ 7...0 bit] location
3713     // [ bit count][     shift] name
3714     // I.e. 0b000000011'00000001 means  (x >> 0b1) & 0b11
3715     Control = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
3716     if (Subtarget->hasTBM()) {
3717       ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
3718       MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
3719     } else {
3720       assert(Subtarget->hasBMI() && "We must have BMI1's BEXTR then.");
3721       // BMI requires the immediate to placed in a register.
3722       ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
3723       MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
3724       unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
3725       Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
3726     }
3727   }
3728 
3729   MachineSDNode *NewNode;
3730   SDValue Input = N0->getOperand(0);
3731   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3732   if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3733     SDValue Ops[] = {
3734         Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Control, Input.getOperand(0)};
3735     SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
3736     NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3737     // Update the chain.
3738     ReplaceUses(Input.getValue(1), SDValue(NewNode, 2));
3739     // Record the mem-refs
3740     CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});
3741   } else {
3742     NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, Control);
3743   }
3744 
3745   if (!PreferBEXTR) {
3746     // We still need to apply the shift.
3747     SDValue ShAmt = CurDAG->getTargetConstant(Shift, dl, NVT);
3748     unsigned NewOpc = NVT == MVT::i64 ? X86::SHR64ri : X86::SHR32ri;
3749     NewNode =
3750         CurDAG->getMachineNode(NewOpc, dl, NVT, SDValue(NewNode, 0), ShAmt);
3751   }
3752 
3753   return NewNode;
3754 }
3755 
3756 // Emit a PCMISTR(I/M) instruction.
3757 MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
3758                                              bool MayFoldLoad, const SDLoc &dl,
3759                                              MVT VT, SDNode *Node) {
3760   SDValue N0 = Node->getOperand(0);
3761   SDValue N1 = Node->getOperand(1);
3762   SDValue Imm = Node->getOperand(2);
3763   const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3764   Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3765 
3766   // Try to fold a load. No need to check alignment.
3767   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3768   if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3769     SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3770                       N1.getOperand(0) };
3771     SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
3772     MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3773     // Update the chain.
3774     ReplaceUses(N1.getValue(1), SDValue(CNode, 2));
3775     // Record the mem-refs
3776     CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
3777     return CNode;
3778   }
3779 
3780   SDValue Ops[] = { N0, N1, Imm };
3781   SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
3782   MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3783   return CNode;
3784 }
3785 
3786 // Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
3787 // to emit a second instruction after this one. This is needed since we have two
3788 // copyToReg nodes glued before this and we need to continue that glue through.
3789 MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
3790                                              bool MayFoldLoad, const SDLoc &dl,
3791                                              MVT VT, SDNode *Node,
3792                                              SDValue &InFlag) {
3793   SDValue N0 = Node->getOperand(0);
3794   SDValue N2 = Node->getOperand(2);
3795   SDValue Imm = Node->getOperand(4);
3796   const ConstantInt *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3797   Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3798 
3799   // Try to fold a load. No need to check alignment.
3800   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3801   if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3802     SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3803                       N2.getOperand(0), InFlag };
3804     SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
3805     MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3806     InFlag = SDValue(CNode, 3);
3807     // Update the chain.
3808     ReplaceUses(N2.getValue(1), SDValue(CNode, 2));
3809     // Record the mem-refs
3810     CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});
3811     return CNode;
3812   }
3813 
3814   SDValue Ops[] = { N0, N2, Imm, InFlag };
3815   SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
3816   MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3817   InFlag = SDValue(CNode, 2);
3818   return CNode;
3819 }
3820 
3821 bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
3822   EVT VT = N->getValueType(0);
3823 
3824   // Only handle scalar shifts.
3825   if (VT.isVector())
3826     return false;
3827 
3828   // Narrower shifts only mask to 5 bits in hardware.
3829   unsigned Size = VT == MVT::i64 ? 64 : 32;
3830 
3831   SDValue OrigShiftAmt = N->getOperand(1);
3832   SDValue ShiftAmt = OrigShiftAmt;
3833   SDLoc DL(N);
3834 
3835   // Skip over a truncate of the shift amount.
3836   if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
3837     ShiftAmt = ShiftAmt->getOperand(0);
3838 
3839   // This function is called after X86DAGToDAGISel::matchBitExtract(),
3840   // so we are not afraid that we might mess up BZHI/BEXTR pattern.
3841 
3842   SDValue NewShiftAmt;
3843   if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) {
3844     SDValue Add0 = ShiftAmt->getOperand(0);
3845     SDValue Add1 = ShiftAmt->getOperand(1);
3846     // If we are shifting by X+/-N where N == 0 mod Size, then just shift by X
3847     // to avoid the ADD/SUB.
3848     if (isa<ConstantSDNode>(Add1) &&
3849         cast<ConstantSDNode>(Add1)->getZExtValue() % Size == 0) {
3850       NewShiftAmt = Add0;
3851     // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
3852     // generate a NEG instead of a SUB of a constant.
3853     } else if (ShiftAmt->getOpcode() == ISD::SUB &&
3854                isa<ConstantSDNode>(Add0) &&
3855                cast<ConstantSDNode>(Add0)->getZExtValue() != 0 &&
3856                cast<ConstantSDNode>(Add0)->getZExtValue() % Size == 0) {
3857       // Insert a negate op.
3858       // TODO: This isn't guaranteed to replace the sub if there is a logic cone
3859       // that uses it that's not a shift.
3860       EVT SubVT = ShiftAmt.getValueType();
3861       SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
3862       SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, Add1);
3863       NewShiftAmt = Neg;
3864 
3865       // Insert these operands into a valid topological order so they can
3866       // get selected independently.
3867       insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
3868       insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
3869     } else
3870       return false;
3871   } else
3872     return false;
3873 
3874   if (NewShiftAmt.getValueType() != MVT::i8) {
3875     // Need to truncate the shift amount.
3876     NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
3877     // Add to a correct topological ordering.
3878     insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3879   }
3880 
3881   // Insert a new mask to keep the shift amount legal. This should be removed
3882   // by isel patterns.
3883   NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
3884                                 CurDAG->getConstant(Size - 1, DL, MVT::i8));
3885   // Place in a correct topological ordering.
3886   insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
3887 
3888   SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
3889                                                    NewShiftAmt);
3890   if (UpdatedNode != N) {
3891     // If we found an existing node, we should replace ourselves with that node
3892     // and wait for it to be selected after its other users.
3893     ReplaceNode(N, UpdatedNode);
3894     return true;
3895   }
3896 
3897   // If the original shift amount is now dead, delete it so that we don't run
3898   // it through isel.
3899   if (OrigShiftAmt.getNode()->use_empty())
3900     CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
3901 
3902   // Now that we've optimized the shift amount, defer to normal isel to get
3903   // load folding and legacy vs BMI2 selection without repeating it here.
3904   SelectCode(N);
3905   return true;
3906 }
3907 
3908 bool X86DAGToDAGISel::tryShrinkShlLogicImm(SDNode *N) {
3909   MVT NVT = N->getSimpleValueType(0);
3910   unsigned Opcode = N->getOpcode();
3911   SDLoc dl(N);
3912 
3913   // For operations of the form (x << C1) op C2, check if we can use a smaller
3914   // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
3915   SDValue Shift = N->getOperand(0);
3916   SDValue N1 = N->getOperand(1);
3917 
3918   ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
3919   if (!Cst)
3920     return false;
3921 
3922   int64_t Val = Cst->getSExtValue();
3923 
3924   // If we have an any_extend feeding the AND, look through it to see if there
3925   // is a shift behind it. But only if the AND doesn't use the extended bits.
3926   // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
3927   bool FoundAnyExtend = false;
3928   if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
3929       Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
3930       isUInt<32>(Val)) {
3931     FoundAnyExtend = true;
3932     Shift = Shift.getOperand(0);
3933   }
3934 
3935   if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse())
3936     return false;
3937 
3938   // i8 is unshrinkable, i16 should be promoted to i32.
3939   if (NVT != MVT::i32 && NVT != MVT::i64)
3940     return false;
3941 
3942   ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
3943   if (!ShlCst)
3944     return false;
3945 
3946   uint64_t ShAmt = ShlCst->getZExtValue();
3947 
3948   // Make sure that we don't change the operation by removing bits.
3949   // This only matters for OR and XOR, AND is unaffected.
3950   uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1;
3951   if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
3952     return false;
3953 
3954   // Check the minimum bitwidth for the new constant.
3955   // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
3956   auto CanShrinkImmediate = [&](int64_t &ShiftedVal) {
3957     if (Opcode == ISD::AND) {
3958       // AND32ri is the same as AND64ri32 with zext imm.
3959       // Try this before sign extended immediates below.
3960       ShiftedVal = (uint64_t)Val >> ShAmt;
3961       if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
3962         return true;
3963       // Also swap order when the AND can become MOVZX.
3964       if (ShiftedVal == UINT8_MAX || ShiftedVal == UINT16_MAX)
3965         return true;
3966     }
3967     ShiftedVal = Val >> ShAmt;
3968     if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) ||
3969         (!isInt<32>(Val) && isInt<32>(ShiftedVal)))
3970       return true;
3971     if (Opcode != ISD::AND) {
3972       // MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr
3973       ShiftedVal = (uint64_t)Val >> ShAmt;
3974       if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
3975         return true;
3976     }
3977     return false;
3978   };
3979 
3980   int64_t ShiftedVal;
3981   if (!CanShrinkImmediate(ShiftedVal))
3982     return false;
3983 
3984   // Ok, we can reorder to get a smaller immediate.
3985 
3986   // But, its possible the original immediate allowed an AND to become MOVZX.
3987   // Doing this late due to avoid the MakedValueIsZero call as late as
3988   // possible.
3989   if (Opcode == ISD::AND) {
3990     // Find the smallest zext this could possibly be.
3991     unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits();
3992     ZExtWidth = PowerOf2Ceil(std::max(ZExtWidth, 8U));
3993 
3994     // Figure out which bits need to be zero to achieve that mask.
3995     APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(),
3996                                             ZExtWidth);
3997     NeededMask &= ~Cst->getAPIntValue();
3998 
3999     if (CurDAG->MaskedValueIsZero(N->getOperand(0), NeededMask))
4000       return false;
4001   }
4002 
4003   SDValue X = Shift.getOperand(0);
4004   if (FoundAnyExtend) {
4005     SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X);
4006     insertDAGNode(*CurDAG, SDValue(N, 0), NewX);
4007     X = NewX;
4008   }
4009 
4010   SDValue NewCst = CurDAG->getConstant(ShiftedVal, dl, NVT);
4011   insertDAGNode(*CurDAG, SDValue(N, 0), NewCst);
4012   SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst);
4013   insertDAGNode(*CurDAG, SDValue(N, 0), NewBinOp);
4014   SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp,
4015                                    Shift.getOperand(1));
4016   ReplaceNode(N, NewSHL.getNode());
4017   SelectCode(NewSHL.getNode());
4018   return true;
4019 }
4020 
4021 /// If the high bits of an 'and' operand are known zero, try setting the
4022 /// high bits of an 'and' constant operand to produce a smaller encoding by
4023 /// creating a small, sign-extended negative immediate rather than a large
4024 /// positive one. This reverses a transform in SimplifyDemandedBits that
4025 /// shrinks mask constants by clearing bits. There is also a possibility that
4026 /// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
4027 /// case, just replace the 'and'. Return 'true' if the node is replaced.
4028 bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
4029   // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
4030   // have immediate operands.
4031   MVT VT = And->getSimpleValueType(0);
4032   if (VT != MVT::i32 && VT != MVT::i64)
4033     return false;
4034 
4035   auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
4036   if (!And1C)
4037     return false;
4038 
4039   // Bail out if the mask constant is already negative. It's can't shrink more.
4040   // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
4041   // patterns to use a 32-bit and instead of a 64-bit and by relying on the
4042   // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
4043   // are negative too.
4044   APInt MaskVal = And1C->getAPIntValue();
4045   unsigned MaskLZ = MaskVal.countLeadingZeros();
4046   if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
4047     return false;
4048 
4049   // Don't extend into the upper 32 bits of a 64 bit mask.
4050   if (VT == MVT::i64 && MaskLZ >= 32) {
4051     MaskLZ -= 32;
4052     MaskVal = MaskVal.trunc(32);
4053   }
4054 
4055   SDValue And0 = And->getOperand(0);
4056   APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
4057   APInt NegMaskVal = MaskVal | HighZeros;
4058 
4059   // If a negative constant would not allow a smaller encoding, there's no need
4060   // to continue. Only change the constant when we know it's a win.
4061   unsigned MinWidth = NegMaskVal.getMinSignedBits();
4062   if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getMinSignedBits() <= 32))
4063     return false;
4064 
4065   // Extend masks if we truncated above.
4066   if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
4067     NegMaskVal = NegMaskVal.zext(64);
4068     HighZeros = HighZeros.zext(64);
4069   }
4070 
4071   // The variable operand must be all zeros in the top bits to allow using the
4072   // new, negative constant as the mask.
4073   if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
4074     return false;
4075 
4076   // Check if the mask is -1. In that case, this is an unnecessary instruction
4077   // that escaped earlier analysis.
4078   if (NegMaskVal.isAllOnesValue()) {
4079     ReplaceNode(And, And0.getNode());
4080     return true;
4081   }
4082 
4083   // A negative mask allows a smaller encoding. Create a new 'and' node.
4084   SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
4085   SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
4086   ReplaceNode(And, NewAnd.getNode());
4087   SelectCode(NewAnd.getNode());
4088   return true;
4089 }
4090 
4091 static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad,
4092                               bool FoldedBCast, bool Masked) {
4093   if (Masked) {
4094     if (FoldedLoad) {
4095       switch (TestVT.SimpleTy) {
4096       default: llvm_unreachable("Unexpected VT!");
4097       case MVT::v16i8:
4098         return IsTestN ? X86::VPTESTNMBZ128rmk : X86::VPTESTMBZ128rmk;
4099       case MVT::v8i16:
4100         return IsTestN ? X86::VPTESTNMWZ128rmk : X86::VPTESTMWZ128rmk;
4101       case MVT::v4i32:
4102         return IsTestN ? X86::VPTESTNMDZ128rmk : X86::VPTESTMDZ128rmk;
4103       case MVT::v2i64:
4104         return IsTestN ? X86::VPTESTNMQZ128rmk : X86::VPTESTMQZ128rmk;
4105       case MVT::v32i8:
4106         return IsTestN ? X86::VPTESTNMBZ256rmk : X86::VPTESTMBZ256rmk;
4107       case MVT::v16i16:
4108         return IsTestN ? X86::VPTESTNMWZ256rmk : X86::VPTESTMWZ256rmk;
4109       case MVT::v8i32:
4110         return IsTestN ? X86::VPTESTNMDZ256rmk : X86::VPTESTMDZ256rmk;
4111       case MVT::v4i64:
4112         return IsTestN ? X86::VPTESTNMQZ256rmk : X86::VPTESTMQZ256rmk;
4113       case MVT::v64i8:
4114         return IsTestN ? X86::VPTESTNMBZrmk : X86::VPTESTMBZrmk;
4115       case MVT::v32i16:
4116         return IsTestN ? X86::VPTESTNMWZrmk : X86::VPTESTMWZrmk;
4117       case MVT::v16i32:
4118         return IsTestN ? X86::VPTESTNMDZrmk : X86::VPTESTMDZrmk;
4119       case MVT::v8i64:
4120         return IsTestN ? X86::VPTESTNMQZrmk : X86::VPTESTMQZrmk;
4121       }
4122     }
4123 
4124     if (FoldedBCast) {
4125       switch (TestVT.SimpleTy) {
4126       default: llvm_unreachable("Unexpected VT!");
4127       case MVT::v4i32:
4128         return IsTestN ? X86::VPTESTNMDZ128rmbk : X86::VPTESTMDZ128rmbk;
4129       case MVT::v2i64:
4130         return IsTestN ? X86::VPTESTNMQZ128rmbk : X86::VPTESTMQZ128rmbk;
4131       case MVT::v8i32:
4132         return IsTestN ? X86::VPTESTNMDZ256rmbk : X86::VPTESTMDZ256rmbk;
4133       case MVT::v4i64:
4134         return IsTestN ? X86::VPTESTNMQZ256rmbk : X86::VPTESTMQZ256rmbk;
4135       case MVT::v16i32:
4136         return IsTestN ? X86::VPTESTNMDZrmbk : X86::VPTESTMDZrmbk;
4137       case MVT::v8i64:
4138         return IsTestN ? X86::VPTESTNMQZrmbk : X86::VPTESTMQZrmbk;
4139       }
4140     }
4141 
4142     switch (TestVT.SimpleTy) {
4143     default: llvm_unreachable("Unexpected VT!");
4144     case MVT::v16i8:
4145       return IsTestN ? X86::VPTESTNMBZ128rrk : X86::VPTESTMBZ128rrk;
4146     case MVT::v8i16:
4147       return IsTestN ? X86::VPTESTNMWZ128rrk : X86::VPTESTMWZ128rrk;
4148     case MVT::v4i32:
4149       return IsTestN ? X86::VPTESTNMDZ128rrk : X86::VPTESTMDZ128rrk;
4150     case MVT::v2i64:
4151       return IsTestN ? X86::VPTESTNMQZ128rrk : X86::VPTESTMQZ128rrk;
4152     case MVT::v32i8:
4153       return IsTestN ? X86::VPTESTNMBZ256rrk : X86::VPTESTMBZ256rrk;
4154     case MVT::v16i16:
4155       return IsTestN ? X86::VPTESTNMWZ256rrk : X86::VPTESTMWZ256rrk;
4156     case MVT::v8i32:
4157       return IsTestN ? X86::VPTESTNMDZ256rrk : X86::VPTESTMDZ256rrk;
4158     case MVT::v4i64:
4159       return IsTestN ? X86::VPTESTNMQZ256rrk : X86::VPTESTMQZ256rrk;
4160     case MVT::v64i8:
4161       return IsTestN ? X86::VPTESTNMBZrrk : X86::VPTESTMBZrrk;
4162     case MVT::v32i16:
4163       return IsTestN ? X86::VPTESTNMWZrrk : X86::VPTESTMWZrrk;
4164     case MVT::v16i32:
4165       return IsTestN ? X86::VPTESTNMDZrrk : X86::VPTESTMDZrrk;
4166     case MVT::v8i64:
4167       return IsTestN ? X86::VPTESTNMQZrrk : X86::VPTESTMQZrrk;
4168     }
4169   }
4170 
4171   if (FoldedLoad) {
4172     switch (TestVT.SimpleTy) {
4173     default: llvm_unreachable("Unexpected VT!");
4174     case MVT::v16i8:
4175       return IsTestN ? X86::VPTESTNMBZ128rm : X86::VPTESTMBZ128rm;
4176     case MVT::v8i16:
4177       return IsTestN ? X86::VPTESTNMWZ128rm : X86::VPTESTMWZ128rm;
4178     case MVT::v4i32:
4179       return IsTestN ? X86::VPTESTNMDZ128rm : X86::VPTESTMDZ128rm;
4180     case MVT::v2i64:
4181       return IsTestN ? X86::VPTESTNMQZ128rm : X86::VPTESTMQZ128rm;
4182     case MVT::v32i8:
4183       return IsTestN ? X86::VPTESTNMBZ256rm : X86::VPTESTMBZ256rm;
4184     case MVT::v16i16:
4185       return IsTestN ? X86::VPTESTNMWZ256rm : X86::VPTESTMWZ256rm;
4186     case MVT::v8i32:
4187       return IsTestN ? X86::VPTESTNMDZ256rm : X86::VPTESTMDZ256rm;
4188     case MVT::v4i64:
4189       return IsTestN ? X86::VPTESTNMQZ256rm : X86::VPTESTMQZ256rm;
4190     case MVT::v64i8:
4191       return IsTestN ? X86::VPTESTNMBZrm : X86::VPTESTMBZrm;
4192     case MVT::v32i16:
4193       return IsTestN ? X86::VPTESTNMWZrm : X86::VPTESTMWZrm;
4194     case MVT::v16i32:
4195       return IsTestN ? X86::VPTESTNMDZrm : X86::VPTESTMDZrm;
4196     case MVT::v8i64:
4197       return IsTestN ? X86::VPTESTNMQZrm : X86::VPTESTMQZrm;
4198     }
4199   }
4200 
4201   if (FoldedBCast) {
4202     switch (TestVT.SimpleTy) {
4203     default: llvm_unreachable("Unexpected VT!");
4204     case MVT::v4i32:
4205       return IsTestN ? X86::VPTESTNMDZ128rmb : X86::VPTESTMDZ128rmb;
4206     case MVT::v2i64:
4207       return IsTestN ? X86::VPTESTNMQZ128rmb : X86::VPTESTMQZ128rmb;
4208     case MVT::v8i32:
4209       return IsTestN ? X86::VPTESTNMDZ256rmb : X86::VPTESTMDZ256rmb;
4210     case MVT::v4i64:
4211       return IsTestN ? X86::VPTESTNMQZ256rmb : X86::VPTESTMQZ256rmb;
4212     case MVT::v16i32:
4213       return IsTestN ? X86::VPTESTNMDZrmb : X86::VPTESTMDZrmb;
4214     case MVT::v8i64:
4215       return IsTestN ? X86::VPTESTNMQZrmb : X86::VPTESTMQZrmb;
4216     }
4217   }
4218 
4219   switch (TestVT.SimpleTy) {
4220   default: llvm_unreachable("Unexpected VT!");
4221   case MVT::v16i8:
4222     return IsTestN ? X86::VPTESTNMBZ128rr : X86::VPTESTMBZ128rr;
4223   case MVT::v8i16:
4224     return IsTestN ? X86::VPTESTNMWZ128rr : X86::VPTESTMWZ128rr;
4225   case MVT::v4i32:
4226     return IsTestN ? X86::VPTESTNMDZ128rr : X86::VPTESTMDZ128rr;
4227   case MVT::v2i64:
4228     return IsTestN ? X86::VPTESTNMQZ128rr : X86::VPTESTMQZ128rr;
4229   case MVT::v32i8:
4230     return IsTestN ? X86::VPTESTNMBZ256rr : X86::VPTESTMBZ256rr;
4231   case MVT::v16i16:
4232     return IsTestN ? X86::VPTESTNMWZ256rr : X86::VPTESTMWZ256rr;
4233   case MVT::v8i32:
4234     return IsTestN ? X86::VPTESTNMDZ256rr : X86::VPTESTMDZ256rr;
4235   case MVT::v4i64:
4236     return IsTestN ? X86::VPTESTNMQZ256rr : X86::VPTESTMQZ256rr;
4237   case MVT::v64i8:
4238     return IsTestN ? X86::VPTESTNMBZrr : X86::VPTESTMBZrr;
4239   case MVT::v32i16:
4240     return IsTestN ? X86::VPTESTNMWZrr : X86::VPTESTMWZrr;
4241   case MVT::v16i32:
4242     return IsTestN ? X86::VPTESTNMDZrr : X86::VPTESTMDZrr;
4243   case MVT::v8i64:
4244     return IsTestN ? X86::VPTESTNMQZrr : X86::VPTESTMQZrr;
4245   }
4246 }
4247 
4248 // Try to create VPTESTM instruction. If InMask is not null, it will be used
4249 // to form a masked operation.
4250 bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc,
4251                                  SDValue InMask) {
4252   assert(Subtarget->hasAVX512() && "Expected AVX512!");
4253   assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 &&
4254          "Unexpected VT!");
4255 
4256   // Look for equal and not equal compares.
4257   ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get();
4258   if (CC != ISD::SETEQ && CC != ISD::SETNE)
4259     return false;
4260 
4261   SDValue SetccOp0 = Setcc.getOperand(0);
4262   SDValue SetccOp1 = Setcc.getOperand(1);
4263 
4264   // Canonicalize the all zero vector to the RHS.
4265   if (ISD::isBuildVectorAllZeros(SetccOp0.getNode()))
4266     std::swap(SetccOp0, SetccOp1);
4267 
4268   // See if we're comparing against zero.
4269   if (!ISD::isBuildVectorAllZeros(SetccOp1.getNode()))
4270     return false;
4271 
4272   SDValue N0 = SetccOp0;
4273 
4274   MVT CmpVT = N0.getSimpleValueType();
4275   MVT CmpSVT = CmpVT.getVectorElementType();
4276 
4277   // Start with both operands the same. We'll try to refine this.
4278   SDValue Src0 = N0;
4279   SDValue Src1 = N0;
4280 
4281   {
4282     // Look through single use bitcasts.
4283     SDValue N0Temp = N0;
4284     if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse())
4285       N0Temp = N0.getOperand(0);
4286 
4287      // Look for single use AND.
4288     if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) {
4289       Src0 = N0Temp.getOperand(0);
4290       Src1 = N0Temp.getOperand(1);
4291     }
4292   }
4293 
4294   // Without VLX we need to widen the load.
4295   bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector();
4296 
4297   // We can only fold loads if the sources are unique.
4298   bool CanFoldLoads = Src0 != Src1;
4299 
4300   // Try to fold loads unless we need to widen.
4301   bool FoldedLoad = false;
4302   SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Load;
4303   if (!Widen && CanFoldLoads) {
4304     Load = Src1;
4305     FoldedLoad = tryFoldLoad(Root, N0.getNode(), Load, Tmp0, Tmp1, Tmp2, Tmp3,
4306                              Tmp4);
4307     if (!FoldedLoad) {
4308       // And is computative.
4309       Load = Src0;
4310       FoldedLoad = tryFoldLoad(Root, N0.getNode(), Load, Tmp0, Tmp1, Tmp2,
4311                                Tmp3, Tmp4);
4312       if (FoldedLoad)
4313         std::swap(Src0, Src1);
4314     }
4315   }
4316 
4317   auto findBroadcastedOp = [](SDValue Src, MVT CmpSVT, SDNode *&Parent) {
4318     // Look through single use bitcasts.
4319     if (Src.getOpcode() == ISD::BITCAST && Src.hasOneUse()) {
4320       Parent = Src.getNode();
4321       Src = Src.getOperand(0);
4322     }
4323 
4324     if (Src.getOpcode() == X86ISD::VBROADCAST_LOAD && Src.hasOneUse()) {
4325       auto *MemIntr = cast<MemIntrinsicSDNode>(Src);
4326       if (MemIntr->getMemoryVT().getSizeInBits() == CmpSVT.getSizeInBits())
4327         return Src;
4328     }
4329 
4330     return SDValue();
4331   };
4332 
4333   // If we didn't fold a load, try to match broadcast. No widening limitation
4334   // for this. But only 32 and 64 bit types are supported.
4335   bool FoldedBCast = false;
4336   if (!FoldedLoad && CanFoldLoads &&
4337       (CmpSVT == MVT::i32 || CmpSVT == MVT::i64)) {
4338     SDNode *ParentNode = N0.getNode();
4339     if ((Load = findBroadcastedOp(Src1, CmpSVT, ParentNode))) {
4340       FoldedBCast = tryFoldBroadcast(Root, ParentNode, Load, Tmp0,
4341                                      Tmp1, Tmp2, Tmp3, Tmp4);
4342     }
4343 
4344     // Try the other operand.
4345     if (!FoldedBCast) {
4346       SDNode *ParentNode = N0.getNode();
4347       if ((Load = findBroadcastedOp(Src0, CmpSVT, ParentNode))) {
4348         FoldedBCast = tryFoldBroadcast(Root, ParentNode, Load, Tmp0,
4349                                        Tmp1, Tmp2, Tmp3, Tmp4);
4350         if (FoldedBCast)
4351           std::swap(Src0, Src1);
4352       }
4353     }
4354   }
4355 
4356   auto getMaskRC = [](MVT MaskVT) {
4357     switch (MaskVT.SimpleTy) {
4358     default: llvm_unreachable("Unexpected VT!");
4359     case MVT::v2i1:  return X86::VK2RegClassID;
4360     case MVT::v4i1:  return X86::VK4RegClassID;
4361     case MVT::v8i1:  return X86::VK8RegClassID;
4362     case MVT::v16i1: return X86::VK16RegClassID;
4363     case MVT::v32i1: return X86::VK32RegClassID;
4364     case MVT::v64i1: return X86::VK64RegClassID;
4365     }
4366   };
4367 
4368   bool IsMasked = InMask.getNode() != nullptr;
4369 
4370   SDLoc dl(Root);
4371 
4372   MVT ResVT = Setcc.getSimpleValueType();
4373   MVT MaskVT = ResVT;
4374   if (Widen) {
4375     // Widen the inputs using insert_subreg or copy_to_regclass.
4376     unsigned Scale = CmpVT.is128BitVector() ? 4 : 2;
4377     unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm;
4378     unsigned NumElts = CmpVT.getVectorNumElements() * Scale;
4379     CmpVT = MVT::getVectorVT(CmpSVT, NumElts);
4380     MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
4381     SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl,
4382                                                      CmpVT), 0);
4383     Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0);
4384 
4385     assert(!FoldedLoad && "Shouldn't have folded the load");
4386     if (!FoldedBCast)
4387       Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1);
4388 
4389     if (IsMasked) {
4390       // Widen the mask.
4391       unsigned RegClass = getMaskRC(MaskVT);
4392       SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
4393       InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4394                                               dl, MaskVT, InMask, RC), 0);
4395     }
4396   }
4397 
4398   bool IsTestN = CC == ISD::SETEQ;
4399   unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast,
4400                                IsMasked);
4401 
4402   MachineSDNode *CNode;
4403   if (FoldedLoad || FoldedBCast) {
4404     SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other);
4405 
4406     if (IsMasked) {
4407       SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
4408                         Load.getOperand(0) };
4409       CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4410     } else {
4411       SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
4412                         Load.getOperand(0) };
4413       CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4414     }
4415 
4416     // Update the chain.
4417     ReplaceUses(Load.getValue(1), SDValue(CNode, 1));
4418     // Record the mem-refs
4419     CurDAG->setNodeMemRefs(CNode, {cast<MemSDNode>(Load)->getMemOperand()});
4420   } else {
4421     if (IsMasked)
4422       CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1);
4423     else
4424       CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1);
4425   }
4426 
4427   // If we widened, we need to shrink the mask VT.
4428   if (Widen) {
4429     unsigned RegClass = getMaskRC(ResVT);
4430     SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
4431     CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4432                                    dl, ResVT, SDValue(CNode, 0), RC);
4433   }
4434 
4435   ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0));
4436   CurDAG->RemoveDeadNode(Root);
4437   return true;
4438 }
4439 
4440 // Try to match the bitselect pattern (or (and A, B), (andn A, C)). Turn it
4441 // into vpternlog.
4442 bool X86DAGToDAGISel::tryMatchBitSelect(SDNode *N) {
4443   assert(N->getOpcode() == ISD::OR && "Unexpected opcode!");
4444 
4445   MVT NVT = N->getSimpleValueType(0);
4446 
4447   // Make sure we support VPTERNLOG.
4448   if (!NVT.isVector() || !Subtarget->hasAVX512())
4449     return false;
4450 
4451   // We need VLX for 128/256-bit.
4452   if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
4453     return false;
4454 
4455   SDValue N0 = N->getOperand(0);
4456   SDValue N1 = N->getOperand(1);
4457 
4458   // Canonicalize AND to LHS.
4459   if (N1.getOpcode() == ISD::AND)
4460     std::swap(N0, N1);
4461 
4462   if (N0.getOpcode() != ISD::AND ||
4463       N1.getOpcode() != X86ISD::ANDNP ||
4464       !N0.hasOneUse() || !N1.hasOneUse())
4465     return false;
4466 
4467   // ANDN is not commutable, use it to pick down A and C.
4468   SDValue A = N1.getOperand(0);
4469   SDValue C = N1.getOperand(1);
4470 
4471   // AND is commutable, if one operand matches A, the other operand is B.
4472   // Otherwise this isn't a match.
4473   SDValue B;
4474   if (N0.getOperand(0) == A)
4475     B = N0.getOperand(1);
4476   else if (N0.getOperand(1) == A)
4477     B = N0.getOperand(0);
4478   else
4479     return false;
4480 
4481   SDLoc dl(N);
4482   SDValue Imm = CurDAG->getTargetConstant(0xCA, dl, MVT::i8);
4483   SDValue Ternlog = CurDAG->getNode(X86ISD::VPTERNLOG, dl, NVT, A, B, C, Imm);
4484   ReplaceNode(N, Ternlog.getNode());
4485   SelectCode(Ternlog.getNode());
4486   return true;
4487 }
4488 
4489 void X86DAGToDAGISel::Select(SDNode *Node) {
4490   MVT NVT = Node->getSimpleValueType(0);
4491   unsigned Opcode = Node->getOpcode();
4492   SDLoc dl(Node);
4493 
4494   if (Node->isMachineOpcode()) {
4495     LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
4496     Node->setNodeId(-1);
4497     return;   // Already selected.
4498   }
4499 
4500   switch (Opcode) {
4501   default: break;
4502   case ISD::INTRINSIC_VOID: {
4503     unsigned IntNo = Node->getConstantOperandVal(1);
4504     switch (IntNo) {
4505     default: break;
4506     case Intrinsic::x86_sse3_monitor:
4507     case Intrinsic::x86_monitorx:
4508     case Intrinsic::x86_clzero: {
4509       bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64;
4510 
4511       unsigned Opc = 0;
4512       switch (IntNo) {
4513       default: llvm_unreachable("Unexpected intrinsic!");
4514       case Intrinsic::x86_sse3_monitor:
4515         if (!Subtarget->hasSSE3())
4516           break;
4517         Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr;
4518         break;
4519       case Intrinsic::x86_monitorx:
4520         if (!Subtarget->hasMWAITX())
4521           break;
4522         Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr;
4523         break;
4524       case Intrinsic::x86_clzero:
4525         if (!Subtarget->hasCLZERO())
4526           break;
4527         Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r;
4528         break;
4529       }
4530 
4531       if (Opc) {
4532         unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX;
4533         SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg,
4534                                              Node->getOperand(2), SDValue());
4535         SDValue InFlag = Chain.getValue(1);
4536 
4537         if (IntNo == Intrinsic::x86_sse3_monitor ||
4538             IntNo == Intrinsic::x86_monitorx) {
4539           // Copy the other two operands to ECX and EDX.
4540           Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3),
4541                                        InFlag);
4542           InFlag = Chain.getValue(1);
4543           Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4),
4544                                        InFlag);
4545           InFlag = Chain.getValue(1);
4546         }
4547 
4548         MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
4549                                                       { Chain, InFlag});
4550         ReplaceNode(Node, CNode);
4551         return;
4552       }
4553 
4554       break;
4555     }
4556     }
4557 
4558     break;
4559   }
4560   case ISD::BRIND: {
4561     if (Subtarget->isTargetNaCl())
4562       // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We
4563       // leave the instruction alone.
4564       break;
4565     if (Subtarget->isTarget64BitILP32()) {
4566       // Converts a 32-bit register to a 64-bit, zero-extended version of
4567       // it. This is needed because x86-64 can do many things, but jmp %r32
4568       // ain't one of them.
4569       SDValue Target = Node->getOperand(1);
4570       assert(Target.getValueType() == MVT::i32 && "Unexpected VT!");
4571       SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, MVT::i64);
4572       SDValue Brind = CurDAG->getNode(ISD::BRIND, dl, MVT::Other,
4573                                       Node->getOperand(0), ZextTarget);
4574       ReplaceNode(Node, Brind.getNode());
4575       SelectCode(ZextTarget.getNode());
4576       SelectCode(Brind.getNode());
4577       return;
4578     }
4579     break;
4580   }
4581   case X86ISD::GlobalBaseReg:
4582     ReplaceNode(Node, getGlobalBaseReg());
4583     return;
4584 
4585   case ISD::BITCAST:
4586     // Just drop all 128/256/512-bit bitcasts.
4587     if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() ||
4588         NVT == MVT::f128) {
4589       ReplaceUses(SDValue(Node, 0), Node->getOperand(0));
4590       CurDAG->RemoveDeadNode(Node);
4591       return;
4592     }
4593     break;
4594 
4595   case ISD::SRL:
4596     if (matchBitExtract(Node))
4597       return;
4598     LLVM_FALLTHROUGH;
4599   case ISD::SRA:
4600   case ISD::SHL:
4601     if (tryShiftAmountMod(Node))
4602       return;
4603     break;
4604 
4605   case ISD::AND:
4606     if (NVT.isVector() && NVT.getVectorElementType() == MVT::i1) {
4607       // Try to form a masked VPTESTM. Operands can be in either order.
4608       SDValue N0 = Node->getOperand(0);
4609       SDValue N1 = Node->getOperand(1);
4610       if (N0.getOpcode() == ISD::SETCC && N0.hasOneUse() &&
4611           tryVPTESTM(Node, N0, N1))
4612         return;
4613       if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse() &&
4614           tryVPTESTM(Node, N1, N0))
4615         return;
4616     }
4617 
4618     if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) {
4619       ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
4620       CurDAG->RemoveDeadNode(Node);
4621       return;
4622     }
4623     if (matchBitExtract(Node))
4624       return;
4625     if (AndImmShrink && shrinkAndImmediate(Node))
4626       return;
4627 
4628     LLVM_FALLTHROUGH;
4629   case ISD::OR:
4630   case ISD::XOR:
4631     if (tryShrinkShlLogicImm(Node))
4632       return;
4633 
4634     if (Opcode == ISD::OR && tryMatchBitSelect(Node))
4635       return;
4636 
4637     LLVM_FALLTHROUGH;
4638   case ISD::ADD:
4639   case ISD::SUB: {
4640     // Try to avoid folding immediates with multiple uses for optsize.
4641     // This code tries to select to register form directly to avoid going
4642     // through the isel table which might fold the immediate. We can't change
4643     // the patterns on the add/sub/and/or/xor with immediate paterns in the
4644     // tablegen files to check immediate use count without making the patterns
4645     // unavailable to the fast-isel table.
4646     if (!OptForSize)
4647       break;
4648 
4649     // Only handle i8/i16/i32/i64.
4650     if (NVT != MVT::i8 && NVT != MVT::i16 && NVT != MVT::i32 && NVT != MVT::i64)
4651       break;
4652 
4653     SDValue N0 = Node->getOperand(0);
4654     SDValue N1 = Node->getOperand(1);
4655 
4656     ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(N1);
4657     if (!Cst)
4658       break;
4659 
4660     int64_t Val = Cst->getSExtValue();
4661 
4662     // Make sure its an immediate that is considered foldable.
4663     // FIXME: Handle unsigned 32 bit immediates for 64-bit AND.
4664     if (!isInt<8>(Val) && !isInt<32>(Val))
4665       break;
4666 
4667     // If this can match to INC/DEC, let it go.
4668     if (Opcode == ISD::ADD && (Val == 1 || Val == -1))
4669       break;
4670 
4671     // Check if we should avoid folding this immediate.
4672     if (!shouldAvoidImmediateInstFormsForSize(N1.getNode()))
4673       break;
4674 
4675     // We should not fold the immediate. So we need a register form instead.
4676     unsigned ROpc, MOpc;
4677     switch (NVT.SimpleTy) {
4678     default: llvm_unreachable("Unexpected VT!");
4679     case MVT::i8:
4680       switch (Opcode) {
4681       default: llvm_unreachable("Unexpected opcode!");
4682       case ISD::ADD: ROpc = X86::ADD8rr; MOpc = X86::ADD8rm; break;
4683       case ISD::SUB: ROpc = X86::SUB8rr; MOpc = X86::SUB8rm; break;
4684       case ISD::AND: ROpc = X86::AND8rr; MOpc = X86::AND8rm; break;
4685       case ISD::OR:  ROpc = X86::OR8rr;  MOpc = X86::OR8rm;  break;
4686       case ISD::XOR: ROpc = X86::XOR8rr; MOpc = X86::XOR8rm; break;
4687       }
4688       break;
4689     case MVT::i16:
4690       switch (Opcode) {
4691       default: llvm_unreachable("Unexpected opcode!");
4692       case ISD::ADD: ROpc = X86::ADD16rr; MOpc = X86::ADD16rm; break;
4693       case ISD::SUB: ROpc = X86::SUB16rr; MOpc = X86::SUB16rm; break;
4694       case ISD::AND: ROpc = X86::AND16rr; MOpc = X86::AND16rm; break;
4695       case ISD::OR:  ROpc = X86::OR16rr;  MOpc = X86::OR16rm;  break;
4696       case ISD::XOR: ROpc = X86::XOR16rr; MOpc = X86::XOR16rm; break;
4697       }
4698       break;
4699     case MVT::i32:
4700       switch (Opcode) {
4701       default: llvm_unreachable("Unexpected opcode!");
4702       case ISD::ADD: ROpc = X86::ADD32rr; MOpc = X86::ADD32rm; break;
4703       case ISD::SUB: ROpc = X86::SUB32rr; MOpc = X86::SUB32rm; break;
4704       case ISD::AND: ROpc = X86::AND32rr; MOpc = X86::AND32rm; break;
4705       case ISD::OR:  ROpc = X86::OR32rr;  MOpc = X86::OR32rm;  break;
4706       case ISD::XOR: ROpc = X86::XOR32rr; MOpc = X86::XOR32rm; break;
4707       }
4708       break;
4709     case MVT::i64:
4710       switch (Opcode) {
4711       default: llvm_unreachable("Unexpected opcode!");
4712       case ISD::ADD: ROpc = X86::ADD64rr; MOpc = X86::ADD64rm; break;
4713       case ISD::SUB: ROpc = X86::SUB64rr; MOpc = X86::SUB64rm; break;
4714       case ISD::AND: ROpc = X86::AND64rr; MOpc = X86::AND64rm; break;
4715       case ISD::OR:  ROpc = X86::OR64rr;  MOpc = X86::OR64rm;  break;
4716       case ISD::XOR: ROpc = X86::XOR64rr; MOpc = X86::XOR64rm; break;
4717       }
4718       break;
4719     }
4720 
4721     // Ok this is a AND/OR/XOR/ADD/SUB with constant.
4722 
4723     // If this is a not a subtract, we can still try to fold a load.
4724     if (Opcode != ISD::SUB) {
4725       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4726       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4727         SDValue Ops[] = { N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
4728         SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
4729         MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4730         // Update the chain.
4731         ReplaceUses(N0.getValue(1), SDValue(CNode, 2));
4732         // Record the mem-refs
4733         CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N0)->getMemOperand()});
4734         ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4735         CurDAG->RemoveDeadNode(Node);
4736         return;
4737       }
4738     }
4739 
4740     CurDAG->SelectNodeTo(Node, ROpc, NVT, MVT::i32, N0, N1);
4741     return;
4742   }
4743 
4744   case X86ISD::SMUL:
4745     // i16/i32/i64 are handled with isel patterns.
4746     if (NVT != MVT::i8)
4747       break;
4748     LLVM_FALLTHROUGH;
4749   case X86ISD::UMUL: {
4750     SDValue N0 = Node->getOperand(0);
4751     SDValue N1 = Node->getOperand(1);
4752 
4753     unsigned LoReg, ROpc, MOpc;
4754     switch (NVT.SimpleTy) {
4755     default: llvm_unreachable("Unsupported VT!");
4756     case MVT::i8:
4757       LoReg = X86::AL;
4758       ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r;
4759       MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m;
4760       break;
4761     case MVT::i16:
4762       LoReg = X86::AX;
4763       ROpc = X86::MUL16r;
4764       MOpc = X86::MUL16m;
4765       break;
4766     case MVT::i32:
4767       LoReg = X86::EAX;
4768       ROpc = X86::MUL32r;
4769       MOpc = X86::MUL32m;
4770       break;
4771     case MVT::i64:
4772       LoReg = X86::RAX;
4773       ROpc = X86::MUL64r;
4774       MOpc = X86::MUL64m;
4775       break;
4776     }
4777 
4778     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4779     bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4780     // Multiply is commmutative.
4781     if (!FoldedLoad) {
4782       FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4783       if (FoldedLoad)
4784         std::swap(N0, N1);
4785     }
4786 
4787     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
4788                                           N0, SDValue()).getValue(1);
4789 
4790     MachineSDNode *CNode;
4791     if (FoldedLoad) {
4792       // i16/i32/i64 use an instruction that produces a low and high result even
4793       // though only the low result is used.
4794       SDVTList VTs;
4795       if (NVT == MVT::i8)
4796         VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
4797       else
4798         VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other);
4799 
4800       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
4801                         InFlag };
4802       CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4803 
4804       // Update the chain.
4805       ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3));
4806       // Record the mem-refs
4807       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
4808     } else {
4809       // i16/i32/i64 use an instruction that produces a low and high result even
4810       // though only the low result is used.
4811       SDVTList VTs;
4812       if (NVT == MVT::i8)
4813         VTs = CurDAG->getVTList(NVT, MVT::i32);
4814       else
4815         VTs = CurDAG->getVTList(NVT, NVT, MVT::i32);
4816 
4817       CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InFlag});
4818     }
4819 
4820     ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
4821     ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2));
4822     CurDAG->RemoveDeadNode(Node);
4823     return;
4824   }
4825 
4826   case ISD::SMUL_LOHI:
4827   case ISD::UMUL_LOHI: {
4828     SDValue N0 = Node->getOperand(0);
4829     SDValue N1 = Node->getOperand(1);
4830 
4831     unsigned Opc, MOpc;
4832     unsigned LoReg, HiReg;
4833     bool IsSigned = Opcode == ISD::SMUL_LOHI;
4834     switch (NVT.SimpleTy) {
4835     default: llvm_unreachable("Unsupported VT!");
4836     case MVT::i32:
4837       Opc  = IsSigned ? X86::IMUL32r : X86::MUL32r;
4838       MOpc = IsSigned ? X86::IMUL32m : X86::MUL32m;
4839       LoReg = X86::EAX; HiReg = X86::EDX;
4840       break;
4841     case MVT::i64:
4842       Opc  = IsSigned ? X86::IMUL64r : X86::MUL64r;
4843       MOpc = IsSigned ? X86::IMUL64m : X86::MUL64m;
4844       LoReg = X86::RAX; HiReg = X86::RDX;
4845       break;
4846     }
4847 
4848     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4849     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4850     // Multiply is commmutative.
4851     if (!foldedLoad) {
4852       foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4853       if (foldedLoad)
4854         std::swap(N0, N1);
4855     }
4856 
4857     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg,
4858                                           N0, SDValue()).getValue(1);
4859     if (foldedLoad) {
4860       SDValue Chain;
4861       MachineSDNode *CNode = nullptr;
4862       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
4863                         InFlag };
4864       SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue);
4865       CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
4866       Chain = SDValue(CNode, 0);
4867       InFlag = SDValue(CNode, 1);
4868 
4869       // Update the chain.
4870       ReplaceUses(N1.getValue(1), Chain);
4871       // Record the mem-refs
4872       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
4873     } else {
4874       SDValue Ops[] = { N1, InFlag };
4875       SDVTList VTs = CurDAG->getVTList(MVT::Glue);
4876       SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4877       InFlag = SDValue(CNode, 0);
4878     }
4879 
4880     // Copy the low half of the result, if it is needed.
4881     if (!SDValue(Node, 0).use_empty()) {
4882       assert(LoReg && "Register for low half is not defined!");
4883       SDValue ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg,
4884                                              NVT, InFlag);
4885       InFlag = ResLo.getValue(2);
4886       ReplaceUses(SDValue(Node, 0), ResLo);
4887       LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG);
4888                  dbgs() << '\n');
4889     }
4890     // Copy the high half of the result, if it is needed.
4891     if (!SDValue(Node, 1).use_empty()) {
4892       assert(HiReg && "Register for high half is not defined!");
4893       SDValue ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg,
4894                                              NVT, InFlag);
4895       InFlag = ResHi.getValue(2);
4896       ReplaceUses(SDValue(Node, 1), ResHi);
4897       LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG);
4898                  dbgs() << '\n');
4899     }
4900 
4901     CurDAG->RemoveDeadNode(Node);
4902     return;
4903   }
4904 
4905   case ISD::SDIVREM:
4906   case ISD::UDIVREM: {
4907     SDValue N0 = Node->getOperand(0);
4908     SDValue N1 = Node->getOperand(1);
4909 
4910     unsigned ROpc, MOpc;
4911     bool isSigned = Opcode == ISD::SDIVREM;
4912     if (!isSigned) {
4913       switch (NVT.SimpleTy) {
4914       default: llvm_unreachable("Unsupported VT!");
4915       case MVT::i8:  ROpc = X86::DIV8r;  MOpc = X86::DIV8m;  break;
4916       case MVT::i16: ROpc = X86::DIV16r; MOpc = X86::DIV16m; break;
4917       case MVT::i32: ROpc = X86::DIV32r; MOpc = X86::DIV32m; break;
4918       case MVT::i64: ROpc = X86::DIV64r; MOpc = X86::DIV64m; break;
4919       }
4920     } else {
4921       switch (NVT.SimpleTy) {
4922       default: llvm_unreachable("Unsupported VT!");
4923       case MVT::i8:  ROpc = X86::IDIV8r;  MOpc = X86::IDIV8m;  break;
4924       case MVT::i16: ROpc = X86::IDIV16r; MOpc = X86::IDIV16m; break;
4925       case MVT::i32: ROpc = X86::IDIV32r; MOpc = X86::IDIV32m; break;
4926       case MVT::i64: ROpc = X86::IDIV64r; MOpc = X86::IDIV64m; break;
4927       }
4928     }
4929 
4930     unsigned LoReg, HiReg, ClrReg;
4931     unsigned SExtOpcode;
4932     switch (NVT.SimpleTy) {
4933     default: llvm_unreachable("Unsupported VT!");
4934     case MVT::i8:
4935       LoReg = X86::AL;  ClrReg = HiReg = X86::AH;
4936       SExtOpcode = 0; // Not used.
4937       break;
4938     case MVT::i16:
4939       LoReg = X86::AX;  HiReg = X86::DX;
4940       ClrReg = X86::DX;
4941       SExtOpcode = X86::CWD;
4942       break;
4943     case MVT::i32:
4944       LoReg = X86::EAX; ClrReg = HiReg = X86::EDX;
4945       SExtOpcode = X86::CDQ;
4946       break;
4947     case MVT::i64:
4948       LoReg = X86::RAX; ClrReg = HiReg = X86::RDX;
4949       SExtOpcode = X86::CQO;
4950       break;
4951     }
4952 
4953     SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4954     bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4);
4955     bool signBitIsZero = CurDAG->SignBitIsZero(N0);
4956 
4957     SDValue InFlag;
4958     if (NVT == MVT::i8) {
4959       // Special case for div8, just use a move with zero extension to AX to
4960       // clear the upper 8 bits (AH).
4961       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain;
4962       MachineSDNode *Move;
4963       if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4964         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) };
4965         unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rm8
4966                                                     : X86::MOVZX16rm8;
4967         Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, MVT::Other, Ops);
4968         Chain = SDValue(Move, 1);
4969         ReplaceUses(N0.getValue(1), Chain);
4970         // Record the mem-refs
4971         CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()});
4972       } else {
4973         unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rr8
4974                                                     : X86::MOVZX16rr8;
4975         Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, N0);
4976         Chain = CurDAG->getEntryNode();
4977       }
4978       Chain  = CurDAG->getCopyToReg(Chain, dl, X86::AX, SDValue(Move, 0),
4979                                     SDValue());
4980       InFlag = Chain.getValue(1);
4981     } else {
4982       InFlag =
4983         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl,
4984                              LoReg, N0, SDValue()).getValue(1);
4985       if (isSigned && !signBitIsZero) {
4986         // Sign extend the low part into the high part.
4987         InFlag =
4988           SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InFlag),0);
4989       } else {
4990         // Zero out the high part, effectively zero extending the input.
4991         SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
4992         SDValue ClrNode =
4993             SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, None), 0);
4994         switch (NVT.SimpleTy) {
4995         case MVT::i16:
4996           ClrNode =
4997               SDValue(CurDAG->getMachineNode(
4998                           TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode,
4999                           CurDAG->getTargetConstant(X86::sub_16bit, dl,
5000                                                     MVT::i32)),
5001                       0);
5002           break;
5003         case MVT::i32:
5004           break;
5005         case MVT::i64:
5006           ClrNode =
5007               SDValue(CurDAG->getMachineNode(
5008                           TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
5009                           CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode,
5010                           CurDAG->getTargetConstant(X86::sub_32bit, dl,
5011                                                     MVT::i32)),
5012                       0);
5013           break;
5014         default:
5015           llvm_unreachable("Unexpected division source");
5016         }
5017 
5018         InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg,
5019                                       ClrNode, InFlag).getValue(1);
5020       }
5021     }
5022 
5023     if (foldedLoad) {
5024       SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0),
5025                         InFlag };
5026       MachineSDNode *CNode =
5027         CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops);
5028       InFlag = SDValue(CNode, 1);
5029       // Update the chain.
5030       ReplaceUses(N1.getValue(1), SDValue(CNode, 0));
5031       // Record the mem-refs
5032       CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
5033     } else {
5034       InFlag =
5035         SDValue(CurDAG->getMachineNode(ROpc, dl, MVT::Glue, N1, InFlag), 0);
5036     }
5037 
5038     // Prevent use of AH in a REX instruction by explicitly copying it to
5039     // an ABCD_L register.
5040     //
5041     // The current assumption of the register allocator is that isel
5042     // won't generate explicit references to the GR8_ABCD_H registers. If
5043     // the allocator and/or the backend get enhanced to be more robust in
5044     // that regard, this can be, and should be, removed.
5045     if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) {
5046       SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8);
5047       unsigned AHExtOpcode =
5048           isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX;
5049 
5050       SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32,
5051                                              MVT::Glue, AHCopy, InFlag);
5052       SDValue Result(RNode, 0);
5053       InFlag = SDValue(RNode, 1);
5054 
5055       Result =
5056           CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result);
5057 
5058       ReplaceUses(SDValue(Node, 1), Result);
5059       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
5060                  dbgs() << '\n');
5061     }
5062     // Copy the division (low) result, if it is needed.
5063     if (!SDValue(Node, 0).use_empty()) {
5064       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
5065                                                 LoReg, NVT, InFlag);
5066       InFlag = Result.getValue(2);
5067       ReplaceUses(SDValue(Node, 0), Result);
5068       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
5069                  dbgs() << '\n');
5070     }
5071     // Copy the remainder (high) result, if it is needed.
5072     if (!SDValue(Node, 1).use_empty()) {
5073       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
5074                                               HiReg, NVT, InFlag);
5075       InFlag = Result.getValue(2);
5076       ReplaceUses(SDValue(Node, 1), Result);
5077       LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG);
5078                  dbgs() << '\n');
5079     }
5080     CurDAG->RemoveDeadNode(Node);
5081     return;
5082   }
5083 
5084   case X86ISD::FCMP:
5085   case X86ISD::STRICT_FCMP:
5086   case X86ISD::STRICT_FCMPS: {
5087     bool IsStrictCmp = Node->getOpcode() == X86ISD::STRICT_FCMP ||
5088                        Node->getOpcode() == X86ISD::STRICT_FCMPS;
5089     SDValue N0 = Node->getOperand(IsStrictCmp ? 1 : 0);
5090     SDValue N1 = Node->getOperand(IsStrictCmp ? 2 : 1);
5091 
5092     // Save the original VT of the compare.
5093     MVT CmpVT = N0.getSimpleValueType();
5094 
5095     // Floating point needs special handling if we don't have FCOMI.
5096     if (Subtarget->hasCMov())
5097       break;
5098 
5099     bool IsSignaling = Node->getOpcode() == X86ISD::STRICT_FCMPS;
5100 
5101     unsigned Opc;
5102     switch (CmpVT.SimpleTy) {
5103     default: llvm_unreachable("Unexpected type!");
5104     case MVT::f32:
5105       Opc = IsSignaling ? X86::COM_Fpr32 : X86::UCOM_Fpr32;
5106       break;
5107     case MVT::f64:
5108       Opc = IsSignaling ? X86::COM_Fpr64 : X86::UCOM_Fpr64;
5109       break;
5110     case MVT::f80:
5111       Opc = IsSignaling ? X86::COM_Fpr80 : X86::UCOM_Fpr80;
5112       break;
5113     }
5114 
5115     SDValue Cmp;
5116     SDValue Chain =
5117         IsStrictCmp ? Node->getOperand(0) : CurDAG->getEntryNode();
5118     if (IsStrictCmp) {
5119       SDVTList VTs = CurDAG->getVTList(MVT::i16, MVT::Other);
5120       Cmp = SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {N0, N1, Chain}), 0);
5121       Chain = Cmp.getValue(1);
5122     } else {
5123       Cmp = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i16, N0, N1), 0);
5124     }
5125 
5126     // Move FPSW to AX.
5127     SDValue FPSW = CurDAG->getCopyToReg(Chain, dl, X86::FPSW, Cmp, SDValue());
5128     Chain = FPSW;
5129     SDValue FNSTSW =
5130         SDValue(CurDAG->getMachineNode(X86::FNSTSW16r, dl, MVT::i16, FPSW,
5131                                        FPSW.getValue(1)),
5132                 0);
5133 
5134     // Extract upper 8-bits of AX.
5135     SDValue Extract =
5136         CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl, MVT::i8, FNSTSW);
5137 
5138     // Move AH into flags.
5139     // Some 64-bit targets lack SAHF support, but they do support FCOMI.
5140     assert(Subtarget->hasLAHFSAHF() &&
5141            "Target doesn't support SAHF or FCOMI?");
5142     SDValue AH = CurDAG->getCopyToReg(Chain, dl, X86::AH, Extract, SDValue());
5143     Chain = AH;
5144     SDValue SAHF = SDValue(
5145         CurDAG->getMachineNode(X86::SAHF, dl, MVT::i32, AH.getValue(1)), 0);
5146 
5147     if (IsStrictCmp)
5148       ReplaceUses(SDValue(Node, 1), Chain);
5149 
5150     ReplaceUses(SDValue(Node, 0), SAHF);
5151     CurDAG->RemoveDeadNode(Node);
5152     return;
5153   }
5154 
5155   case X86ISD::CMP: {
5156     SDValue N0 = Node->getOperand(0);
5157     SDValue N1 = Node->getOperand(1);
5158 
5159     // Optimizations for TEST compares.
5160     if (!isNullConstant(N1))
5161       break;
5162 
5163     // Save the original VT of the compare.
5164     MVT CmpVT = N0.getSimpleValueType();
5165 
5166     // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed
5167     // by a test instruction. The test should be removed later by
5168     // analyzeCompare if we are using only the zero flag.
5169     // TODO: Should we check the users and use the BEXTR flags directly?
5170     if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5171       if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) {
5172         unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr
5173                                              : X86::TEST32rr;
5174         SDValue BEXTR = SDValue(NewNode, 0);
5175         NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR);
5176         ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
5177         CurDAG->RemoveDeadNode(Node);
5178         return;
5179       }
5180     }
5181 
5182     // We can peek through truncates, but we need to be careful below.
5183     if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse())
5184       N0 = N0.getOperand(0);
5185 
5186     // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to
5187     // use a smaller encoding.
5188     // Look past the truncate if CMP is the only use of it.
5189     if (N0.getOpcode() == ISD::AND &&
5190         N0.getNode()->hasOneUse() &&
5191         N0.getValueType() != MVT::i8) {
5192       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5193       if (!C) break;
5194       uint64_t Mask = C->getZExtValue();
5195 
5196       // Check if we can replace AND+IMM64 with a shift. This is possible for
5197       // masks/ like 0xFF000000 or 0x00FFFFFF and if we care only about the zero
5198       // flag.
5199       if (CmpVT == MVT::i64 && !isInt<32>(Mask) &&
5200           onlyUsesZeroFlag(SDValue(Node, 0))) {
5201         if (isMask_64(~Mask)) {
5202           unsigned TrailingZeros = countTrailingZeros(Mask);
5203           SDValue Imm = CurDAG->getTargetConstant(TrailingZeros, dl, MVT::i64);
5204           SDValue Shift =
5205             SDValue(CurDAG->getMachineNode(X86::SHR64ri, dl, MVT::i64, MVT::i32,
5206                                            N0.getOperand(0), Imm), 0);
5207           MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl,
5208                                                        MVT::i32, Shift, Shift);
5209           ReplaceNode(Node, Test);
5210           return;
5211         }
5212         if (isMask_64(Mask)) {
5213           unsigned LeadingZeros = countLeadingZeros(Mask);
5214           SDValue Imm = CurDAG->getTargetConstant(LeadingZeros, dl, MVT::i64);
5215           SDValue Shift =
5216             SDValue(CurDAG->getMachineNode(X86::SHL64ri, dl, MVT::i64, MVT::i32,
5217                                            N0.getOperand(0), Imm), 0);
5218           MachineSDNode *Test = CurDAG->getMachineNode(X86::TEST64rr, dl,
5219                                                        MVT::i32, Shift, Shift);
5220           ReplaceNode(Node, Test);
5221           return;
5222         }
5223       }
5224 
5225       MVT VT;
5226       int SubRegOp;
5227       unsigned ROpc, MOpc;
5228 
5229       // For each of these checks we need to be careful if the sign flag is
5230       // being used. It is only safe to use the sign flag in two conditions,
5231       // either the sign bit in the shrunken mask is zero or the final test
5232       // size is equal to the original compare size.
5233 
5234       if (isUInt<8>(Mask) &&
5235           (!(Mask & 0x80) || CmpVT == MVT::i8 ||
5236            hasNoSignFlagUses(SDValue(Node, 0)))) {
5237         // For example, convert "testl %eax, $8" to "testb %al, $8"
5238         VT = MVT::i8;
5239         SubRegOp = X86::sub_8bit;
5240         ROpc = X86::TEST8ri;
5241         MOpc = X86::TEST8mi;
5242       } else if (OptForMinSize && isUInt<16>(Mask) &&
5243                  (!(Mask & 0x8000) || CmpVT == MVT::i16 ||
5244                   hasNoSignFlagUses(SDValue(Node, 0)))) {
5245         // For example, "testl %eax, $32776" to "testw %ax, $32776".
5246         // NOTE: We only want to form TESTW instructions if optimizing for
5247         // min size. Otherwise we only save one byte and possibly get a length
5248         // changing prefix penalty in the decoders.
5249         VT = MVT::i16;
5250         SubRegOp = X86::sub_16bit;
5251         ROpc = X86::TEST16ri;
5252         MOpc = X86::TEST16mi;
5253       } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 &&
5254                  ((!(Mask & 0x80000000) &&
5255                    // Without minsize 16-bit Cmps can get here so we need to
5256                    // be sure we calculate the correct sign flag if needed.
5257                    (CmpVT != MVT::i16 || !(Mask & 0x8000))) ||
5258                   CmpVT == MVT::i32 ||
5259                   hasNoSignFlagUses(SDValue(Node, 0)))) {
5260         // For example, "testq %rax, $268468232" to "testl %eax, $268468232".
5261         // NOTE: We only want to run that transform if N0 is 32 or 64 bits.
5262         // Otherwize, we find ourselves in a position where we have to do
5263         // promotion. If previous passes did not promote the and, we assume
5264         // they had a good reason not to and do not promote here.
5265         VT = MVT::i32;
5266         SubRegOp = X86::sub_32bit;
5267         ROpc = X86::TEST32ri;
5268         MOpc = X86::TEST32mi;
5269       } else {
5270         // No eligible transformation was found.
5271         break;
5272       }
5273 
5274       SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT);
5275       SDValue Reg = N0.getOperand(0);
5276 
5277       // Emit a testl or testw.
5278       MachineSDNode *NewNode;
5279       SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
5280       if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
5281         if (auto *LoadN = dyn_cast<LoadSDNode>(N0.getOperand(0).getNode())) {
5282           if (!LoadN->isSimple()) {
5283             unsigned NumVolBits = LoadN->getValueType(0).getSizeInBits();
5284             if (MOpc == X86::TEST8mi && NumVolBits != 8)
5285               break;
5286             else if (MOpc == X86::TEST16mi && NumVolBits != 16)
5287               break;
5288             else if (MOpc == X86::TEST32mi && NumVolBits != 32)
5289               break;
5290           }
5291         }
5292         SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
5293                           Reg.getOperand(0) };
5294         NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops);
5295         // Update the chain.
5296         ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1));
5297         // Record the mem-refs
5298         CurDAG->setNodeMemRefs(NewNode,
5299                                {cast<LoadSDNode>(Reg)->getMemOperand()});
5300       } else {
5301         // Extract the subregister if necessary.
5302         if (N0.getValueType() != VT)
5303           Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg);
5304 
5305         NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm);
5306       }
5307       // Replace CMP with TEST.
5308       ReplaceNode(Node, NewNode);
5309       return;
5310     }
5311     break;
5312   }
5313   case X86ISD::PCMPISTR: {
5314     if (!Subtarget->hasSSE42())
5315       break;
5316 
5317     bool NeedIndex = !SDValue(Node, 0).use_empty();
5318     bool NeedMask = !SDValue(Node, 1).use_empty();
5319     // We can't fold a load if we are going to make two instructions.
5320     bool MayFoldLoad = !NeedIndex || !NeedMask;
5321 
5322     MachineSDNode *CNode;
5323     if (NeedMask) {
5324       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr;
5325       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm;
5326       CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node);
5327       ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
5328     }
5329     if (NeedIndex || !NeedMask) {
5330       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr;
5331       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm;
5332       CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node);
5333       ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
5334     }
5335 
5336     // Connect the flag usage to the last instruction created.
5337     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
5338     CurDAG->RemoveDeadNode(Node);
5339     return;
5340   }
5341   case X86ISD::PCMPESTR: {
5342     if (!Subtarget->hasSSE42())
5343       break;
5344 
5345     // Copy the two implicit register inputs.
5346     SDValue InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX,
5347                                           Node->getOperand(1),
5348                                           SDValue()).getValue(1);
5349     InFlag = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX,
5350                                   Node->getOperand(3), InFlag).getValue(1);
5351 
5352     bool NeedIndex = !SDValue(Node, 0).use_empty();
5353     bool NeedMask = !SDValue(Node, 1).use_empty();
5354     // We can't fold a load if we are going to make two instructions.
5355     bool MayFoldLoad = !NeedIndex || !NeedMask;
5356 
5357     MachineSDNode *CNode;
5358     if (NeedMask) {
5359       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr;
5360       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm;
5361       CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node,
5362                            InFlag);
5363       ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0));
5364     }
5365     if (NeedIndex || !NeedMask) {
5366       unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr;
5367       unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm;
5368       CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InFlag);
5369       ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0));
5370     }
5371     // Connect the flag usage to the last instruction created.
5372     ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1));
5373     CurDAG->RemoveDeadNode(Node);
5374     return;
5375   }
5376 
5377   case ISD::SETCC: {
5378     if (NVT.isVector() && tryVPTESTM(Node, SDValue(Node, 0), SDValue()))
5379       return;
5380 
5381     break;
5382   }
5383 
5384   case ISD::STORE:
5385     if (foldLoadStoreIntoMemOperand(Node))
5386       return;
5387     break;
5388 
5389   case X86ISD::SETCC_CARRY: {
5390     // We have to do this manually because tblgen will put the eflags copy in
5391     // the wrong place if we use an extract_subreg in the pattern.
5392     MVT VT = Node->getSimpleValueType(0);
5393 
5394     // Copy flags to the EFLAGS register and glue it to next node.
5395     SDValue EFLAGS =
5396         CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
5397                              Node->getOperand(1), SDValue());
5398 
5399     // Create a 64-bit instruction if the result is 64-bits otherwise use the
5400     // 32-bit version.
5401     unsigned Opc = VT == MVT::i64 ? X86::SETB_C64r : X86::SETB_C32r;
5402     MVT SetVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
5403     SDValue Result = SDValue(
5404         CurDAG->getMachineNode(Opc, dl, SetVT, EFLAGS, EFLAGS.getValue(1)), 0);
5405 
5406     // For less than 32-bits we need to extract from the 32-bit node.
5407     if (VT == MVT::i8 || VT == MVT::i16) {
5408       int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;
5409       Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);
5410     }
5411 
5412     ReplaceUses(SDValue(Node, 0), Result);
5413     CurDAG->RemoveDeadNode(Node);
5414     return;
5415   }
5416   case X86ISD::SBB: {
5417     if (isNullConstant(Node->getOperand(0)) &&
5418         isNullConstant(Node->getOperand(1))) {
5419       MVT VT = Node->getSimpleValueType(0);
5420 
5421       // Create zero.
5422       SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
5423       SDValue Zero =
5424           SDValue(CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, None), 0);
5425       if (VT == MVT::i64) {
5426         Zero = SDValue(
5427             CurDAG->getMachineNode(
5428                 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
5429                 CurDAG->getTargetConstant(0, dl, MVT::i64), Zero,
5430                 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
5431             0);
5432       }
5433 
5434       // Copy flags to the EFLAGS register and glue it to next node.
5435       SDValue EFLAGS =
5436           CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
5437                                Node->getOperand(2), SDValue());
5438 
5439       // Create a 64-bit instruction if the result is 64-bits otherwise use the
5440       // 32-bit version.
5441       unsigned Opc = VT == MVT::i64 ? X86::SBB64rr : X86::SBB32rr;
5442       MVT SBBVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
5443       VTs = CurDAG->getVTList(SBBVT, MVT::i32);
5444       SDValue Result =
5445           SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {Zero, Zero, EFLAGS,
5446                                          EFLAGS.getValue(1)}),
5447                   0);
5448 
5449       // Replace the flag use.
5450       ReplaceUses(SDValue(Node, 1), Result.getValue(1));
5451 
5452       // Replace the result use.
5453       if (!SDValue(Node, 0).use_empty()) {
5454         // For less than 32-bits we need to extract from the 32-bit node.
5455         if (VT == MVT::i8 || VT == MVT::i16) {
5456           int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit;
5457           Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result);
5458         }
5459         ReplaceUses(SDValue(Node, 0), Result);
5460       }
5461 
5462       CurDAG->RemoveDeadNode(Node);
5463       return;
5464     }
5465     break;
5466   }
5467   case X86ISD::MGATHER: {
5468     auto *Mgt = cast<X86MaskedGatherSDNode>(Node);
5469     SDValue IndexOp = Mgt->getIndex();
5470     SDValue Mask = Mgt->getMask();
5471     MVT IndexVT = IndexOp.getSimpleValueType();
5472     MVT ValueVT = Node->getSimpleValueType(0);
5473     MVT MaskVT = Mask.getSimpleValueType();
5474 
5475     // This is just to prevent crashes if the nodes are malformed somehow. We're
5476     // otherwise only doing loose type checking in here based on type what
5477     // a type constraint would say just like table based isel.
5478     if (!ValueVT.isVector() || !MaskVT.isVector())
5479       break;
5480 
5481     unsigned NumElts = ValueVT.getVectorNumElements();
5482     MVT ValueSVT = ValueVT.getVectorElementType();
5483 
5484     bool IsFP = ValueSVT.isFloatingPoint();
5485     unsigned EltSize = ValueSVT.getSizeInBits();
5486 
5487     unsigned Opc = 0;
5488     bool AVX512Gather = MaskVT.getVectorElementType() == MVT::i1;
5489     if (AVX512Gather) {
5490       if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
5491         Opc = IsFP ? X86::VGATHERDPSZ128rm : X86::VPGATHERDDZ128rm;
5492       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
5493         Opc = IsFP ? X86::VGATHERDPSZ256rm : X86::VPGATHERDDZ256rm;
5494       else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)
5495         Opc = IsFP ? X86::VGATHERDPSZrm : X86::VPGATHERDDZrm;
5496       else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
5497         Opc = IsFP ? X86::VGATHERDPDZ128rm : X86::VPGATHERDQZ128rm;
5498       else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
5499         Opc = IsFP ? X86::VGATHERDPDZ256rm : X86::VPGATHERDQZ256rm;
5500       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)
5501         Opc = IsFP ? X86::VGATHERDPDZrm : X86::VPGATHERDQZrm;
5502       else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
5503         Opc = IsFP ? X86::VGATHERQPSZ128rm : X86::VPGATHERQDZ128rm;
5504       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
5505         Opc = IsFP ? X86::VGATHERQPSZ256rm : X86::VPGATHERQDZ256rm;
5506       else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)
5507         Opc = IsFP ? X86::VGATHERQPSZrm : X86::VPGATHERQDZrm;
5508       else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
5509         Opc = IsFP ? X86::VGATHERQPDZ128rm : X86::VPGATHERQQZ128rm;
5510       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
5511         Opc = IsFP ? X86::VGATHERQPDZ256rm : X86::VPGATHERQQZ256rm;
5512       else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)
5513         Opc = IsFP ? X86::VGATHERQPDZrm : X86::VPGATHERQQZrm;
5514     } else {
5515       assert(EVT(MaskVT) == EVT(ValueVT).changeVectorElementTypeToInteger() &&
5516              "Unexpected mask VT!");
5517       if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
5518         Opc = IsFP ? X86::VGATHERDPSrm : X86::VPGATHERDDrm;
5519       else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
5520         Opc = IsFP ? X86::VGATHERDPSYrm : X86::VPGATHERDDYrm;
5521       else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
5522         Opc = IsFP ? X86::VGATHERDPDrm : X86::VPGATHERDQrm;
5523       else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
5524         Opc = IsFP ? X86::VGATHERDPDYrm : X86::VPGATHERDQYrm;
5525       else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
5526         Opc = IsFP ? X86::VGATHERQPSrm : X86::VPGATHERQDrm;
5527       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
5528         Opc = IsFP ? X86::VGATHERQPSYrm : X86::VPGATHERQDYrm;
5529       else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
5530         Opc = IsFP ? X86::VGATHERQPDrm : X86::VPGATHERQQrm;
5531       else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
5532         Opc = IsFP ? X86::VGATHERQPDYrm : X86::VPGATHERQQYrm;
5533     }
5534 
5535     if (!Opc)
5536       break;
5537 
5538     SDValue Base, Scale, Index, Disp, Segment;
5539     if (!selectVectorAddr(Mgt, Mgt->getBasePtr(), IndexOp, Mgt->getScale(),
5540                           Base, Scale, Index, Disp, Segment))
5541       break;
5542 
5543     SDValue PassThru = Mgt->getPassThru();
5544     SDValue Chain = Mgt->getChain();
5545     // Gather instructions have a mask output not in the ISD node.
5546     SDVTList VTs = CurDAG->getVTList(ValueVT, MaskVT, MVT::Other);
5547 
5548     MachineSDNode *NewNode;
5549     if (AVX512Gather) {
5550       SDValue Ops[] = {PassThru, Mask, Base,    Scale,
5551                        Index,    Disp, Segment, Chain};
5552       NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
5553     } else {
5554       SDValue Ops[] = {PassThru, Base,    Scale, Index,
5555                        Disp,     Segment, Mask,  Chain};
5556       NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
5557     }
5558     CurDAG->setNodeMemRefs(NewNode, {Mgt->getMemOperand()});
5559     ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0));
5560     ReplaceUses(SDValue(Node, 1), SDValue(NewNode, 2));
5561     CurDAG->RemoveDeadNode(Node);
5562     return;
5563   }
5564   case X86ISD::MSCATTER: {
5565     auto *Sc = cast<X86MaskedScatterSDNode>(Node);
5566     SDValue Value = Sc->getValue();
5567     SDValue IndexOp = Sc->getIndex();
5568     MVT IndexVT = IndexOp.getSimpleValueType();
5569     MVT ValueVT = Value.getSimpleValueType();
5570 
5571     // This is just to prevent crashes if the nodes are malformed somehow. We're
5572     // otherwise only doing loose type checking in here based on type what
5573     // a type constraint would say just like table based isel.
5574     if (!ValueVT.isVector())
5575       break;
5576 
5577     unsigned NumElts = ValueVT.getVectorNumElements();
5578     MVT ValueSVT = ValueVT.getVectorElementType();
5579 
5580     bool IsFP = ValueSVT.isFloatingPoint();
5581     unsigned EltSize = ValueSVT.getSizeInBits();
5582 
5583     unsigned Opc;
5584     if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32)
5585       Opc = IsFP ? X86::VSCATTERDPSZ128mr : X86::VPSCATTERDDZ128mr;
5586     else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32)
5587       Opc = IsFP ? X86::VSCATTERDPSZ256mr : X86::VPSCATTERDDZ256mr;
5588     else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32)
5589       Opc = IsFP ? X86::VSCATTERDPSZmr : X86::VPSCATTERDDZmr;
5590     else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64)
5591       Opc = IsFP ? X86::VSCATTERDPDZ128mr : X86::VPSCATTERDQZ128mr;
5592     else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64)
5593       Opc = IsFP ? X86::VSCATTERDPDZ256mr : X86::VPSCATTERDQZ256mr;
5594     else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64)
5595       Opc = IsFP ? X86::VSCATTERDPDZmr : X86::VPSCATTERDQZmr;
5596     else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32)
5597       Opc = IsFP ? X86::VSCATTERQPSZ128mr : X86::VPSCATTERQDZ128mr;
5598     else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32)
5599       Opc = IsFP ? X86::VSCATTERQPSZ256mr : X86::VPSCATTERQDZ256mr;
5600     else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32)
5601       Opc = IsFP ? X86::VSCATTERQPSZmr : X86::VPSCATTERQDZmr;
5602     else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64)
5603       Opc = IsFP ? X86::VSCATTERQPDZ128mr : X86::VPSCATTERQQZ128mr;
5604     else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64)
5605       Opc = IsFP ? X86::VSCATTERQPDZ256mr : X86::VPSCATTERQQZ256mr;
5606     else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64)
5607       Opc = IsFP ? X86::VSCATTERQPDZmr : X86::VPSCATTERQQZmr;
5608     else
5609       break;
5610 
5611     SDValue Base, Scale, Index, Disp, Segment;
5612     if (!selectVectorAddr(Sc, Sc->getBasePtr(), IndexOp, Sc->getScale(),
5613                           Base, Scale, Index, Disp, Segment))
5614       break;
5615 
5616     SDValue Mask = Sc->getMask();
5617     SDValue Chain = Sc->getChain();
5618     // Scatter instructions have a mask output not in the ISD node.
5619     SDVTList VTs = CurDAG->getVTList(Mask.getValueType(), MVT::Other);
5620     SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Mask, Value, Chain};
5621 
5622     MachineSDNode *NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops);
5623     CurDAG->setNodeMemRefs(NewNode, {Sc->getMemOperand()});
5624     ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 1));
5625     CurDAG->RemoveDeadNode(Node);
5626     return;
5627   }
5628   }
5629 
5630   SelectCode(Node);
5631 }
5632 
5633 bool X86DAGToDAGISel::
5634 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
5635                              std::vector<SDValue> &OutOps) {
5636   SDValue Op0, Op1, Op2, Op3, Op4;
5637   switch (ConstraintID) {
5638   default:
5639     llvm_unreachable("Unexpected asm memory constraint");
5640   case InlineAsm::Constraint_o: // offsetable        ??
5641   case InlineAsm::Constraint_v: // not offsetable    ??
5642   case InlineAsm::Constraint_m: // memory
5643   case InlineAsm::Constraint_X:
5644     if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4))
5645       return true;
5646     break;
5647   }
5648 
5649   OutOps.push_back(Op0);
5650   OutOps.push_back(Op1);
5651   OutOps.push_back(Op2);
5652   OutOps.push_back(Op3);
5653   OutOps.push_back(Op4);
5654   return false;
5655 }
5656 
5657 /// This pass converts a legalized DAG into a X86-specific DAG,
5658 /// ready for instruction scheduling.
5659 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM,
5660                                      CodeGenOpt::Level OptLevel) {
5661   return new X86DAGToDAGISel(TM, OptLevel);
5662 }
5663