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