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