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