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