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