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