LLVM 17.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 "X86RegisterInfo.h"
17#include "X86Subtarget.h"
18#include "X86TargetMachine.h"
19#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/Type.h"
29#include "llvm/Support/Debug.h"
33#include <cstdint>
34
35using namespace llvm;
36
37#define DEBUG_TYPE "x86-isel"
38#define PASS_NAME "X86 DAG->DAG Instruction Selection"
39
40STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor");
41
42static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true),
43 cl::desc("Enable setting constant bits to reduce size of mask immediates"),
45
47 "x86-promote-anyext-load", cl::init(true),
48 cl::desc("Enable promoting aligned anyext load to wider load"), cl::Hidden);
49
51
52//===----------------------------------------------------------------------===//
53// Pattern Matcher Implementation
54//===----------------------------------------------------------------------===//
55
56namespace {
57 /// This corresponds to X86AddressMode, but uses SDValue's instead of register
58 /// numbers for the leaves of the matched tree.
59 struct X86ISelAddressMode {
60 enum {
61 RegBase,
62 FrameIndexBase
63 } BaseType = RegBase;
64
65 // This is really a union, discriminated by BaseType!
66 SDValue Base_Reg;
67 int Base_FrameIndex = 0;
68
69 unsigned Scale = 1;
70 SDValue IndexReg;
71 int32_t Disp = 0;
72 SDValue Segment;
73 const GlobalValue *GV = nullptr;
74 const Constant *CP = nullptr;
75 const BlockAddress *BlockAddr = nullptr;
76 const char *ES = nullptr;
77 MCSymbol *MCSym = nullptr;
78 int JT = -1;
79 Align Alignment; // CP alignment.
80 unsigned char SymbolFlags = X86II::MO_NO_FLAG; // X86II::MO_*
81 bool NegateIndex = false;
82
83 X86ISelAddressMode() = default;
84
85 bool hasSymbolicDisplacement() const {
86 return GV != nullptr || CP != nullptr || ES != nullptr ||
87 MCSym != nullptr || JT != -1 || BlockAddr != nullptr;
88 }
89
90 bool hasBaseOrIndexReg() const {
91 return BaseType == FrameIndexBase ||
92 IndexReg.getNode() != nullptr || Base_Reg.getNode() != nullptr;
93 }
94
95 /// Return true if this addressing mode is already RIP-relative.
96 bool isRIPRelative() const {
97 if (BaseType != RegBase) return false;
98 if (RegisterSDNode *RegNode =
99 dyn_cast_or_null<RegisterSDNode>(Base_Reg.getNode()))
100 return RegNode->getReg() == X86::RIP;
101 return false;
102 }
103
104 void setBaseReg(SDValue Reg) {
105 BaseType = RegBase;
106 Base_Reg = Reg;
107 }
108
109#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
110 void dump(SelectionDAG *DAG = nullptr) {
111 dbgs() << "X86ISelAddressMode " << this << '\n';
112 dbgs() << "Base_Reg ";
113 if (Base_Reg.getNode())
114 Base_Reg.getNode()->dump(DAG);
115 else
116 dbgs() << "nul\n";
117 if (BaseType == FrameIndexBase)
118 dbgs() << " Base.FrameIndex " << Base_FrameIndex << '\n';
119 dbgs() << " Scale " << Scale << '\n'
120 << "IndexReg ";
121 if (NegateIndex)
122 dbgs() << "negate ";
123 if (IndexReg.getNode())
124 IndexReg.getNode()->dump(DAG);
125 else
126 dbgs() << "nul\n";
127 dbgs() << " Disp " << Disp << '\n'
128 << "GV ";
129 if (GV)
130 GV->dump();
131 else
132 dbgs() << "nul";
133 dbgs() << " CP ";
134 if (CP)
135 CP->dump();
136 else
137 dbgs() << "nul";
138 dbgs() << '\n'
139 << "ES ";
140 if (ES)
141 dbgs() << ES;
142 else
143 dbgs() << "nul";
144 dbgs() << " MCSym ";
145 if (MCSym)
146 dbgs() << MCSym;
147 else
148 dbgs() << "nul";
149 dbgs() << " JT" << JT << " Align" << Alignment.value() << '\n';
150 }
151#endif
152 };
153}
154
155namespace {
156 //===--------------------------------------------------------------------===//
157 /// ISel - X86-specific code to select X86 machine instructions for
158 /// SelectionDAG operations.
159 ///
160 class X86DAGToDAGISel final : public SelectionDAGISel {
161 /// Keep a pointer to the X86Subtarget around so that we can
162 /// make the right decision when generating code for different targets.
163 const X86Subtarget *Subtarget;
164
165 /// If true, selector should try to optimize for minimum code size.
166 bool OptForMinSize;
167
168 /// Disable direct TLS access through segment registers.
169 bool IndirectTlsSegRefs;
170
171 public:
172 static char ID;
173
174 X86DAGToDAGISel() = delete;
175
176 explicit X86DAGToDAGISel(X86TargetMachine &tm, CodeGenOpt::Level OptLevel)
177 : SelectionDAGISel(ID, tm, OptLevel), Subtarget(nullptr),
178 OptForMinSize(false), IndirectTlsSegRefs(false) {}
179
180 bool runOnMachineFunction(MachineFunction &MF) override {
181 // Reset the subtarget each time through.
182 Subtarget = &MF.getSubtarget<X86Subtarget>();
183 IndirectTlsSegRefs = MF.getFunction().hasFnAttribute(
184 "indirect-tls-seg-refs");
185
186 // OptFor[Min]Size are used in pattern predicates that isel is matching.
187 OptForMinSize = MF.getFunction().hasMinSize();
188 assert((!OptForMinSize || MF.getFunction().hasOptSize()) &&
189 "OptForMinSize implies OptForSize");
190
192 return true;
193 }
194
195 void emitFunctionEntryCode() override;
196
197 bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const override;
198
199 void PreprocessISelDAG() override;
200 void PostprocessISelDAG() override;
201
202// Include the pieces autogenerated from the target description.
203#include "X86GenDAGISel.inc"
204
205 private:
206 void Select(SDNode *N) override;
207
208 bool foldOffsetIntoAddress(uint64_t Offset, X86ISelAddressMode &AM);
209 bool matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM,
210 bool AllowSegmentRegForX32 = false);
211 bool matchWrapper(SDValue N, X86ISelAddressMode &AM);
212 bool matchAddress(SDValue N, X86ISelAddressMode &AM);
213 bool matchVectorAddress(SDValue N, X86ISelAddressMode &AM);
214 bool matchAdd(SDValue &N, X86ISelAddressMode &AM, unsigned Depth);
215 bool matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
216 unsigned Depth);
217 bool matchVectorAddressRecursively(SDValue N, X86ISelAddressMode &AM,
218 unsigned Depth);
219 bool matchAddressBase(SDValue N, X86ISelAddressMode &AM);
220 bool selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
221 SDValue &Scale, SDValue &Index, SDValue &Disp,
222 SDValue &Segment);
223 bool selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, SDValue IndexOp,
224 SDValue ScaleOp, SDValue &Base, SDValue &Scale,
225 SDValue &Index, SDValue &Disp, SDValue &Segment);
226 bool selectMOV64Imm32(SDValue N, SDValue &Imm);
227 bool selectLEAAddr(SDValue N, SDValue &Base,
228 SDValue &Scale, SDValue &Index, SDValue &Disp,
229 SDValue &Segment);
230 bool selectLEA64_32Addr(SDValue N, SDValue &Base,
231 SDValue &Scale, SDValue &Index, SDValue &Disp,
232 SDValue &Segment);
233 bool selectTLSADDRAddr(SDValue N, SDValue &Base,
234 SDValue &Scale, SDValue &Index, SDValue &Disp,
235 SDValue &Segment);
236 bool selectRelocImm(SDValue N, SDValue &Op);
237
238 bool tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
239 SDValue &Base, SDValue &Scale,
240 SDValue &Index, SDValue &Disp,
241 SDValue &Segment);
242
243 // Convenience method where P is also root.
244 bool tryFoldLoad(SDNode *P, SDValue N,
245 SDValue &Base, SDValue &Scale,
246 SDValue &Index, SDValue &Disp,
247 SDValue &Segment) {
248 return tryFoldLoad(P, P, N, Base, Scale, Index, Disp, Segment);
249 }
250
251 bool tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
252 SDValue &Base, SDValue &Scale,
253 SDValue &Index, SDValue &Disp,
254 SDValue &Segment);
255
256 bool isProfitableToFormMaskedOp(SDNode *N) const;
257
258 /// Implement addressing mode selection for inline asm expressions.
260 unsigned ConstraintID,
261 std::vector<SDValue> &OutOps) override;
262
263 void emitSpecialCodeForMain();
264
265 inline void getAddressOperands(X86ISelAddressMode &AM, const SDLoc &DL,
266 MVT VT, SDValue &Base, SDValue &Scale,
267 SDValue &Index, SDValue &Disp,
268 SDValue &Segment) {
269 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
270 Base = CurDAG->getTargetFrameIndex(
271 AM.Base_FrameIndex, TLI->getPointerTy(CurDAG->getDataLayout()));
272 else if (AM.Base_Reg.getNode())
273 Base = AM.Base_Reg;
274 else
275 Base = CurDAG->getRegister(0, VT);
276
277 Scale = getI8Imm(AM.Scale, DL);
278
279 // Negate the index if needed.
280 if (AM.NegateIndex) {
281 unsigned NegOpc = VT == MVT::i64 ? X86::NEG64r : X86::NEG32r;
282 SDValue Neg = SDValue(CurDAG->getMachineNode(NegOpc, DL, VT, MVT::i32,
283 AM.IndexReg), 0);
284 AM.IndexReg = Neg;
285 }
286
287 if (AM.IndexReg.getNode())
288 Index = AM.IndexReg;
289 else
290 Index = CurDAG->getRegister(0, VT);
291
292 // These are 32-bit even in 64-bit mode since RIP-relative offset
293 // is 32-bit.
294 if (AM.GV)
295 Disp = CurDAG->getTargetGlobalAddress(AM.GV, SDLoc(),
296 MVT::i32, AM.Disp,
297 AM.SymbolFlags);
298 else if (AM.CP)
299 Disp = CurDAG->getTargetConstantPool(AM.CP, MVT::i32, AM.Alignment,
300 AM.Disp, AM.SymbolFlags);
301 else if (AM.ES) {
302 assert(!AM.Disp && "Non-zero displacement is ignored with ES.");
303 Disp = CurDAG->getTargetExternalSymbol(AM.ES, MVT::i32, AM.SymbolFlags);
304 } else if (AM.MCSym) {
305 assert(!AM.Disp && "Non-zero displacement is ignored with MCSym.");
306 assert(AM.SymbolFlags == 0 && "oo");
307 Disp = CurDAG->getMCSymbol(AM.MCSym, MVT::i32);
308 } else if (AM.JT != -1) {
309 assert(!AM.Disp && "Non-zero displacement is ignored with JT.");
310 Disp = CurDAG->getTargetJumpTable(AM.JT, MVT::i32, AM.SymbolFlags);
311 } else if (AM.BlockAddr)
312 Disp = CurDAG->getTargetBlockAddress(AM.BlockAddr, MVT::i32, AM.Disp,
313 AM.SymbolFlags);
314 else
315 Disp = CurDAG->getTargetConstant(AM.Disp, DL, MVT::i32);
316
317 if (AM.Segment.getNode())
318 Segment = AM.Segment;
319 else
320 Segment = CurDAG->getRegister(0, MVT::i16);
321 }
322
323 // Utility function to determine whether we should avoid selecting
324 // immediate forms of instructions for better code size or not.
325 // At a high level, we'd like to avoid such instructions when
326 // we have similar constants used within the same basic block
327 // that can be kept in a register.
328 //
329 bool shouldAvoidImmediateInstFormsForSize(SDNode *N) const {
330 uint32_t UseCount = 0;
331
332 // Do not want to hoist if we're not optimizing for size.
333 // TODO: We'd like to remove this restriction.
334 // See the comment in X86InstrInfo.td for more info.
335 if (!CurDAG->shouldOptForSize())
336 return false;
337
338 // Walk all the users of the immediate.
339 for (const SDNode *User : N->uses()) {
340 if (UseCount >= 2)
341 break;
342
343 // This user is already selected. Count it as a legitimate use and
344 // move on.
345 if (User->isMachineOpcode()) {
346 UseCount++;
347 continue;
348 }
349
350 // We want to count stores of immediates as real uses.
351 if (User->getOpcode() == ISD::STORE &&
352 User->getOperand(1).getNode() == N) {
353 UseCount++;
354 continue;
355 }
356
357 // We don't currently match users that have > 2 operands (except
358 // for stores, which are handled above)
359 // Those instruction won't match in ISEL, for now, and would
360 // be counted incorrectly.
361 // This may change in the future as we add additional instruction
362 // types.
363 if (User->getNumOperands() != 2)
364 continue;
365
366 // If this is a sign-extended 8-bit integer immediate used in an ALU
367 // instruction, there is probably an opcode encoding to save space.
368 auto *C = dyn_cast<ConstantSDNode>(N);
369 if (C && isInt<8>(C->getSExtValue()))
370 continue;
371
372 // Immediates that are used for offsets as part of stack
373 // manipulation should be left alone. These are typically
374 // used to indicate SP offsets for argument passing and
375 // will get pulled into stores/pushes (implicitly).
376 if (User->getOpcode() == X86ISD::ADD ||
377 User->getOpcode() == ISD::ADD ||
378 User->getOpcode() == X86ISD::SUB ||
379 User->getOpcode() == ISD::SUB) {
380
381 // Find the other operand of the add/sub.
382 SDValue OtherOp = User->getOperand(0);
383 if (OtherOp.getNode() == N)
384 OtherOp = User->getOperand(1);
385
386 // Don't count if the other operand is SP.
387 RegisterSDNode *RegNode;
388 if (OtherOp->getOpcode() == ISD::CopyFromReg &&
389 (RegNode = dyn_cast_or_null<RegisterSDNode>(
390 OtherOp->getOperand(1).getNode())))
391 if ((RegNode->getReg() == X86::ESP) ||
392 (RegNode->getReg() == X86::RSP))
393 continue;
394 }
395
396 // ... otherwise, count this and move on.
397 UseCount++;
398 }
399
400 // If we have more than 1 use, then recommend for hoisting.
401 return (UseCount > 1);
402 }
403
404 /// Return a target constant with the specified value of type i8.
405 inline SDValue getI8Imm(unsigned Imm, const SDLoc &DL) {
406 return CurDAG->getTargetConstant(Imm, DL, MVT::i8);
407 }
408
409 /// Return a target constant with the specified value, of type i32.
410 inline SDValue getI32Imm(unsigned Imm, const SDLoc &DL) {
411 return CurDAG->getTargetConstant(Imm, DL, MVT::i32);
412 }
413
414 /// Return a target constant with the specified value, of type i64.
415 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &DL) {
416 return CurDAG->getTargetConstant(Imm, DL, MVT::i64);
417 }
418
419 SDValue getExtractVEXTRACTImmediate(SDNode *N, unsigned VecWidth,
420 const SDLoc &DL) {
421 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
422 uint64_t Index = N->getConstantOperandVal(1);
423 MVT VecVT = N->getOperand(0).getSimpleValueType();
424 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
425 }
426
427 SDValue getInsertVINSERTImmediate(SDNode *N, unsigned VecWidth,
428 const SDLoc &DL) {
429 assert((VecWidth == 128 || VecWidth == 256) && "Unexpected vector width");
430 uint64_t Index = N->getConstantOperandVal(2);
431 MVT VecVT = N->getSimpleValueType(0);
432 return getI8Imm((Index * VecVT.getScalarSizeInBits()) / VecWidth, DL);
433 }
434
435 SDValue getPermuteVINSERTCommutedImmediate(SDNode *N, unsigned VecWidth,
436 const SDLoc &DL) {
437 assert(VecWidth == 128 && "Unexpected vector width");
438 uint64_t Index = N->getConstantOperandVal(2);
439 MVT VecVT = N->getSimpleValueType(0);
440 uint64_t InsertIdx = (Index * VecVT.getScalarSizeInBits()) / VecWidth;
441 assert((InsertIdx == 0 || InsertIdx == 1) && "Bad insertf128 index");
442 // vinsert(0,sub,vec) -> [sub0][vec1] -> vperm2x128(0x30,vec,sub)
443 // vinsert(1,sub,vec) -> [vec0][sub0] -> vperm2x128(0x02,vec,sub)
444 return getI8Imm(InsertIdx ? 0x02 : 0x30, DL);
445 }
446
447 SDValue getSBBZero(SDNode *N) {
448 SDLoc dl(N);
449 MVT VT = N->getSimpleValueType(0);
450
451 // Create zero.
452 SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32);
454 CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, std::nullopt), 0);
455 if (VT == MVT::i64) {
456 Zero = SDValue(
457 CurDAG->getMachineNode(
458 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64,
459 CurDAG->getTargetConstant(0, dl, MVT::i64), Zero,
460 CurDAG->getTargetConstant(X86::sub_32bit, dl, MVT::i32)),
461 0);
462 }
463
464 // Copy flags to the EFLAGS register and glue it to next node.
465 unsigned Opcode = N->getOpcode();
466 assert((Opcode == X86ISD::SBB || Opcode == X86ISD::SETCC_CARRY) &&
467 "Unexpected opcode for SBB materialization");
468 unsigned FlagOpIndex = Opcode == X86ISD::SBB ? 2 : 1;
469 SDValue EFLAGS =
470 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS,
471 N->getOperand(FlagOpIndex), SDValue());
472
473 // Create a 64-bit instruction if the result is 64-bits otherwise use the
474 // 32-bit version.
475 unsigned Opc = VT == MVT::i64 ? X86::SBB64rr : X86::SBB32rr;
476 MVT SBBVT = VT == MVT::i64 ? MVT::i64 : MVT::i32;
477 VTs = CurDAG->getVTList(SBBVT, MVT::i32);
478 return SDValue(
479 CurDAG->getMachineNode(Opc, dl, VTs,
480 {Zero, Zero, EFLAGS, EFLAGS.getValue(1)}),
481 0);
482 }
483
484 // Helper to detect unneeded and instructions on shift amounts. Called
485 // from PatFrags in tablegen.
486 bool isUnneededShiftMask(SDNode *N, unsigned Width) const {
487 assert(N->getOpcode() == ISD::AND && "Unexpected opcode");
488 const APInt &Val = cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
489
490 if (Val.countr_one() >= Width)
491 return true;
492
493 APInt Mask = Val | CurDAG->computeKnownBits(N->getOperand(0)).Zero;
494 return Mask.countr_one() >= Width;
495 }
496
497 /// Return an SDNode that returns the value of the global base register.
498 /// Output instructions required to initialize the global base register,
499 /// if necessary.
500 SDNode *getGlobalBaseReg();
501
502 /// Return a reference to the TargetMachine, casted to the target-specific
503 /// type.
504 const X86TargetMachine &getTargetMachine() const {
505 return static_cast<const X86TargetMachine &>(TM);
506 }
507
508 /// Return a reference to the TargetInstrInfo, casted to the target-specific
509 /// type.
510 const X86InstrInfo *getInstrInfo() const {
511 return Subtarget->getInstrInfo();
512 }
513
514 /// Return a condition code of the given SDNode
515 X86::CondCode getCondFromNode(SDNode *N) const;
516
517 /// Address-mode matching performs shift-of-and to and-of-shift
518 /// reassociation in order to expose more scaled addressing
519 /// opportunities.
520 bool ComplexPatternFuncMutatesDAG() const override {
521 return true;
522 }
523
524 bool isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const;
525
526 // Indicates we should prefer to use a non-temporal load for this load.
527 bool useNonTemporalLoad(LoadSDNode *N) const {
528 if (!N->isNonTemporal())
529 return false;
530
531 unsigned StoreSize = N->getMemoryVT().getStoreSize();
532
533 if (N->getAlign().value() < StoreSize)
534 return false;
535
536 switch (StoreSize) {
537 default: llvm_unreachable("Unsupported store size");
538 case 4:
539 case 8:
540 return false;
541 case 16:
542 return Subtarget->hasSSE41();
543 case 32:
544 return Subtarget->hasAVX2();
545 case 64:
546 return Subtarget->hasAVX512();
547 }
548 }
549
550 bool foldLoadStoreIntoMemOperand(SDNode *Node);
551 MachineSDNode *matchBEXTRFromAndImm(SDNode *Node);
552 bool matchBitExtract(SDNode *Node);
553 bool shrinkAndImmediate(SDNode *N);
554 bool isMaskZeroExtended(SDNode *N) const;
555 bool tryShiftAmountMod(SDNode *N);
556 bool tryShrinkShlLogicImm(SDNode *N);
557 bool tryVPTERNLOG(SDNode *N);
558 bool matchVPTERNLOG(SDNode *Root, SDNode *ParentA, SDNode *ParentB,
559 SDNode *ParentC, SDValue A, SDValue B, SDValue C,
560 uint8_t Imm);
561 bool tryVPTESTM(SDNode *Root, SDValue Setcc, SDValue Mask);
562 bool tryMatchBitSelect(SDNode *N);
563
564 MachineSDNode *emitPCMPISTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
565 const SDLoc &dl, MVT VT, SDNode *Node);
566 MachineSDNode *emitPCMPESTR(unsigned ROpc, unsigned MOpc, bool MayFoldLoad,
567 const SDLoc &dl, MVT VT, SDNode *Node,
568 SDValue &InGlue);
569
570 bool tryOptimizeRem8Extend(SDNode *N);
571
572 bool onlyUsesZeroFlag(SDValue Flags) const;
573 bool hasNoSignFlagUses(SDValue Flags) const;
574 bool hasNoCarryFlagUses(SDValue Flags) const;
575 };
576}
577
578char X86DAGToDAGISel::ID = 0;
579
580INITIALIZE_PASS(X86DAGToDAGISel, DEBUG_TYPE, PASS_NAME, false, false)
581
582// Returns true if this masked compare can be implemented legally with this
583// type.
584static bool isLegalMaskCompare(SDNode *N, const X86Subtarget *Subtarget) {
585 unsigned Opcode = N->getOpcode();
586 if (Opcode == X86ISD::CMPM || Opcode == X86ISD::CMPMM ||
587 Opcode == X86ISD::STRICT_CMPM || Opcode == ISD::SETCC ||
588 Opcode == X86ISD::CMPMM_SAE || Opcode == X86ISD::VFPCLASS) {
589 // We can get 256-bit 8 element types here without VLX being enabled. When
590 // this happens we will use 512-bit operations and the mask will not be
591 // zero extended.
592 EVT OpVT = N->getOperand(0).getValueType();
593 // The first operand of X86ISD::STRICT_CMPM is chain, so we need to get the
594 // second operand.
595 if (Opcode == X86ISD::STRICT_CMPM)
596 OpVT = N->getOperand(1).getValueType();
597 if (OpVT.is256BitVector() || OpVT.is128BitVector())
598 return Subtarget->hasVLX();
599
600 return true;
601 }
602 // Scalar opcodes use 128 bit registers, but aren't subject to the VLX check.
603 if (Opcode == X86ISD::VFPCLASSS || Opcode == X86ISD::FSETCCM ||
604 Opcode == X86ISD::FSETCCM_SAE)
605 return true;
606
607 return false;
608}
609
610// Returns true if we can assume the writer of the mask has zero extended it
611// for us.
612bool X86DAGToDAGISel::isMaskZeroExtended(SDNode *N) const {
613 // If this is an AND, check if we have a compare on either side. As long as
614 // one side guarantees the mask is zero extended, the AND will preserve those
615 // zeros.
616 if (N->getOpcode() == ISD::AND)
617 return isLegalMaskCompare(N->getOperand(0).getNode(), Subtarget) ||
618 isLegalMaskCompare(N->getOperand(1).getNode(), Subtarget);
619
620 return isLegalMaskCompare(N, Subtarget);
621}
622
623bool
624X86DAGToDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const {
625 if (OptLevel == CodeGenOpt::None) return false;
626
627 if (!N.hasOneUse())
628 return false;
629
630 if (N.getOpcode() != ISD::LOAD)
631 return true;
632
633 // Don't fold non-temporal loads if we have an instruction for them.
634 if (useNonTemporalLoad(cast<LoadSDNode>(N)))
635 return false;
636
637 // If N is a load, do additional profitability checks.
638 if (U == Root) {
639 switch (U->getOpcode()) {
640 default: break;
641 case X86ISD::ADD:
642 case X86ISD::ADC:
643 case X86ISD::SUB:
644 case X86ISD::SBB:
645 case X86ISD::AND:
646 case X86ISD::XOR:
647 case X86ISD::OR:
648 case ISD::ADD:
649 case ISD::UADDO_CARRY:
650 case ISD::AND:
651 case ISD::OR:
652 case ISD::XOR: {
653 SDValue Op1 = U->getOperand(1);
654
655 // If the other operand is a 8-bit immediate we should fold the immediate
656 // instead. This reduces code size.
657 // e.g.
658 // movl 4(%esp), %eax
659 // addl $4, %eax
660 // vs.
661 // movl $4, %eax
662 // addl 4(%esp), %eax
663 // The former is 2 bytes shorter. In case where the increment is 1, then
664 // the saving can be 4 bytes (by using incl %eax).
665 if (auto *Imm = dyn_cast<ConstantSDNode>(Op1)) {
666 if (Imm->getAPIntValue().isSignedIntN(8))
667 return false;
668
669 // If this is a 64-bit AND with an immediate that fits in 32-bits,
670 // prefer using the smaller and over folding the load. This is needed to
671 // make sure immediates created by shrinkAndImmediate are always folded.
672 // Ideally we would narrow the load during DAG combine and get the
673 // best of both worlds.
674 if (U->getOpcode() == ISD::AND &&
675 Imm->getAPIntValue().getBitWidth() == 64 &&
676 Imm->getAPIntValue().isIntN(32))
677 return false;
678
679 // If this really a zext_inreg that can be represented with a movzx
680 // instruction, prefer that.
681 // TODO: We could shrink the load and fold if it is non-volatile.
682 if (U->getOpcode() == ISD::AND &&
683 (Imm->getAPIntValue() == UINT8_MAX ||
684 Imm->getAPIntValue() == UINT16_MAX ||
685 Imm->getAPIntValue() == UINT32_MAX))
686 return false;
687
688 // ADD/SUB with can negate the immediate and use the opposite operation
689 // to fit 128 into a sign extended 8 bit immediate.
690 if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB) &&
691 (-Imm->getAPIntValue()).isSignedIntN(8))
692 return false;
693
694 if ((U->getOpcode() == X86ISD::ADD || U->getOpcode() == X86ISD::SUB) &&
695 (-Imm->getAPIntValue()).isSignedIntN(8) &&
696 hasNoCarryFlagUses(SDValue(U, 1)))
697 return false;
698 }
699
700 // If the other operand is a TLS address, we should fold it instead.
701 // This produces
702 // movl %gs:0, %eax
703 // leal i@NTPOFF(%eax), %eax
704 // instead of
705 // movl $i@NTPOFF, %eax
706 // addl %gs:0, %eax
707 // if the block also has an access to a second TLS address this will save
708 // a load.
709 // FIXME: This is probably also true for non-TLS addresses.
710 if (Op1.getOpcode() == X86ISD::Wrapper) {
711 SDValue Val = Op1.getOperand(0);
713 return false;
714 }
715
716 // Don't fold load if this matches the BTS/BTR/BTC patterns.
717 // BTS: (or X, (shl 1, n))
718 // BTR: (and X, (rotl -2, n))
719 // BTC: (xor X, (shl 1, n))
720 if (U->getOpcode() == ISD::OR || U->getOpcode() == ISD::XOR) {
721 if (U->getOperand(0).getOpcode() == ISD::SHL &&
722 isOneConstant(U->getOperand(0).getOperand(0)))
723 return false;
724
725 if (U->getOperand(1).getOpcode() == ISD::SHL &&
726 isOneConstant(U->getOperand(1).getOperand(0)))
727 return false;
728 }
729 if (U->getOpcode() == ISD::AND) {
730 SDValue U0 = U->getOperand(0);
731 SDValue U1 = U->getOperand(1);
732 if (U0.getOpcode() == ISD::ROTL) {
733 auto *C = dyn_cast<ConstantSDNode>(U0.getOperand(0));
734 if (C && C->getSExtValue() == -2)
735 return false;
736 }
737
738 if (U1.getOpcode() == ISD::ROTL) {
739 auto *C = dyn_cast<ConstantSDNode>(U1.getOperand(0));
740 if (C && C->getSExtValue() == -2)
741 return false;
742 }
743 }
744
745 break;
746 }
747 case ISD::SHL:
748 case ISD::SRA:
749 case ISD::SRL:
750 // Don't fold a load into a shift by immediate. The BMI2 instructions
751 // support folding a load, but not an immediate. The legacy instructions
752 // support folding an immediate, but can't fold a load. Folding an
753 // immediate is preferable to folding a load.
754 if (isa<ConstantSDNode>(U->getOperand(1)))
755 return false;
756
757 break;
758 }
759 }
760
761 // Prevent folding a load if this can implemented with an insert_subreg or
762 // a move that implicitly zeroes.
763 if (Root->getOpcode() == ISD::INSERT_SUBVECTOR &&
764 isNullConstant(Root->getOperand(2)) &&
765 (Root->getOperand(0).isUndef() ||
767 return false;
768
769 return true;
770}
771
772// Indicates it is profitable to form an AVX512 masked operation. Returning
773// false will favor a masked register-register masked move or vblendm and the
774// operation will be selected separately.
775bool X86DAGToDAGISel::isProfitableToFormMaskedOp(SDNode *N) const {
776 assert(
777 (N->getOpcode() == ISD::VSELECT || N->getOpcode() == X86ISD::SELECTS) &&
778 "Unexpected opcode!");
779
780 // If the operation has additional users, the operation will be duplicated.
781 // Check the use count to prevent that.
782 // FIXME: Are there cheap opcodes we might want to duplicate?
783 return N->getOperand(1).hasOneUse();
784}
785
786/// Replace the original chain operand of the call with
787/// load's chain operand and move load below the call's chain operand.
788static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load,
789 SDValue Call, SDValue OrigChain) {
791 SDValue Chain = OrigChain.getOperand(0);
792 if (Chain.getNode() == Load.getNode())
793 Ops.push_back(Load.getOperand(0));
794 else {
795 assert(Chain.getOpcode() == ISD::TokenFactor &&
796 "Unexpected chain operand");
797 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
798 if (Chain.getOperand(i).getNode() == Load.getNode())
799 Ops.push_back(Load.getOperand(0));
800 else
801 Ops.push_back(Chain.getOperand(i));
802 SDValue NewChain =
803 CurDAG->getNode(ISD::TokenFactor, SDLoc(Load), MVT::Other, Ops);
804 Ops.clear();
805 Ops.push_back(NewChain);
806 }
807 Ops.append(OrigChain->op_begin() + 1, OrigChain->op_end());
808 CurDAG->UpdateNodeOperands(OrigChain.getNode(), Ops);
809 CurDAG->UpdateNodeOperands(Load.getNode(), Call.getOperand(0),
810 Load.getOperand(1), Load.getOperand(2));
811
812 Ops.clear();
813 Ops.push_back(SDValue(Load.getNode(), 1));
814 Ops.append(Call->op_begin() + 1, Call->op_end());
815 CurDAG->UpdateNodeOperands(Call.getNode(), Ops);
816}
817
818/// Return true if call address is a load and it can be
819/// moved below CALLSEQ_START and the chains leading up to the call.
820/// Return the CALLSEQ_START by reference as a second output.
821/// In the case of a tail call, there isn't a callseq node between the call
822/// chain and the load.
823static bool isCalleeLoad(SDValue Callee, SDValue &Chain, bool HasCallSeq) {
824 // The transformation is somewhat dangerous if the call's chain was glued to
825 // the call. After MoveBelowOrigChain the load is moved between the call and
826 // the chain, this can create a cycle if the load is not folded. So it is
827 // *really* important that we are sure the load will be folded.
828 if (Callee.getNode() == Chain.getNode() || !Callee.hasOneUse())
829 return false;
830 auto *LD = dyn_cast<LoadSDNode>(Callee.getNode());
831 if (!LD ||
832 !LD->isSimple() ||
833 LD->getAddressingMode() != ISD::UNINDEXED ||
834 LD->getExtensionType() != ISD::NON_EXTLOAD)
835 return false;
836
837 // Now let's find the callseq_start.
838 while (HasCallSeq && Chain.getOpcode() != ISD::CALLSEQ_START) {
839 if (!Chain.hasOneUse())
840 return false;
841 Chain = Chain.getOperand(0);
842 }
843
844 if (!Chain.getNumOperands())
845 return false;
846 // Since we are not checking for AA here, conservatively abort if the chain
847 // writes to memory. It's not safe to move the callee (a load) across a store.
848 if (isa<MemSDNode>(Chain.getNode()) &&
849 cast<MemSDNode>(Chain.getNode())->writeMem())
850 return false;
851 if (Chain.getOperand(0).getNode() == Callee.getNode())
852 return true;
853 if (Chain.getOperand(0).getOpcode() == ISD::TokenFactor &&
854 Callee.getValue(1).isOperandOf(Chain.getOperand(0).getNode()) &&
855 Callee.getValue(1).hasOneUse())
856 return true;
857 return false;
858}
859
860static bool isEndbrImm64(uint64_t Imm) {
861// There may be some other prefix bytes between 0xF3 and 0x0F1EFA.
862// i.g: 0xF3660F1EFA, 0xF3670F1EFA
863 if ((Imm & 0x00FFFFFF) != 0x0F1EFA)
864 return false;
865
866 uint8_t OptionalPrefixBytes [] = {0x26, 0x2e, 0x36, 0x3e, 0x64,
867 0x65, 0x66, 0x67, 0xf0, 0xf2};
868 int i = 24; // 24bit 0x0F1EFA has matched
869 while (i < 64) {
870 uint8_t Byte = (Imm >> i) & 0xFF;
871 if (Byte == 0xF3)
872 return true;
873 if (!llvm::is_contained(OptionalPrefixBytes, Byte))
874 return false;
875 i += 8;
876 }
877
878 return false;
879}
880
881void X86DAGToDAGISel::PreprocessISelDAG() {
882 bool MadeChange = false;
883 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
884 E = CurDAG->allnodes_end(); I != E; ) {
885 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues.
886
887 // This is for CET enhancement.
888 //
889 // ENDBR32 and ENDBR64 have specific opcodes:
890 // ENDBR32: F3 0F 1E FB
891 // ENDBR64: F3 0F 1E FA
892 // And we want that attackers won’t find unintended ENDBR32/64
893 // opcode matches in the binary
894 // Here’s an example:
895 // If the compiler had to generate asm for the following code:
896 // a = 0xF30F1EFA
897 // it could, for example, generate:
898 // mov 0xF30F1EFA, dword ptr[a]
899 // In such a case, the binary would include a gadget that starts
900 // with a fake ENDBR64 opcode. Therefore, we split such generation
901 // into multiple operations, let it not shows in the binary
902 if (N->getOpcode() == ISD::Constant) {
903 MVT VT = N->getSimpleValueType(0);
904 int64_t Imm = cast<ConstantSDNode>(N)->getSExtValue();
905 int32_t EndbrImm = Subtarget->is64Bit() ? 0xF30F1EFA : 0xF30F1EFB;
906 if (Imm == EndbrImm || isEndbrImm64(Imm)) {
907 // Check that the cf-protection-branch is enabled.
908 Metadata *CFProtectionBranch =
909 MF->getMMI().getModule()->getModuleFlag("cf-protection-branch");
910 if (CFProtectionBranch || IndirectBranchTracking) {
911 SDLoc dl(N);
912 SDValue Complement = CurDAG->getConstant(~Imm, dl, VT, false, true);
913 Complement = CurDAG->getNOT(dl, Complement, VT);
914 --I;
915 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Complement);
916 ++I;
917 MadeChange = true;
918 continue;
919 }
920 }
921 }
922
923 // If this is a target specific AND node with no flag usages, turn it back
924 // into ISD::AND to enable test instruction matching.
925 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) {
926 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0),
927 N->getOperand(0), N->getOperand(1));
928 --I;
929 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
930 ++I;
931 MadeChange = true;
932 continue;
933 }
934
935 // Convert vector increment or decrement to sub/add with an all-ones
936 // constant:
937 // add X, <1, 1...> --> sub X, <-1, -1...>
938 // sub X, <1, 1...> --> add X, <-1, -1...>
939 // The all-ones vector constant can be materialized using a pcmpeq
940 // instruction that is commonly recognized as an idiom (has no register
941 // dependency), so that's better/smaller than loading a splat 1 constant.
942 //
943 // But don't do this if it would inhibit a potentially profitable load
944 // folding opportunity for the other operand. That only occurs with the
945 // intersection of:
946 // (1) The other operand (op0) is load foldable.
947 // (2) The op is an add (otherwise, we are *creating* an add and can still
948 // load fold the other op).
949 // (3) The target has AVX (otherwise, we have a destructive add and can't
950 // load fold the other op without killing the constant op).
951 // (4) The constant 1 vector has multiple uses (so it is profitable to load
952 // into a register anyway).
953 auto mayPreventLoadFold = [&]() {
954 return X86::mayFoldLoad(N->getOperand(0), *Subtarget) &&
955 N->getOpcode() == ISD::ADD && Subtarget->hasAVX() &&
956 !N->getOperand(1).hasOneUse();
957 };
958 if ((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
959 N->getSimpleValueType(0).isVector() && !mayPreventLoadFold()) {
960 APInt SplatVal;
961 if (X86::isConstantSplat(N->getOperand(1), SplatVal) &&
962 SplatVal.isOne()) {
963 SDLoc DL(N);
964
965 MVT VT = N->getSimpleValueType(0);
966 unsigned NumElts = VT.getSizeInBits() / 32;
968 CurDAG->getAllOnesConstant(DL, MVT::getVectorVT(MVT::i32, NumElts));
969 AllOnes = CurDAG->getBitcast(VT, AllOnes);
970
971 unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD;
972 SDValue Res =
973 CurDAG->getNode(NewOpcode, DL, VT, N->getOperand(0), AllOnes);
974 --I;
975 CurDAG->ReplaceAllUsesWith(N, Res.getNode());
976 ++I;
977 MadeChange = true;
978 continue;
979 }
980 }
981
982 switch (N->getOpcode()) {
983 case X86ISD::VBROADCAST: {
984 MVT VT = N->getSimpleValueType(0);
985 // Emulate v32i16/v64i8 broadcast without BWI.
986 if (!Subtarget->hasBWI() && (VT == MVT::v32i16 || VT == MVT::v64i8)) {
987 MVT NarrowVT = VT == MVT::v32i16 ? MVT::v16i16 : MVT::v32i8;
988 SDLoc dl(N);
989 SDValue NarrowBCast =
990 CurDAG->getNode(X86ISD::VBROADCAST, dl, NarrowVT, N->getOperand(0));
991 SDValue Res =
992 CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
993 NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
994 unsigned Index = VT == MVT::v32i16 ? 16 : 32;
995 Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
996 CurDAG->getIntPtrConstant(Index, dl));
997
998 --I;
999 CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1000 ++I;
1001 MadeChange = true;
1002 continue;
1003 }
1004
1005 break;
1006 }
1008 MVT VT = N->getSimpleValueType(0);
1009 // Emulate v32i16/v64i8 broadcast without BWI.
1010 if (!Subtarget->hasBWI() && (VT == MVT::v32i16 || VT == MVT::v64i8)) {
1011 MVT NarrowVT = VT == MVT::v32i16 ? MVT::v16i16 : MVT::v32i8;
1012 auto *MemNode = cast<MemSDNode>(N);
1013 SDLoc dl(N);
1014 SDVTList VTs = CurDAG->getVTList(NarrowVT, MVT::Other);
1015 SDValue Ops[] = {MemNode->getChain(), MemNode->getBasePtr()};
1016 SDValue NarrowBCast = CurDAG->getMemIntrinsicNode(
1017 X86ISD::VBROADCAST_LOAD, dl, VTs, Ops, MemNode->getMemoryVT(),
1018 MemNode->getMemOperand());
1019 SDValue Res =
1020 CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT),
1021 NarrowBCast, CurDAG->getIntPtrConstant(0, dl));
1022 unsigned Index = VT == MVT::v32i16 ? 16 : 32;
1023 Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast,
1024 CurDAG->getIntPtrConstant(Index, dl));
1025
1026 --I;
1027 SDValue To[] = {Res, NarrowBCast.getValue(1)};
1028 CurDAG->ReplaceAllUsesWith(N, To);
1029 ++I;
1030 MadeChange = true;
1031 continue;
1032 }
1033
1034 break;
1035 }
1036 case ISD::VSELECT: {
1037 // Replace VSELECT with non-mask conditions with with BLENDV/VPTERNLOG.
1038 EVT EleVT = N->getOperand(0).getValueType().getVectorElementType();
1039 if (EleVT == MVT::i1)
1040 break;
1041
1042 assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!");
1043 assert(N->getValueType(0).getVectorElementType() != MVT::i16 &&
1044 "We can't replace VSELECT with BLENDV in vXi16!");
1045 SDValue R;
1046 if (Subtarget->hasVLX() && CurDAG->ComputeNumSignBits(N->getOperand(0)) ==
1047 EleVT.getSizeInBits()) {
1048 R = CurDAG->getNode(X86ISD::VPTERNLOG, SDLoc(N), N->getValueType(0),
1049 N->getOperand(0), N->getOperand(1), N->getOperand(2),
1050 CurDAG->getTargetConstant(0xCA, SDLoc(N), MVT::i8));
1051 } else {
1052 R = CurDAG->getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0),
1053 N->getOperand(0), N->getOperand(1),
1054 N->getOperand(2));
1055 }
1056 --I;
1057 CurDAG->ReplaceAllUsesWith(N, R.getNode());
1058 ++I;
1059 MadeChange = true;
1060 continue;
1061 }
1062 case ISD::FP_ROUND:
1064 case ISD::FP_TO_SINT:
1065 case ISD::FP_TO_UINT:
1068 // Replace vector fp_to_s/uint with their X86 specific equivalent so we
1069 // don't need 2 sets of patterns.
1070 if (!N->getSimpleValueType(0).isVector())
1071 break;
1072
1073 unsigned NewOpc;
1074 switch (N->getOpcode()) {
1075 default: llvm_unreachable("Unexpected opcode!");
1076 case ISD::FP_ROUND: NewOpc = X86ISD::VFPROUND; break;
1077 case ISD::STRICT_FP_ROUND: NewOpc = X86ISD::STRICT_VFPROUND; break;
1078 case ISD::STRICT_FP_TO_SINT: NewOpc = X86ISD::STRICT_CVTTP2SI; break;
1079 case ISD::FP_TO_SINT: NewOpc = X86ISD::CVTTP2SI; break;
1080 case ISD::STRICT_FP_TO_UINT: NewOpc = X86ISD::STRICT_CVTTP2UI; break;
1081 case ISD::FP_TO_UINT: NewOpc = X86ISD::CVTTP2UI; break;
1082 }
1083 SDValue Res;
1084 if (N->isStrictFPOpcode())
1085 Res =
1086 CurDAG->getNode(NewOpc, SDLoc(N), {N->getValueType(0), MVT::Other},
1087 {N->getOperand(0), N->getOperand(1)});
1088 else
1089 Res =
1090 CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
1091 N->getOperand(0));
1092 --I;
1093 CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1094 ++I;
1095 MadeChange = true;
1096 continue;
1097 }
1098 case ISD::SHL:
1099 case ISD::SRA:
1100 case ISD::SRL: {
1101 // Replace vector shifts with their X86 specific equivalent so we don't
1102 // need 2 sets of patterns.
1103 if (!N->getValueType(0).isVector())
1104 break;
1105
1106 unsigned NewOpc;
1107 switch (N->getOpcode()) {
1108 default: llvm_unreachable("Unexpected opcode!");
1109 case ISD::SHL: NewOpc = X86ISD::VSHLV; break;
1110 case ISD::SRA: NewOpc = X86ISD::VSRAV; break;
1111 case ISD::SRL: NewOpc = X86ISD::VSRLV; break;
1112 }
1113 SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
1114 N->getOperand(0), N->getOperand(1));
1115 --I;
1116 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1117 ++I;
1118 MadeChange = true;
1119 continue;
1120 }
1121 case ISD::ANY_EXTEND:
1123 // Replace vector any extend with the zero extend equivalents so we don't
1124 // need 2 sets of patterns. Ignore vXi1 extensions.
1125 if (!N->getValueType(0).isVector())
1126 break;
1127
1128 unsigned NewOpc;
1129 if (N->getOperand(0).getScalarValueSizeInBits() == 1) {
1130 assert(N->getOpcode() == ISD::ANY_EXTEND &&
1131 "Unexpected opcode for mask vector!");
1132 NewOpc = ISD::SIGN_EXTEND;
1133 } else {
1134 NewOpc = N->getOpcode() == ISD::ANY_EXTEND
1137 }
1138
1139 SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0),
1140 N->getOperand(0));
1141 --I;
1142 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1143 ++I;
1144 MadeChange = true;
1145 continue;
1146 }
1147 case ISD::FCEIL:
1148 case ISD::STRICT_FCEIL:
1149 case ISD::FFLOOR:
1150 case ISD::STRICT_FFLOOR:
1151 case ISD::FTRUNC:
1152 case ISD::STRICT_FTRUNC:
1153 case ISD::FROUNDEVEN:
1155 case ISD::FNEARBYINT:
1157 case ISD::FRINT:
1158 case ISD::STRICT_FRINT: {
1159 // Replace fp rounding with their X86 specific equivalent so we don't
1160 // need 2 sets of patterns.
1161 unsigned Imm;
1162 switch (N->getOpcode()) {
1163 default: llvm_unreachable("Unexpected opcode!");
1164 case ISD::STRICT_FCEIL:
1165 case ISD::FCEIL: Imm = 0xA; break;
1166 case ISD::STRICT_FFLOOR:
1167 case ISD::FFLOOR: Imm = 0x9; break;
1168 case ISD::STRICT_FTRUNC:
1169 case ISD::FTRUNC: Imm = 0xB; break;
1171 case ISD::FROUNDEVEN: Imm = 0x8; break;
1173 case ISD::FNEARBYINT: Imm = 0xC; break;
1174 case ISD::STRICT_FRINT:
1175 case ISD::FRINT: Imm = 0x4; break;
1176 }
1177 SDLoc dl(N);
1178 bool IsStrict = N->isStrictFPOpcode();
1179 SDValue Res;
1180 if (IsStrict)
1181 Res = CurDAG->getNode(X86ISD::STRICT_VRNDSCALE, dl,
1182 {N->getValueType(0), MVT::Other},
1183 {N->getOperand(0), N->getOperand(1),
1184 CurDAG->getTargetConstant(Imm, dl, MVT::i32)});
1185 else
1186 Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl, N->getValueType(0),
1187 N->getOperand(0),
1188 CurDAG->getTargetConstant(Imm, dl, MVT::i32));
1189 --I;
1190 CurDAG->ReplaceAllUsesWith(N, Res.getNode());
1191 ++I;
1192 MadeChange = true;
1193 continue;
1194 }
1195 case X86ISD::FANDN:
1196 case X86ISD::FAND:
1197 case X86ISD::FOR:
1198 case X86ISD::FXOR: {
1199 // Widen scalar fp logic ops to vector to reduce isel patterns.
1200 // FIXME: Can we do this during lowering/combine.
1201 MVT VT = N->getSimpleValueType(0);
1202 if (VT.isVector() || VT == MVT::f128)
1203 break;
1204
1205 MVT VecVT = VT == MVT::f64 ? MVT::v2f64
1206 : VT == MVT::f32 ? MVT::v4f32
1207 : MVT::v8f16;
1208
1209 SDLoc dl(N);
1210 SDValue Op0 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
1211 N->getOperand(0));
1212 SDValue Op1 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT,
1213 N->getOperand(1));
1214
1215 SDValue Res;
1216 if (Subtarget->hasSSE2()) {
1217 EVT IntVT = EVT(VecVT).changeVectorElementTypeToInteger();
1218 Op0 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op0);
1219 Op1 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op1);
1220 unsigned Opc;
1221 switch (N->getOpcode()) {
1222 default: llvm_unreachable("Unexpected opcode!");
1223 case X86ISD::FANDN: Opc = X86ISD::ANDNP; break;
1224 case X86ISD::FAND: Opc = ISD::AND; break;
1225 case X86ISD::FOR: Opc = ISD::OR; break;
1226 case X86ISD::FXOR: Opc = ISD::XOR; break;
1227 }
1228 Res = CurDAG->getNode(Opc, dl, IntVT, Op0, Op1);
1229 Res = CurDAG->getNode(ISD::BITCAST, dl, VecVT, Res);
1230 } else {
1231 Res = CurDAG->getNode(N->getOpcode(), dl, VecVT, Op0, Op1);
1232 }
1233 Res = CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res,
1234 CurDAG->getIntPtrConstant(0, dl));
1235 --I;
1236 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
1237 ++I;
1238 MadeChange = true;
1239 continue;
1240 }
1241 }
1242
1243 if (OptLevel != CodeGenOpt::None &&
1244 // Only do this when the target can fold the load into the call or
1245 // jmp.
1246 !Subtarget->useIndirectThunkCalls() &&
1247 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) ||
1248 (N->getOpcode() == X86ISD::TC_RETURN &&
1249 (Subtarget->is64Bit() ||
1250 !getTargetMachine().isPositionIndependent())))) {
1251 /// Also try moving call address load from outside callseq_start to just
1252 /// before the call to allow it to be folded.
1253 ///
1254 /// [Load chain]
1255 /// ^
1256 /// |
1257 /// [Load]
1258 /// ^ ^
1259 /// | |
1260 /// / \--
1261 /// / |
1262 ///[CALLSEQ_START] |
1263 /// ^ |
1264 /// | |
1265 /// [LOAD/C2Reg] |
1266 /// | |
1267 /// \ /
1268 /// \ /
1269 /// [CALL]
1270 bool HasCallSeq = N->getOpcode() == X86ISD::CALL;
1271 SDValue Chain = N->getOperand(0);
1272 SDValue Load = N->getOperand(1);
1273 if (!isCalleeLoad(Load, Chain, HasCallSeq))
1274 continue;
1275 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain);
1276 ++NumLoadMoved;
1277 MadeChange = true;
1278 continue;
1279 }
1280
1281 // Lower fpround and fpextend nodes that target the FP stack to be store and
1282 // load to the stack. This is a gross hack. We would like to simply mark
1283 // these as being illegal, but when we do that, legalize produces these when
1284 // it expands calls, then expands these in the same legalize pass. We would
1285 // like dag combine to be able to hack on these between the call expansion
1286 // and the node legalization. As such this pass basically does "really
1287 // late" legalization of these inline with the X86 isel pass.
1288 // FIXME: This should only happen when not compiled with -O0.
1289 switch (N->getOpcode()) {
1290 default: continue;
1291 case ISD::FP_ROUND:
1292 case ISD::FP_EXTEND:
1293 {
1294 MVT SrcVT = N->getOperand(0).getSimpleValueType();
1295 MVT DstVT = N->getSimpleValueType(0);
1296
1297 // If any of the sources are vectors, no fp stack involved.
1298 if (SrcVT.isVector() || DstVT.isVector())
1299 continue;
1300
1301 // If the source and destination are SSE registers, then this is a legal
1302 // conversion that should not be lowered.
1303 const X86TargetLowering *X86Lowering =
1304 static_cast<const X86TargetLowering *>(TLI);
1305 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
1306 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
1307 if (SrcIsSSE && DstIsSSE)
1308 continue;
1309
1310 if (!SrcIsSSE && !DstIsSSE) {
1311 // If this is an FPStack extension, it is a noop.
1312 if (N->getOpcode() == ISD::FP_EXTEND)
1313 continue;
1314 // If this is a value-preserving FPStack truncation, it is a noop.
1315 if (N->getConstantOperandVal(1))
1316 continue;
1317 }
1318
1319 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
1320 // FPStack has extload and truncstore. SSE can fold direct loads into other
1321 // operations. Based on this, decide what we want to do.
1322 MVT MemVT = (N->getOpcode() == ISD::FP_ROUND) ? DstVT : SrcVT;
1323 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
1324 int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
1325 MachinePointerInfo MPI =
1326 MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
1327 SDLoc dl(N);
1328
1329 // FIXME: optimize the case where the src/dest is a load or store?
1330
1331 SDValue Store = CurDAG->getTruncStore(
1332 CurDAG->getEntryNode(), dl, N->getOperand(0), MemTmp, MPI, MemVT);
1333 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store,
1334 MemTmp, MPI, MemVT);
1335
1336 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
1337 // extload we created. This will cause general havok on the dag because
1338 // anything below the conversion could be folded into other existing nodes.
1339 // To avoid invalidating 'I', back it up to the convert node.
1340 --I;
1341 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1342 break;
1343 }
1344
1345 //The sequence of events for lowering STRICT_FP versions of these nodes requires
1346 //dealing with the chain differently, as there is already a preexisting chain.
1349 {
1350 MVT SrcVT = N->getOperand(1).getSimpleValueType();
1351 MVT DstVT = N->getSimpleValueType(0);
1352
1353 // If any of the sources are vectors, no fp stack involved.
1354 if (SrcVT.isVector() || DstVT.isVector())
1355 continue;
1356
1357 // If the source and destination are SSE registers, then this is a legal
1358 // conversion that should not be lowered.
1359 const X86TargetLowering *X86Lowering =
1360 static_cast<const X86TargetLowering *>(TLI);
1361 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT);
1362 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT);
1363 if (SrcIsSSE && DstIsSSE)
1364 continue;
1365
1366 if (!SrcIsSSE && !DstIsSSE) {
1367 // If this is an FPStack extension, it is a noop.
1368 if (N->getOpcode() == ISD::STRICT_FP_EXTEND)
1369 continue;
1370 // If this is a value-preserving FPStack truncation, it is a noop.
1371 if (N->getConstantOperandVal(2))
1372 continue;
1373 }
1374
1375 // Here we could have an FP stack truncation or an FPStack <-> SSE convert.
1376 // FPStack has extload and truncstore. SSE can fold direct loads into other
1377 // operations. Based on this, decide what we want to do.
1378 MVT MemVT = (N->getOpcode() == ISD::STRICT_FP_ROUND) ? DstVT : SrcVT;
1379 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT);
1380 int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex();
1381 MachinePointerInfo MPI =
1382 MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI);
1383 SDLoc dl(N);
1384
1385 // FIXME: optimize the case where the src/dest is a load or store?
1386
1387 //Since the operation is StrictFP, use the preexisting chain.
1389 if (!SrcIsSSE) {
1390 SDVTList VTs = CurDAG->getVTList(MVT::Other);
1391 SDValue Ops[] = {N->getOperand(0), N->getOperand(1), MemTmp};
1392 Store = CurDAG->getMemIntrinsicNode(X86ISD::FST, dl, VTs, Ops, MemVT,
1393 MPI, /*Align*/ std::nullopt,
1395 if (N->getFlags().hasNoFPExcept()) {
1396 SDNodeFlags Flags = Store->getFlags();
1397 Flags.setNoFPExcept(true);
1398 Store->setFlags(Flags);
1399 }
1400 } else {
1401 assert(SrcVT == MemVT && "Unexpected VT!");
1402 Store = CurDAG->getStore(N->getOperand(0), dl, N->getOperand(1), MemTmp,
1403 MPI);
1404 }
1405
1406 if (!DstIsSSE) {
1407 SDVTList VTs = CurDAG->getVTList(DstVT, MVT::Other);
1408 SDValue Ops[] = {Store, MemTmp};
1409 Result = CurDAG->getMemIntrinsicNode(
1410 X86ISD::FLD, dl, VTs, Ops, MemVT, MPI,
1411 /*Align*/ std::nullopt, MachineMemOperand::MOLoad);
1412 if (N->getFlags().hasNoFPExcept()) {
1413 SDNodeFlags Flags = Result->getFlags();
1414 Flags.setNoFPExcept(true);
1415 Result->setFlags(Flags);
1416 }
1417 } else {
1418 assert(DstVT == MemVT && "Unexpected VT!");
1419 Result = CurDAG->getLoad(DstVT, dl, Store, MemTmp, MPI);
1420 }
1421
1422 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the
1423 // extload we created. This will cause general havok on the dag because
1424 // anything below the conversion could be folded into other existing nodes.
1425 // To avoid invalidating 'I', back it up to the convert node.
1426 --I;
1427 CurDAG->ReplaceAllUsesWith(N, Result.getNode());
1428 break;
1429 }
1430 }
1431
1432
1433 // Now that we did that, the node is dead. Increment the iterator to the
1434 // next node to process, then delete N.
1435 ++I;
1436 MadeChange = true;
1437 }
1438
1439 // Remove any dead nodes that may have been left behind.
1440 if (MadeChange)
1441 CurDAG->RemoveDeadNodes();
1442}
1443
1444// Look for a redundant movzx/movsx that can occur after an 8-bit divrem.
1445bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) {
1446 unsigned Opc = N->getMachineOpcode();
1447 if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 &&
1448 Opc != X86::MOVSX64rr8)
1449 return false;
1450
1451 SDValue N0 = N->getOperand(0);
1452
1453 // We need to be extracting the lower bit of an extend.
1454 if (!N0.isMachineOpcode() ||
1455 N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG ||
1456 N0.getConstantOperandVal(1) != X86::sub_8bit)
1457 return false;
1458
1459 // We're looking for either a movsx or movzx to match the original opcode.
1460 unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX
1461 : X86::MOVSX32rr8_NOREX;
1462 SDValue N00 = N0.getOperand(0);
1463 if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc)
1464 return false;
1465
1466 if (Opc == X86::MOVSX64rr8) {
1467 // If we had a sign extend from 8 to 64 bits. We still need to go from 32
1468 // to 64.
1469 MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N),
1470 MVT::i64, N00);
1471 ReplaceUses(N, Extend);
1472 } else {
1473 // Ok we can drop this extend and just use the original extend.
1474 ReplaceUses(N, N00.getNode());
1475 }
1476
1477 return true;
1478}
1479
1480void X86DAGToDAGISel::PostprocessISelDAG() {
1481 // Skip peepholes at -O0.
1482 if (TM.getOptLevel() == CodeGenOpt::None)
1483 return;
1484
1485 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
1486
1487 bool MadeChange = false;
1488 while (Position != CurDAG->allnodes_begin()) {
1489 SDNode *N = &*--Position;
1490 // Skip dead nodes and any non-machine opcodes.
1491 if (N->use_empty() || !N->isMachineOpcode())
1492 continue;
1493
1494 if (tryOptimizeRem8Extend(N)) {
1495 MadeChange = true;
1496 continue;
1497 }
1498
1499 // Look for a TESTrr+ANDrr pattern where both operands of the test are
1500 // the same. Rewrite to remove the AND.
1501 unsigned Opc = N->getMachineOpcode();
1502 if ((Opc == X86::TEST8rr || Opc == X86::TEST16rr ||
1503 Opc == X86::TEST32rr || Opc == X86::TEST64rr) &&
1504 N->getOperand(0) == N->getOperand(1) &&
1505 N->getOperand(0)->hasNUsesOfValue(2, N->getOperand(0).getResNo()) &&
1506 N->getOperand(0).isMachineOpcode()) {
1507 SDValue And = N->getOperand(0);
1508 unsigned N0Opc = And.getMachineOpcode();
1509 if ((N0Opc == X86::AND8rr || N0Opc == X86::AND16rr ||
1510 N0Opc == X86::AND32rr || N0Opc == X86::AND64rr) &&
1511 !And->hasAnyUseOfValue(1)) {
1512 MachineSDNode *Test = CurDAG->getMachineNode(Opc, SDLoc(N),
1513 MVT::i32,
1514 And.getOperand(0),
1515 And.getOperand(1));
1516 ReplaceUses(N, Test);
1517 MadeChange = true;
1518 continue;
1519 }
1520 if ((N0Opc == X86::AND8rm || N0Opc == X86::AND16rm ||
1521 N0Opc == X86::AND32rm || N0Opc == X86::AND64rm) &&
1522 !And->hasAnyUseOfValue(1)) {
1523 unsigned NewOpc;
1524 switch (N0Opc) {
1525 case X86::AND8rm: NewOpc = X86::TEST8mr; break;
1526 case X86::AND16rm: NewOpc = X86::TEST16mr; break;
1527 case X86::AND32rm: NewOpc = X86::TEST32mr; break;
1528 case X86::AND64rm: NewOpc = X86::TEST64mr; break;
1529 }
1530
1531 // Need to swap the memory and register operand.
1532 SDValue Ops[] = { And.getOperand(1),
1533 And.getOperand(2),
1534 And.getOperand(3),
1535 And.getOperand(4),
1536 And.getOperand(5),
1537 And.getOperand(0),
1538 And.getOperand(6) /* Chain */ };
1539 MachineSDNode *Test = CurDAG->getMachineNode(NewOpc, SDLoc(N),
1540 MVT::i32, MVT::Other, Ops);
1541 CurDAG->setNodeMemRefs(
1542 Test, cast<MachineSDNode>(And.getNode())->memoperands());
1543 ReplaceUses(And.getValue(2), SDValue(Test, 1));
1544 ReplaceUses(SDValue(N, 0), SDValue(Test, 0));
1545 MadeChange = true;
1546 continue;
1547 }
1548 }
1549
1550 // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is
1551 // used. We're doing this late so we can prefer to fold the AND into masked
1552 // comparisons. Doing that can be better for the live range of the mask
1553 // register.
1554 if ((Opc == X86::KORTESTBrr || Opc == X86::KORTESTWrr ||
1555 Opc == X86::KORTESTDrr || Opc == X86::KORTESTQrr) &&
1556 N->getOperand(0) == N->getOperand(1) &&
1557 N->isOnlyUserOf(N->getOperand(0).getNode()) &&
1558 N->getOperand(0).isMachineOpcode() &&
1559 onlyUsesZeroFlag(SDValue(N, 0))) {
1560 SDValue And = N->getOperand(0);
1561 unsigned N0Opc = And.getMachineOpcode();
1562 // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other
1563 // KAND instructions and KTEST use the same ISA feature.
1564 if (N0Opc == X86::KANDBrr ||
1565 (N0Opc == X86::KANDWrr && Subtarget->hasDQI()) ||
1566 N0Opc == X86::KANDDrr || N0Opc == X86::KANDQrr) {
1567 unsigned NewOpc;
1568 switch (Opc) {
1569 default: llvm_unreachable("Unexpected opcode!");
1570 case X86::KORTESTBrr: NewOpc = X86::KTESTBrr; break;
1571 case X86::KORTESTWrr: NewOpc = X86::KTESTWrr; break;
1572 case X86::KORTESTDrr: NewOpc = X86::KTESTDrr; break;
1573 case X86::KORTESTQrr: NewOpc = X86::KTESTQrr; break;
1574 }
1575 MachineSDNode *KTest = CurDAG->getMachineNode(NewOpc, SDLoc(N),
1576 MVT::i32,
1577 And.getOperand(0),
1578 And.getOperand(1));
1579 ReplaceUses(N, KTest);
1580 MadeChange = true;
1581 continue;
1582 }
1583 }
1584
1585 // Attempt to remove vectors moves that were inserted to zero upper bits.
1586 if (Opc != TargetOpcode::SUBREG_TO_REG)
1587 continue;
1588
1589 unsigned SubRegIdx = N->getConstantOperandVal(2);
1590 if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm)
1591 continue;
1592
1593 SDValue Move = N->getOperand(1);
1594 if (!Move.isMachineOpcode())
1595 continue;
1596
1597 // Make sure its one of the move opcodes we recognize.
1598 switch (Move.getMachineOpcode()) {
1599 default:
1600 continue;
1601 case X86::VMOVAPDrr: case X86::VMOVUPDrr:
1602 case X86::VMOVAPSrr: case X86::VMOVUPSrr:
1603 case X86::VMOVDQArr: case X86::VMOVDQUrr:
1604 case X86::VMOVAPDYrr: case X86::VMOVUPDYrr:
1605 case X86::VMOVAPSYrr: case X86::VMOVUPSYrr:
1606 case X86::VMOVDQAYrr: case X86::VMOVDQUYrr:
1607 case X86::VMOVAPDZ128rr: case X86::VMOVUPDZ128rr:
1608 case X86::VMOVAPSZ128rr: case X86::VMOVUPSZ128rr:
1609 case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr:
1610 case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr:
1611 case X86::VMOVAPDZ256rr: case X86::VMOVUPDZ256rr:
1612 case X86::VMOVAPSZ256rr: case X86::VMOVUPSZ256rr:
1613 case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr:
1614 case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr:
1615 break;
1616 }
1617
1618 SDValue In = Move.getOperand(0);
1619 if (!In.isMachineOpcode() ||
1620 In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END)
1621 continue;
1622
1623 // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers
1624 // the SHA instructions which use a legacy encoding.
1625 uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags;
1629 continue;
1630
1631 // Producing instruction is another vector instruction. We can drop the
1632 // move.
1633 CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2));
1634 MadeChange = true;
1635 }
1636
1637 if (MadeChange)
1638 CurDAG->RemoveDeadNodes();
1639}
1640
1641
1642/// Emit any code that needs to be executed only in the main function.
1643void X86DAGToDAGISel::emitSpecialCodeForMain() {
1644 if (Subtarget->isTargetCygMing()) {
1646 auto &DL = CurDAG->getDataLayout();
1647
1649 CLI.setChain(CurDAG->getRoot())
1650 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()),
1651 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)),
1652 std::move(Args));
1653 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo();
1654 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
1655 CurDAG->setRoot(Result.second);
1656 }
1657}
1658
1659void X86DAGToDAGISel::emitFunctionEntryCode() {
1660 // If this is main, emit special code for main.
1661 const Function &F = MF->getFunction();
1662 if (F.hasExternalLinkage() && F.getName() == "main")
1663 emitSpecialCodeForMain();
1664}
1665
1666static bool isDispSafeForFrameIndex(int64_t Val) {
1667 // On 64-bit platforms, we can run into an issue where a frame index
1668 // includes a displacement that, when added to the explicit displacement,
1669 // will overflow the displacement field. Assuming that the frame index
1670 // displacement fits into a 31-bit integer (which is only slightly more
1671 // aggressive than the current fundamental assumption that it fits into
1672 // a 32-bit integer), a 31-bit disp should always be safe.
1673 return isInt<31>(Val);
1674}
1675
1676bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset,
1677 X86ISelAddressMode &AM) {
1678 // We may have already matched a displacement and the caller just added the
1679 // symbolic displacement. So we still need to do the checks even if Offset
1680 // is zero.
1681
1682 int64_t Val = AM.Disp + Offset;
1683
1684 // Cannot combine ExternalSymbol displacements with integer offsets.
1685 if (Val != 0 && (AM.ES || AM.MCSym))
1686 return true;
1687
1688 CodeModel::Model M = TM.getCodeModel();
1689 if (Subtarget->is64Bit()) {
1690 if (Val != 0 &&
1692 AM.hasSymbolicDisplacement()))
1693 return true;
1694 // In addition to the checks required for a register base, check that
1695 // we do not try to use an unsafe Disp with a frame index.
1696 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase &&
1698 return true;
1699 }
1700 AM.Disp = Val;
1701 return false;
1702
1703}
1704
1705bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM,
1706 bool AllowSegmentRegForX32) {
1707 SDValue Address = N->getOperand(1);
1708
1709 // load gs:0 -> GS segment register.
1710 // load fs:0 -> FS segment register.
1711 //
1712 // This optimization is generally valid because the GNU TLS model defines that
1713 // gs:0 (or fs:0 on X86-64) contains its own address. However, for X86-64 mode
1714 // with 32-bit registers, as we get in ILP32 mode, those registers are first
1715 // zero-extended to 64 bits and then added it to the base address, which gives
1716 // unwanted results when the register holds a negative value.
1717 // For more information see http://people.redhat.com/drepper/tls.pdf
1718 if (isNullConstant(Address) && AM.Segment.getNode() == nullptr &&
1719 !IndirectTlsSegRefs &&
1720 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() ||
1721 Subtarget->isTargetFuchsia())) {
1722 if (Subtarget->isTarget64BitILP32() && !AllowSegmentRegForX32)
1723 return true;
1724 switch (N->getPointerInfo().getAddrSpace()) {
1725 case X86AS::GS:
1726 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
1727 return false;
1728 case X86AS::FS:
1729 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
1730 return false;
1731 // Address space X86AS::SS is not handled here, because it is not used to
1732 // address TLS areas.
1733 }
1734 }
1735
1736 return true;
1737}
1738
1739/// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing
1740/// mode. These wrap things that will resolve down into a symbol reference.
1741/// If no match is possible, this returns true, otherwise it returns false.
1742bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) {
1743 // If the addressing mode already has a symbol as the displacement, we can
1744 // never match another symbol.
1745 if (AM.hasSymbolicDisplacement())
1746 return true;
1747
1748 bool IsRIPRelTLS = false;
1749 bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP;
1750 if (IsRIPRel) {
1751 SDValue Val = N.getOperand(0);
1753 IsRIPRelTLS = true;
1754 }
1755
1756 // We can't use an addressing mode in the 64-bit large code model.
1757 // Global TLS addressing is an exception. In the medium code model,
1758 // we use can use a mode when RIP wrappers are present.
1759 // That signifies access to globals that are known to be "near",
1760 // such as the GOT itself.
1761 CodeModel::Model M = TM.getCodeModel();
1762 if (Subtarget->is64Bit() &&
1763 ((M == CodeModel::Large && !IsRIPRelTLS) ||
1764 (M == CodeModel::Medium && !IsRIPRel)))
1765 return true;
1766
1767 // Base and index reg must be 0 in order to use %rip as base.
1768 if (IsRIPRel && AM.hasBaseOrIndexReg())
1769 return true;
1770
1771 // Make a local copy in case we can't do this fold.
1772 X86ISelAddressMode Backup = AM;
1773
1774 int64_t Offset = 0;
1775 SDValue N0 = N.getOperand(0);
1776 if (auto *G = dyn_cast<GlobalAddressSDNode>(N0)) {
1777 AM.GV = G->getGlobal();
1778 AM.SymbolFlags = G->getTargetFlags();
1779 Offset = G->getOffset();
1780 } else if (auto *CP = dyn_cast<ConstantPoolSDNode>(N0)) {
1781 AM.CP = CP->getConstVal();
1782 AM.Alignment = CP->getAlign();
1783 AM.SymbolFlags = CP->getTargetFlags();
1784 Offset = CP->getOffset();
1785 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(N0)) {
1786 AM.ES = S->getSymbol();
1787 AM.SymbolFlags = S->getTargetFlags();
1788 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) {
1789 AM.MCSym = S->getMCSymbol();
1790 } else if (auto *J = dyn_cast<JumpTableSDNode>(N0)) {
1791 AM.JT = J->getIndex();
1792 AM.SymbolFlags = J->getTargetFlags();
1793 } else if (auto *BA = dyn_cast<BlockAddressSDNode>(N0)) {
1794 AM.BlockAddr = BA->getBlockAddress();
1795 AM.SymbolFlags = BA->getTargetFlags();
1796 Offset = BA->getOffset();
1797 } else
1798 llvm_unreachable("Unhandled symbol reference node.");
1799
1800 if (foldOffsetIntoAddress(Offset, AM)) {
1801 AM = Backup;
1802 return true;
1803 }
1804
1805 if (IsRIPRel)
1806 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64));
1807
1808 // Commit the changes now that we know this fold is safe.
1809 return false;
1810}
1811
1812/// Add the specified node to the specified addressing mode, returning true if
1813/// it cannot be done. This just pattern matches for the addressing mode.
1814bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) {
1815 if (matchAddressRecursively(N, AM, 0))
1816 return true;
1817
1818 // Post-processing: Make a second attempt to fold a load, if we now know
1819 // that there will not be any other register. This is only performed for
1820 // 64-bit ILP32 mode since 32-bit mode and 64-bit LP64 mode will have folded
1821 // any foldable load the first time.
1822 if (Subtarget->isTarget64BitILP32() &&
1823 AM.BaseType == X86ISelAddressMode::RegBase &&
1824 AM.Base_Reg.getNode() != nullptr && AM.IndexReg.getNode() == nullptr) {
1825 SDValue Save_Base_Reg = AM.Base_Reg;
1826 if (auto *LoadN = dyn_cast<LoadSDNode>(Save_Base_Reg)) {
1827 AM.Base_Reg = SDValue();
1828 if (matchLoadInAddress(LoadN, AM, /*AllowSegmentRegForX32=*/true))
1829 AM.Base_Reg = Save_Base_Reg;
1830 }
1831 }
1832
1833 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has
1834 // a smaller encoding and avoids a scaled-index.
1835 if (AM.Scale == 2 &&
1836 AM.BaseType == X86ISelAddressMode::RegBase &&
1837 AM.Base_Reg.getNode() == nullptr) {
1838 AM.Base_Reg = AM.IndexReg;
1839 AM.Scale = 1;
1840 }
1841
1842 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode,
1843 // because it has a smaller encoding.
1844 // TODO: Which other code models can use this?
1845 switch (TM.getCodeModel()) {
1846 default: break;
1847 case CodeModel::Small:
1848 case CodeModel::Kernel:
1849 if (Subtarget->is64Bit() &&
1850 AM.Scale == 1 &&
1851 AM.BaseType == X86ISelAddressMode::RegBase &&
1852 AM.Base_Reg.getNode() == nullptr &&
1853 AM.IndexReg.getNode() == nullptr &&
1854 AM.SymbolFlags == X86II::MO_NO_FLAG &&
1855 AM.hasSymbolicDisplacement())
1856 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64);
1857 break;
1858 }
1859
1860 return false;
1861}
1862
1863bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM,
1864 unsigned Depth) {
1865 // Add an artificial use to this node so that we can keep track of
1866 // it if it gets CSE'd with a different node.
1867 HandleSDNode Handle(N);
1868
1869 X86ISelAddressMode Backup = AM;
1870 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) &&
1871 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1))
1872 return false;
1873 AM = Backup;
1874
1875 // Try again after commutating the operands.
1876 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM,
1877 Depth + 1) &&
1878 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth + 1))
1879 return false;
1880 AM = Backup;
1881
1882 // If we couldn't fold both operands into the address at the same time,
1883 // see if we can just put each operand into a register and fold at least
1884 // the add.
1885 if (AM.BaseType == X86ISelAddressMode::RegBase &&
1886 !AM.Base_Reg.getNode() &&
1887 !AM.IndexReg.getNode()) {
1888 N = Handle.getValue();
1889 AM.Base_Reg = N.getOperand(0);
1890 AM.IndexReg = N.getOperand(1);
1891 AM.Scale = 1;
1892 return false;
1893 }
1894 N = Handle.getValue();
1895 return true;
1896}
1897
1898// Insert a node into the DAG at least before the Pos node's position. This
1899// will reposition the node as needed, and will assign it a node ID that is <=
1900// the Pos node's ID. Note that this does *not* preserve the uniqueness of node
1901// IDs! The selection DAG must no longer depend on their uniqueness when this
1902// is used.
1903static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) {
1904 if (N->getNodeId() == -1 ||
1907 DAG.RepositionNode(Pos->getIterator(), N.getNode());
1908 // Mark Node as invalid for pruning as after this it may be a successor to a
1909 // selected node but otherwise be in the same position of Pos.
1910 // Conservatively mark it with the same -abs(Id) to assure node id
1911 // invariant is preserved.
1912 N->setNodeId(Pos->getNodeId());
1914 }
1915}
1916
1917// Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if
1918// safe. This allows us to convert the shift and and into an h-register
1919// extract and a scaled index. Returns false if the simplification is
1920// performed.
1922 uint64_t Mask,
1923 SDValue Shift, SDValue X,
1924 X86ISelAddressMode &AM) {
1925 if (Shift.getOpcode() != ISD::SRL ||
1926 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
1927 !Shift.hasOneUse())
1928 return true;
1929
1930 int ScaleLog = 8 - Shift.getConstantOperandVal(1);
1931 if (ScaleLog <= 0 || ScaleLog >= 4 ||
1932 Mask != (0xffu << ScaleLog))
1933 return true;
1934
1935 MVT VT = N.getSimpleValueType();
1936 SDLoc DL(N);
1937 SDValue Eight = DAG.getConstant(8, DL, MVT::i8);
1938 SDValue NewMask = DAG.getConstant(0xff, DL, VT);
1939 SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, X, Eight);
1940 SDValue And = DAG.getNode(ISD::AND, DL, VT, Srl, NewMask);
1941 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8);
1942 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, And, ShlCount);
1943
1944 // Insert the new nodes into the topological ordering. We must do this in
1945 // a valid topological ordering as nothing is going to go back and re-sort
1946 // these nodes. We continually insert before 'N' in sequence as this is
1947 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
1948 // hierarchy left to express.
1949 insertDAGNode(DAG, N, Eight);
1950 insertDAGNode(DAG, N, Srl);
1951 insertDAGNode(DAG, N, NewMask);
1952 insertDAGNode(DAG, N, And);
1953 insertDAGNode(DAG, N, ShlCount);
1954 insertDAGNode(DAG, N, Shl);
1955 DAG.ReplaceAllUsesWith(N, Shl);
1956 DAG.RemoveDeadNode(N.getNode());
1957 AM.IndexReg = And;
1958 AM.Scale = (1 << ScaleLog);
1959 return false;
1960}
1961
1962// Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this
1963// allows us to fold the shift into this addressing mode. Returns false if the
1964// transform succeeded.
1966 X86ISelAddressMode &AM) {
1967 SDValue Shift = N.getOperand(0);
1968
1969 // Use a signed mask so that shifting right will insert sign bits. These
1970 // bits will be removed when we shift the result left so it doesn't matter
1971 // what we use. This might allow a smaller immediate encoding.
1972 int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue();
1973
1974 // If we have an any_extend feeding the AND, look through it to see if there
1975 // is a shift behind it. But only if the AND doesn't use the extended bits.
1976 // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
1977 bool FoundAnyExtend = false;
1978 if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
1979 Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
1980 isUInt<32>(Mask)) {
1981 FoundAnyExtend = true;
1982 Shift = Shift.getOperand(0);
1983 }
1984
1985 if (Shift.getOpcode() != ISD::SHL ||
1986 !isa<ConstantSDNode>(Shift.getOperand(1)))
1987 return true;
1988
1989 SDValue X = Shift.getOperand(0);
1990
1991 // Not likely to be profitable if either the AND or SHIFT node has more
1992 // than one use (unless all uses are for address computation). Besides,
1993 // isel mechanism requires their node ids to be reused.
1994 if (!N.hasOneUse() || !Shift.hasOneUse())
1995 return true;
1996
1997 // Verify that the shift amount is something we can fold.
1998 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
1999 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3)
2000 return true;
2001
2002 MVT VT = N.getSimpleValueType();
2003 SDLoc DL(N);
2004 if (FoundAnyExtend) {
2005 SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X);
2006 insertDAGNode(DAG, N, NewX);
2007 X = NewX;
2008 }
2009
2010 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT);
2011 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask);
2012 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1));
2013
2014 // Insert the new nodes into the topological ordering. We must do this in
2015 // a valid topological ordering as nothing is going to go back and re-sort
2016 // these nodes. We continually insert before 'N' in sequence as this is
2017 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2018 // hierarchy left to express.
2019 insertDAGNode(DAG, N, NewMask);
2020 insertDAGNode(DAG, N, NewAnd);
2021 insertDAGNode(DAG, N, NewShift);
2022 DAG.ReplaceAllUsesWith(N, NewShift);
2023 DAG.RemoveDeadNode(N.getNode());
2024
2025 AM.Scale = 1 << ShiftAmt;
2026 AM.IndexReg = NewAnd;
2027 return false;
2028}
2029
2030// Implement some heroics to detect shifts of masked values where the mask can
2031// be replaced by extending the shift and undoing that in the addressing mode
2032// scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and
2033// (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in
2034// the addressing mode. This results in code such as:
2035//
2036// int f(short *y, int *lookup_table) {
2037// ...
2038// return *y + lookup_table[*y >> 11];
2039// }
2040//
2041// Turning into:
2042// movzwl (%rdi), %eax
2043// movl %eax, %ecx
2044// shrl $11, %ecx
2045// addl (%rsi,%rcx,4), %eax
2046//
2047// Instead of:
2048// movzwl (%rdi), %eax
2049// movl %eax, %ecx
2050// shrl $9, %ecx
2051// andl $124, %rcx
2052// addl (%rsi,%rcx), %eax
2053//
2054// Note that this function assumes the mask is provided as a mask *after* the
2055// value is shifted. The input chain may or may not match that, but computing
2056// such a mask is trivial.
2058 uint64_t Mask,
2059 SDValue Shift, SDValue X,
2060 X86ISelAddressMode &AM) {
2061 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() ||
2062 !isa<ConstantSDNode>(Shift.getOperand(1)))
2063 return true;
2064
2065 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
2066 unsigned MaskLZ = llvm::countl_zero(Mask);
2067 unsigned MaskTZ = llvm::countr_zero(Mask);
2068
2069 // The amount of shift we're trying to fit into the addressing mode is taken
2070 // from the trailing zeros of the mask.
2071 unsigned AMShiftAmt = MaskTZ;
2072
2073 // There is nothing we can do here unless the mask is removing some bits.
2074 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
2075 if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
2076
2077 // We also need to ensure that mask is a continuous run of bits.
2078 if (llvm::countr_one(Mask >> MaskTZ) + MaskTZ + MaskLZ != 64)
2079 return true;
2080
2081 // Scale the leading zero count down based on the actual size of the value.
2082 // Also scale it down based on the size of the shift.
2083 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt;
2084 if (MaskLZ < ScaleDown)
2085 return true;
2086 MaskLZ -= ScaleDown;
2087
2088 // The final check is to ensure that any masked out high bits of X are
2089 // already known to be zero. Otherwise, the mask has a semantic impact
2090 // other than masking out a couple of low bits. Unfortunately, because of
2091 // the mask, zero extensions will be removed from operands in some cases.
2092 // This code works extra hard to look through extensions because we can
2093 // replace them with zero extensions cheaply if necessary.
2094 bool ReplacingAnyExtend = false;
2095 if (X.getOpcode() == ISD::ANY_EXTEND) {
2096 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() -
2097 X.getOperand(0).getSimpleValueType().getSizeInBits();
2098 // Assume that we'll replace the any-extend with a zero-extend, and
2099 // narrow the search to the extended value.
2100 X = X.getOperand(0);
2101 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits;
2102 ReplacingAnyExtend = true;
2103 }
2104 APInt MaskedHighBits =
2105 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ);
2106 KnownBits Known = DAG.computeKnownBits(X);
2107 if (MaskedHighBits != Known.Zero) return true;
2108
2109 // We've identified a pattern that can be transformed into a single shift
2110 // and an addressing mode. Make it so.
2111 MVT VT = N.getSimpleValueType();
2112 if (ReplacingAnyExtend) {
2113 assert(X.getValueType() != VT);
2114 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND.
2115 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X);
2116 insertDAGNode(DAG, N, NewX);
2117 X = NewX;
2118 }
2119 SDLoc DL(N);
2120 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
2121 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
2122 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
2123 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewSRL, NewSHLAmt);
2124
2125 // Insert the new nodes into the topological ordering. We must do this in
2126 // a valid topological ordering as nothing is going to go back and re-sort
2127 // these nodes. We continually insert before 'N' in sequence as this is
2128 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2129 // hierarchy left to express.
2130 insertDAGNode(DAG, N, NewSRLAmt);
2131 insertDAGNode(DAG, N, NewSRL);
2132 insertDAGNode(DAG, N, NewSHLAmt);
2133 insertDAGNode(DAG, N, NewSHL);
2134 DAG.ReplaceAllUsesWith(N, NewSHL);
2135 DAG.RemoveDeadNode(N.getNode());
2136
2137 AM.Scale = 1 << AMShiftAmt;
2138 AM.IndexReg = NewSRL;
2139 return false;
2140}
2141
2142// Transform "(X >> SHIFT) & (MASK << C1)" to
2143// "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be
2144// matched to a BEXTR later. Returns false if the simplification is performed.
2146 uint64_t Mask,
2147 SDValue Shift, SDValue X,
2148 X86ISelAddressMode &AM,
2149 const X86Subtarget &Subtarget) {
2150 if (Shift.getOpcode() != ISD::SRL ||
2151 !isa<ConstantSDNode>(Shift.getOperand(1)) ||
2152 !Shift.hasOneUse() || !N.hasOneUse())
2153 return true;
2154
2155 // Only do this if BEXTR will be matched by matchBEXTRFromAndImm.
2156 if (!Subtarget.hasTBM() &&
2157 !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR()))
2158 return true;
2159
2160 // We need to ensure that mask is a continuous run of bits.
2161 if (!isShiftedMask_64(Mask)) return true;
2162
2163 unsigned ShiftAmt = Shift.getConstantOperandVal(1);
2164
2165 // The amount of shift we're trying to fit into the addressing mode is taken
2166 // from the trailing zeros of the mask.
2167 unsigned AMShiftAmt = llvm::countr_zero(Mask);
2168
2169 // There is nothing we can do here unless the mask is removing some bits.
2170 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits.
2171 if (AMShiftAmt == 0 || AMShiftAmt > 3) return true;
2172
2173 MVT VT = N.getSimpleValueType();
2174 SDLoc DL(N);
2175 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8);
2176 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, VT, X, NewSRLAmt);
2177 SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, VT);
2178 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, NewSRL, NewMask);
2179 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8);
2180 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewAnd, NewSHLAmt);
2181
2182 // Insert the new nodes into the topological ordering. We must do this in
2183 // a valid topological ordering as nothing is going to go back and re-sort
2184 // these nodes. We continually insert before 'N' in sequence as this is
2185 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no
2186 // hierarchy left to express.
2187 insertDAGNode(DAG, N, NewSRLAmt);
2188 insertDAGNode(DAG, N, NewSRL);
2189 insertDAGNode(DAG, N, NewMask);
2190 insertDAGNode(DAG, N, NewAnd);
2191 insertDAGNode(DAG, N, NewSHLAmt);
2192 insertDAGNode(DAG, N, NewSHL);
2193 DAG.ReplaceAllUsesWith(N, NewSHL);
2194 DAG.RemoveDeadNode(N.getNode());
2195
2196 AM.Scale = 1 << AMShiftAmt;
2197 AM.IndexReg = NewAnd;
2198 return false;
2199}
2200
2201bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM,
2202 unsigned Depth) {
2203 SDLoc dl(N);
2204 LLVM_DEBUG({
2205 dbgs() << "MatchAddress: ";
2206 AM.dump(CurDAG);
2207 });
2208 // Limit recursion.
2209 if (Depth > 5)
2210 return matchAddressBase(N, AM);
2211
2212 // If this is already a %rip relative address, we can only merge immediates
2213 // into it. Instead of handling this in every case, we handle it here.
2214 // RIP relative addressing: %rip + 32-bit displacement!
2215 if (AM.isRIPRelative()) {
2216 // FIXME: JumpTable and ExternalSymbol address currently don't like
2217 // displacements. It isn't very important, but this should be fixed for
2218 // consistency.
2219 if (!(AM.ES || AM.MCSym) && AM.JT != -1)
2220 return true;
2221
2222 if (auto *Cst = dyn_cast<ConstantSDNode>(N))
2223 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM))
2224 return false;
2225 return true;
2226 }
2227
2228 switch (N.getOpcode()) {
2229 default: break;
2230 case ISD::LOCAL_RECOVER: {
2231 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0)
2232 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) {
2233 // Use the symbol and don't prefix it.
2234 AM.MCSym = ESNode->getMCSymbol();
2235 return false;
2236 }
2237 break;
2238 }
2239 case ISD::Constant: {
2240 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
2241 if (!foldOffsetIntoAddress(Val, AM))
2242 return false;
2243 break;
2244 }
2245
2246 case X86ISD::Wrapper:
2247 case X86ISD::WrapperRIP:
2248 if (!matchWrapper(N, AM))
2249 return false;
2250 break;
2251
2252 case ISD::LOAD:
2253 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM))
2254 return false;
2255 break;
2256
2257 case ISD::FrameIndex:
2258 if (AM.BaseType == X86ISelAddressMode::RegBase &&
2259 AM.Base_Reg.getNode() == nullptr &&
2260 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) {
2261 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
2262 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
2263 return false;
2264 }
2265 break;
2266
2267 case ISD::SHL:
2268 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
2269 break;
2270
2271 if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2272 unsigned Val = CN->getZExtValue();
2273 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so
2274 // that the base operand remains free for further matching. If
2275 // the base doesn't end up getting used, a post-processing step
2276 // in MatchAddress turns (,x,2) into (x,x), which is cheaper.
2277 if (Val == 1 || Val == 2 || Val == 3) {
2278 AM.Scale = 1 << Val;
2279 SDValue ShVal = N.getOperand(0);
2280
2281 // Okay, we know that we have a scale by now. However, if the scaled
2282 // value is an add of something and a constant, we can fold the
2283 // constant into the disp field here.
2284 if (CurDAG->isBaseWithConstantOffset(ShVal)) {
2285 AM.IndexReg = ShVal.getOperand(0);
2286 auto *AddVal = cast<ConstantSDNode>(ShVal.getOperand(1));
2287 uint64_t Disp = (uint64_t)AddVal->getSExtValue() << Val;
2288 if (!foldOffsetIntoAddress(Disp, AM))
2289 return false;
2290 }
2291
2292 AM.IndexReg = ShVal;
2293 return false;
2294 }
2295 }
2296 break;
2297
2298 case ISD::SRL: {
2299 // Scale must not be used already.
2300 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
2301
2302 // We only handle up to 64-bit values here as those are what matter for
2303 // addressing mode optimizations.
2304 assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
2305 "Unexpected value size!");
2306
2307 SDValue And = N.getOperand(0);
2308 if (And.getOpcode() != ISD::AND) break;
2309 SDValue X = And.getOperand(0);
2310
2311 // The mask used for the transform is expected to be post-shift, but we
2312 // found the shift first so just apply the shift to the mask before passing
2313 // it down.
2314 if (!isa<ConstantSDNode>(N.getOperand(1)) ||
2315 !isa<ConstantSDNode>(And.getOperand(1)))
2316 break;
2317 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1);
2318
2319 // Try to fold the mask and shift into the scale, and return false if we
2320 // succeed.
2321 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM))
2322 return false;
2323 break;
2324 }
2325
2326 case ISD::SMUL_LOHI:
2327 case ISD::UMUL_LOHI:
2328 // A mul_lohi where we need the low part can be folded as a plain multiply.
2329 if (N.getResNo() != 0) break;
2330 [[fallthrough]];
2331 case ISD::MUL:
2332 case X86ISD::MUL_IMM:
2333 // X*[3,5,9] -> X+X*[2,4,8]
2334 if (AM.BaseType == X86ISelAddressMode::RegBase &&
2335 AM.Base_Reg.getNode() == nullptr &&
2336 AM.IndexReg.getNode() == nullptr) {
2337 if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1)))
2338 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 ||
2339 CN->getZExtValue() == 9) {
2340 AM.Scale = unsigned(CN->getZExtValue())-1;
2341
2342 SDValue MulVal = N.getOperand(0);
2343 SDValue Reg;
2344
2345 // Okay, we know that we have a scale by now. However, if the scaled
2346 // value is an add of something and a constant, we can fold the
2347 // constant into the disp field here.
2348 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
2349 isa<ConstantSDNode>(MulVal.getOperand(1))) {
2350 Reg = MulVal.getOperand(0);
2351 auto *AddVal = cast<ConstantSDNode>(MulVal.getOperand(1));
2352 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue();
2353 if (foldOffsetIntoAddress(Disp, AM))
2354 Reg = N.getOperand(0);
2355 } else {
2356 Reg = N.getOperand(0);
2357 }
2358
2359 AM.IndexReg = AM.Base_Reg = Reg;
2360 return false;
2361 }
2362 }
2363 break;
2364
2365 case ISD::SUB: {
2366 // Given A-B, if A can be completely folded into the address and
2367 // the index field with the index field unused, use -B as the index.
2368 // This is a win if a has multiple parts that can be folded into
2369 // the address. Also, this saves a mov if the base register has
2370 // other uses, since it avoids a two-address sub instruction, however
2371 // it costs an additional mov if the index register has other uses.
2372
2373 // Add an artificial use to this node so that we can keep track of
2374 // it if it gets CSE'd with a different node.
2375 HandleSDNode Handle(N);
2376
2377 // Test if the LHS of the sub can be folded.
2378 X86ISelAddressMode Backup = AM;
2379 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) {
2380 N = Handle.getValue();
2381 AM = Backup;
2382 break;
2383 }
2384 N = Handle.getValue();
2385 // Test if the index field is free for use.
2386 if (AM.IndexReg.getNode() || AM.isRIPRelative()) {
2387 AM = Backup;
2388 break;
2389 }
2390
2391 int Cost = 0;
2392 SDValue RHS = N.getOperand(1);
2393 // If the RHS involves a register with multiple uses, this
2394 // transformation incurs an extra mov, due to the neg instruction
2395 // clobbering its operand.
2396 if (!RHS.getNode()->hasOneUse() ||
2397 RHS.getNode()->getOpcode() == ISD::CopyFromReg ||
2398 RHS.getNode()->getOpcode() == ISD::TRUNCATE ||
2399 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND ||
2400 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND &&
2401 RHS.getOperand(0).getValueType() == MVT::i32))
2402 ++Cost;
2403 // If the base is a register with multiple uses, this
2404 // transformation may save a mov.
2405 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() &&
2406 !AM.Base_Reg.getNode()->hasOneUse()) ||
2407 AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2408 --Cost;
2409 // If the folded LHS was interesting, this transformation saves
2410 // address arithmetic.
2411 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) +
2412 ((AM.Disp != 0) && (Backup.Disp == 0)) +
2413 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2)
2414 --Cost;
2415 // If it doesn't look like it may be an overall win, don't do it.
2416 if (Cost >= 0) {
2417 AM = Backup;
2418 break;
2419 }
2420
2421 // Ok, the transformation is legal and appears profitable. Go for it.
2422 // Negation will be emitted later to avoid creating dangling nodes if this
2423 // was an unprofitable LEA.
2424 AM.IndexReg = RHS;
2425 AM.NegateIndex = true;
2426 AM.Scale = 1;
2427 return false;
2428 }
2429
2430 case ISD::ADD:
2431 if (!matchAdd(N, AM, Depth))
2432 return false;
2433 break;
2434
2435 case ISD::OR:
2436 // We want to look through a transform in InstCombine and DAGCombiner that
2437 // turns 'add' into 'or', so we can treat this 'or' exactly like an 'add'.
2438 // Example: (or (and x, 1), (shl y, 3)) --> (add (and x, 1), (shl y, 3))
2439 // An 'lea' can then be used to match the shift (multiply) and add:
2440 // and $1, %esi
2441 // lea (%rsi, %rdi, 8), %rax
2442 if (CurDAG->haveNoCommonBitsSet(N.getOperand(0), N.getOperand(1)) &&
2443 !matchAdd(N, AM, Depth))
2444 return false;
2445 break;
2446
2447 case ISD::XOR:
2448 // We want to look through a transform in InstCombine that
2449 // turns 'add' with min_signed_val into 'xor', so we can treat this 'xor'
2450 // exactly like an 'add'.
2451 if (isMinSignedConstant(N.getOperand(1)) && !matchAdd(N, AM, Depth))
2452 return false;
2453 break;
2454
2455 case ISD::AND: {
2456 // Perform some heroic transforms on an and of a constant-count shift
2457 // with a constant to enable use of the scaled offset field.
2458
2459 // Scale must not be used already.
2460 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break;
2461
2462 // We only handle up to 64-bit values here as those are what matter for
2463 // addressing mode optimizations.
2464 assert(N.getSimpleValueType().getSizeInBits() <= 64 &&
2465 "Unexpected value size!");
2466
2467 if (!isa<ConstantSDNode>(N.getOperand(1)))
2468 break;
2469
2470 if (N.getOperand(0).getOpcode() == ISD::SRL) {
2471 SDValue Shift = N.getOperand(0);
2472 SDValue X = Shift.getOperand(0);
2473
2474 uint64_t Mask = N.getConstantOperandVal(1);
2475
2476 // Try to fold the mask and shift into an extract and scale.
2477 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM))
2478 return false;
2479
2480 // Try to fold the mask and shift directly into the scale.
2481 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM))
2482 return false;
2483
2484 // Try to fold the mask and shift into BEXTR and scale.
2485 if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget))
2486 return false;
2487 }
2488
2489 // Try to swap the mask and shift to place shifts which can be done as
2490 // a scale on the outside of the mask.
2491 if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM))
2492 return false;
2493
2494 break;
2495 }
2496 case ISD::ZERO_EXTEND: {
2497 // Try to widen a zexted shift left to the same size as its use, so we can
2498 // match the shift as a scale factor.
2499 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1)
2500 break;
2501
2502 // Peek through mask: zext(and(shl(x,c1),c2))
2503 SDValue Src = N.getOperand(0);
2504 APInt Mask = APInt::getAllOnes(Src.getScalarValueSizeInBits());
2505 if (Src.getOpcode() == ISD::AND && Src.hasOneUse())
2506 if (auto *MaskC = dyn_cast<ConstantSDNode>(Src.getOperand(1))) {
2507 Mask = MaskC->getAPIntValue();
2508 Src = Src.getOperand(0);
2509 }
2510
2511 if (Src.getOpcode() != ISD::SHL || !Src.hasOneUse())
2512 break;
2513
2514 // Give up if the shift is not a valid scale factor [1,2,3].
2515 SDValue ShlSrc = Src.getOperand(0);
2516 SDValue ShlAmt = Src.getOperand(1);
2517 auto *ShAmtC = dyn_cast<ConstantSDNode>(ShlAmt);
2518 if (!ShAmtC)
2519 break;
2520 unsigned ShAmtV = ShAmtC->getZExtValue();
2521 if (ShAmtV > 3)
2522 break;
2523
2524 // The narrow shift must only shift out zero bits (it must be 'nuw').
2525 // That makes it safe to widen to the destination type.
2526 APInt HighZeros =
2527 APInt::getHighBitsSet(ShlSrc.getValueSizeInBits(), ShAmtV);
2528 if (!CurDAG->MaskedValueIsZero(ShlSrc, HighZeros & Mask))
2529 break;
2530
2531 // zext (shl nuw i8 %x, C1) to i32
2532 // --> shl (zext i8 %x to i32), (zext C1)
2533 // zext (and (shl nuw i8 %x, C1), C2) to i32
2534 // --> shl (zext i8 (and %x, C2 >> C1) to i32), (zext C1)
2535 MVT SrcVT = ShlSrc.getSimpleValueType();
2536 MVT VT = N.getSimpleValueType();
2537 SDLoc DL(N);
2538
2539 SDValue Res = ShlSrc;
2540 if (!Mask.isAllOnes()) {
2541 Res = CurDAG->getConstant(Mask.lshr(ShAmtV), DL, SrcVT);
2542 insertDAGNode(*CurDAG, N, Res);
2543 Res = CurDAG->getNode(ISD::AND, DL, SrcVT, ShlSrc, Res);
2544 insertDAGNode(*CurDAG, N, Res);
2545 }
2546 SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Res);
2547 insertDAGNode(*CurDAG, N, Zext);
2548 SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, ShlAmt);
2549 insertDAGNode(*CurDAG, N, NewShl);
2550
2551 // Convert the shift to scale factor.
2552 AM.Scale = 1 << ShAmtV;
2553 AM.IndexReg = Zext;
2554
2555 CurDAG->ReplaceAllUsesWith(N, NewShl);
2556 CurDAG->RemoveDeadNode(N.getNode());
2557 return false;
2558 }
2559 }
2560
2561 return matchAddressBase(N, AM);
2562}
2563
2564/// Helper for MatchAddress. Add the specified node to the
2565/// specified addressing mode without any further recursion.
2566bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) {
2567 // Is the base register already occupied?
2568 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) {
2569 // If so, check to see if the scale index register is set.
2570 if (!AM.IndexReg.getNode()) {
2571 AM.IndexReg = N;
2572 AM.Scale = 1;
2573 return false;
2574 }
2575
2576 // Otherwise, we cannot select it.
2577 return true;
2578 }
2579
2580 // Default, generate it as a register.
2581 AM.BaseType = X86ISelAddressMode::RegBase;
2582 AM.Base_Reg = N;
2583 return false;
2584}
2585
2586bool X86DAGToDAGISel::matchVectorAddressRecursively(SDValue N,
2587 X86ISelAddressMode &AM,
2588 unsigned Depth) {
2589 SDLoc dl(N);
2590 LLVM_DEBUG({
2591 dbgs() << "MatchVectorAddress: ";
2592 AM.dump(CurDAG);
2593 });
2594 // Limit recursion.
2595 if (Depth > 5)
2596 return matchAddressBase(N, AM);
2597
2598 // TODO: Support other operations.
2599 switch (N.getOpcode()) {
2600 case ISD::Constant: {
2601 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue();
2602 if (!foldOffsetIntoAddress(Val, AM))
2603 return false;
2604 break;
2605 }
2606 case X86ISD::Wrapper:
2607 if (!matchWrapper(N, AM))
2608 return false;
2609 break;
2610 case ISD::ADD: {
2611 // Add an artificial use to this node so that we can keep track of
2612 // it if it gets CSE'd with a different node.
2613 HandleSDNode Handle(N);
2614
2615 X86ISelAddressMode Backup = AM;
2616 if (!matchVectorAddressRecursively(N.getOperand(0), AM, Depth + 1) &&
2617 !matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM,
2618 Depth + 1))
2619 return false;
2620 AM = Backup;
2621
2622 // Try again after commuting the operands.
2623 if (!matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM,
2624 Depth + 1) &&
2625 !matchVectorAddressRecursively(Handle.getValue().getOperand(0), AM,
2626 Depth + 1))
2627 return false;
2628 AM = Backup;
2629
2630 N = Handle.getValue();
2631 break;
2632 }
2633 }
2634
2635 return matchAddressBase(N, AM);
2636}
2637
2638/// Helper for selectVectorAddr. Handles things that can be folded into a
2639/// gather/scatter address. The index register and scale should have already
2640/// been handled.
2641bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) {
2642 return matchVectorAddressRecursively(N, AM, 0);
2643}
2644
2645bool X86DAGToDAGISel::selectVectorAddr(MemSDNode *Parent, SDValue BasePtr,
2646 SDValue IndexOp, SDValue ScaleOp,
2647 SDValue &Base, SDValue &Scale,
2648 SDValue &Index, SDValue &Disp,
2649 SDValue &Segment) {
2650 X86ISelAddressMode AM;
2651 AM.IndexReg = IndexOp;
2652 AM.Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
2653
2654 unsigned AddrSpace = Parent->getPointerInfo().getAddrSpace();
2655 if (AddrSpace == X86AS::GS)
2656 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2657 if (AddrSpace == X86AS::FS)
2658 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2659 if (AddrSpace == X86AS::SS)
2660 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
2661
2662 SDLoc DL(BasePtr);
2663 MVT VT = BasePtr.getSimpleValueType();
2664
2665 // Try to match into the base and displacement fields.
2666 if (matchVectorAddress(BasePtr, AM))
2667 return false;
2668
2669 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2670 return true;
2671}
2672
2673/// Returns true if it is able to pattern match an addressing mode.
2674/// It returns the operands which make up the maximal addressing mode it can
2675/// match by reference.
2676///
2677/// Parent is the parent node of the addr operand that is being matched. It
2678/// is always a load, store, atomic node, or null. It is only null when
2679/// checking memory operands for inline asm nodes.
2680bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base,
2681 SDValue &Scale, SDValue &Index,
2682 SDValue &Disp, SDValue &Segment) {
2683 X86ISelAddressMode AM;
2684
2685 if (Parent &&
2686 // This list of opcodes are all the nodes that have an "addr:$ptr" operand
2687 // that are not a MemSDNode, and thus don't have proper addrspace info.
2688 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme
2689 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores
2690 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme
2691 Parent->getOpcode() != X86ISD::ENQCMD && // Fixme
2692 Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme
2693 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp
2694 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp
2695 unsigned AddrSpace =
2696 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace();
2697 if (AddrSpace == X86AS::GS)
2698 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16);
2699 if (AddrSpace == X86AS::FS)
2700 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16);
2701 if (AddrSpace == X86AS::SS)
2702 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16);
2703 }
2704
2705 // Save the DL and VT before calling matchAddress, it can invalidate N.
2706 SDLoc DL(N);
2707 MVT VT = N.getSimpleValueType();
2708
2709 if (matchAddress(N, AM))
2710 return false;
2711
2712 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2713 return true;
2714}
2715
2716bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) {
2717 // In static codegen with small code model, we can get the address of a label
2718 // into a register with 'movl'
2719 if (N->getOpcode() != X86ISD::Wrapper)
2720 return false;
2721
2722 N = N.getOperand(0);
2723
2724 // At least GNU as does not accept 'movl' for TPOFF relocations.
2725 // FIXME: We could use 'movl' when we know we are targeting MC.
2726 if (N->getOpcode() == ISD::TargetGlobalTLSAddress)
2727 return false;
2728
2729 Imm = N;
2730 if (N->getOpcode() != ISD::TargetGlobalAddress)
2731 return TM.getCodeModel() == CodeModel::Small;
2732
2733 std::optional<ConstantRange> CR =
2734 cast<GlobalAddressSDNode>(N)->getGlobal()->getAbsoluteSymbolRange();
2735 if (!CR)
2736 return TM.getCodeModel() == CodeModel::Small;
2737
2738 return CR->getUnsignedMax().ult(1ull << 32);
2739}
2740
2741bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base,
2742 SDValue &Scale, SDValue &Index,
2743 SDValue &Disp, SDValue &Segment) {
2744 // Save the debug loc before calling selectLEAAddr, in case it invalidates N.
2745 SDLoc DL(N);
2746
2747 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment))
2748 return false;
2749
2750 auto *RN = dyn_cast<RegisterSDNode>(Base);
2751 if (RN && RN->getReg() == 0)
2752 Base = CurDAG->getRegister(0, MVT::i64);
2753 else if (Base.getValueType() == MVT::i32 && !isa<FrameIndexSDNode>(Base)) {
2754 // Base could already be %rip, particularly in the x32 ABI.
2755 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
2756 MVT::i64), 0);
2757 Base = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
2758 Base);
2759 }
2760
2761 RN = dyn_cast<RegisterSDNode>(Index);
2762 if (RN && RN->getReg() == 0)
2763 Index = CurDAG->getRegister(0, MVT::i64);
2764 else {
2765 assert(Index.getValueType() == MVT::i32 &&
2766 "Expect to be extending 32-bit registers for use in LEA");
2767 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL,
2768 MVT::i64), 0);
2769 Index = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef,
2770 Index);
2771 }
2772
2773 return true;
2774}
2775
2776/// Calls SelectAddr and determines if the maximal addressing
2777/// mode it matches can be cost effectively emitted as an LEA instruction.
2778bool X86DAGToDAGISel::selectLEAAddr(SDValue N,
2779 SDValue &Base, SDValue &Scale,
2780 SDValue &Index, SDValue &Disp,
2781 SDValue &Segment) {
2782 X86ISelAddressMode AM;
2783
2784 // Save the DL and VT before calling matchAddress, it can invalidate N.
2785 SDLoc DL(N);
2786 MVT VT = N.getSimpleValueType();
2787
2788 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support
2789 // segments.
2790 SDValue Copy = AM.Segment;
2791 SDValue T = CurDAG->getRegister(0, MVT::i32);
2792 AM.Segment = T;
2793 if (matchAddress(N, AM))
2794 return false;
2795 assert (T == AM.Segment);
2796 AM.Segment = Copy;
2797
2798 unsigned Complexity = 0;
2799 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode())
2800 Complexity = 1;
2801 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase)
2802 Complexity = 4;
2803
2804 if (AM.IndexReg.getNode())
2805 Complexity++;
2806
2807 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with
2808 // a simple shift.
2809 if (AM.Scale > 1)
2810 Complexity++;
2811
2812 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA
2813 // to a LEA. This is determined with some experimentation but is by no means
2814 // optimal (especially for code size consideration). LEA is nice because of
2815 // its three-address nature. Tweak the cost function again when we can run
2816 // convertToThreeAddress() at register allocation time.
2817 if (AM.hasSymbolicDisplacement()) {
2818 // For X86-64, always use LEA to materialize RIP-relative addresses.
2819 if (Subtarget->is64Bit())
2820 Complexity = 4;
2821 else
2822 Complexity += 2;
2823 }
2824
2825 // Heuristic: try harder to form an LEA from ADD if the operands set flags.
2826 // Unlike ADD, LEA does not affect flags, so we will be less likely to require
2827 // duplicating flag-producing instructions later in the pipeline.
2828 if (N.getOpcode() == ISD::ADD) {
2829 auto isMathWithFlags = [](SDValue V) {
2830 switch (V.getOpcode()) {
2831 case X86ISD::ADD:
2832 case X86ISD::SUB:
2833 case X86ISD::ADC:
2834 case X86ISD::SBB:
2835 case X86ISD::SMUL:
2836 case X86ISD::UMUL:
2837 /* TODO: These opcodes can be added safely, but we may want to justify
2838 their inclusion for different reasons (better for reg-alloc).
2839 case X86ISD::OR:
2840 case X86ISD::XOR:
2841 case X86ISD::AND:
2842 */
2843 // Value 1 is the flag output of the node - verify it's not dead.
2844 return !SDValue(V.getNode(), 1).use_empty();
2845 default:
2846 return false;
2847 }
2848 };
2849 // TODO: We might want to factor in whether there's a load folding
2850 // opportunity for the math op that disappears with LEA.
2851 if (isMathWithFlags(N.getOperand(0)) || isMathWithFlags(N.getOperand(1)))
2852 Complexity++;
2853 }
2854
2855 if (AM.Disp)
2856 Complexity++;
2857
2858 // If it isn't worth using an LEA, reject it.
2859 if (Complexity <= 2)
2860 return false;
2861
2862 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment);
2863 return true;
2864}
2865
2866/// This is only run on TargetGlobalTLSAddress nodes.
2867bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base,
2868 SDValue &Scale, SDValue &Index,
2869 SDValue &Disp, SDValue &Segment) {
2870 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress);
2871 auto *GA = cast<GlobalAddressSDNode>(N);
2872
2873 X86ISelAddressMode AM;
2874 AM.GV = GA->getGlobal();
2875 AM.Disp += GA->getOffset();
2876 AM.SymbolFlags = GA->getTargetFlags();
2877
2878 if (Subtarget->is32Bit()) {
2879 AM.Scale = 1;
2880 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32);
2881 }
2882
2883 MVT VT = N.getSimpleValueType();
2884 getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment);
2885 return true;
2886}
2887
2888bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) {
2889 // Keep track of the original value type and whether this value was
2890 // truncated. If we see a truncation from pointer type to VT that truncates
2891 // bits that are known to be zero, we can use a narrow reference.
2892 EVT VT = N.getValueType();
2893 bool WasTruncated = false;
2894 if (N.getOpcode() == ISD::TRUNCATE) {
2895 WasTruncated = true;
2896 N = N.getOperand(0);
2897 }
2898
2899 if (N.getOpcode() != X86ISD::Wrapper)
2900 return false;
2901
2902 // We can only use non-GlobalValues as immediates if they were not truncated,
2903 // as we do not have any range information. If we have a GlobalValue and the
2904 // address was not truncated, we can select it as an operand directly.
2905 unsigned Opc = N.getOperand(0)->getOpcode();
2906 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) {
2907 Op = N.getOperand(0);
2908 // We can only select the operand directly if we didn't have to look past a
2909 // truncate.
2910 return !WasTruncated;
2911 }
2912
2913 // Check that the global's range fits into VT.
2914 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0));
2915 std::optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2916 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits()))
2917 return false;
2918
2919 // Okay, we can use a narrow reference.
2920 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT,
2921 GA->getOffset(), GA->getTargetFlags());
2922 return true;
2923}
2924
2925bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N,
2926 SDValue &Base, SDValue &Scale,
2927 SDValue &Index, SDValue &Disp,
2928 SDValue &Segment) {
2929 assert(Root && P && "Unknown root/parent nodes");
2930 if (!ISD::isNON_EXTLoad(N.getNode()) ||
2931 !IsProfitableToFold(N, P, Root) ||
2932 !IsLegalToFold(N, P, Root, OptLevel))
2933 return false;
2934
2935 return selectAddr(N.getNode(),
2936 N.getOperand(1), Base, Scale, Index, Disp, Segment);
2937}
2938
2939bool X86DAGToDAGISel::tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N,
2940 SDValue &Base, SDValue &Scale,
2941 SDValue &Index, SDValue &Disp,
2942 SDValue &Segment) {
2943 assert(Root && P && "Unknown root/parent nodes");
2944 if (N->getOpcode() != X86ISD::VBROADCAST_LOAD ||
2945 !IsProfitableToFold(N, P, Root) ||
2946 !IsLegalToFold(N, P, Root, OptLevel))
2947 return false;
2948
2949 return selectAddr(N.getNode(),
2950 N.getOperand(1), Base, Scale, Index, Disp, Segment);
2951}
2952
2953/// Return an SDNode that returns the value of the global base register.
2954/// Output instructions required to initialize the global base register,
2955/// if necessary.
2956SDNode *X86DAGToDAGISel::getGlobalBaseReg() {
2957 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
2958 auto &DL = MF->getDataLayout();
2959 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode();
2960}
2961
2962bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const {
2963 if (N->getOpcode() == ISD::TRUNCATE)
2964 N = N->getOperand(0).getNode();
2965 if (N->getOpcode() != X86ISD::Wrapper)
2966 return false;
2967
2968 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0));
2969 if (!GA)
2970 return false;
2971
2972 std::optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange();
2973 if (!CR)
2974 return Width == 32 && TM.getCodeModel() == CodeModel::Small;
2975
2976 return CR->getSignedMin().sge(-1ull << Width) &&
2977 CR->getSignedMax().slt(1ull << Width);
2978}
2979
2980X86::CondCode X86DAGToDAGISel::getCondFromNode(SDNode *N) const {
2981 assert(N->isMachineOpcode() && "Unexpected node");
2982 unsigned Opc = N->getMachineOpcode();
2983 const MCInstrDesc &MCID = getInstrInfo()->get(Opc);
2984 int CondNo = X86::getCondSrcNoFromDesc(MCID);
2985 if (CondNo < 0)
2986 return X86::COND_INVALID;
2987
2988 return static_cast<X86::CondCode>(N->getConstantOperandVal(CondNo));
2989}
2990
2991/// Test whether the given X86ISD::CMP node has any users that use a flag
2992/// other than ZF.
2993bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const {
2994 // Examine each user of the node.
2995 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
2996 UI != UE; ++UI) {
2997 // Only check things that use the flags.
2998 if (UI.getUse().getResNo() != Flags.getResNo())
2999 continue;
3000 // Only examine CopyToReg uses that copy to EFLAGS.
3001 if (UI->getOpcode() != ISD::CopyToReg ||
3002 cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
3003 return false;
3004 // Examine each user of the CopyToReg use.
3005 for (SDNode::use_iterator FlagUI = UI->use_begin(),
3006 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
3007 // Only examine the Flag result.
3008 if (FlagUI.getUse().getResNo() != 1) continue;
3009 // Anything unusual: assume conservatively.
3010 if (!FlagUI->isMachineOpcode()) return false;
3011 // Examine the condition code of the user.
3012 X86::CondCode CC = getCondFromNode(*FlagUI);
3013
3014 switch (CC) {
3015 // Comparisons which only use the zero flag.
3016 case X86::COND_E: case X86::COND_NE:
3017 continue;
3018 // Anything else: assume conservatively.
3019 default:
3020 return false;
3021 }
3022 }
3023 }
3024 return true;
3025}
3026
3027/// Test whether the given X86ISD::CMP node has any uses which require the SF
3028/// flag to be accurate.
3029bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const {
3030 // Examine each user of the node.
3031 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
3032 UI != UE; ++UI) {
3033 // Only check things that use the flags.
3034 if (UI.getUse().getResNo() != Flags.getResNo())
3035 continue;
3036 // Only examine CopyToReg uses that copy to EFLAGS.
3037 if (UI->getOpcode() != ISD::CopyToReg ||
3038 cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
3039 return false;
3040 // Examine each user of the CopyToReg use.
3041 for (SDNode::use_iterator FlagUI = UI->use_begin(),
3042 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) {
3043 // Only examine the Flag result.
3044 if (FlagUI.getUse().getResNo() != 1) continue;
3045 // Anything unusual: assume conservatively.
3046 if (!FlagUI->isMachineOpcode()) return false;
3047 // Examine the condition code of the user.
3048 X86::CondCode CC = getCondFromNode(*FlagUI);
3049
3050 switch (CC) {
3051 // Comparisons which don't examine the SF flag.
3052 case X86::COND_A: case X86::COND_AE:
3053 case X86::COND_B: case X86::COND_BE:
3054 case X86::COND_E: case X86::COND_NE:
3055 case X86::COND_O: case X86::COND_NO:
3056 case X86::COND_P: case X86::COND_NP:
3057 continue;
3058 // Anything else: assume conservatively.
3059 default:
3060 return false;
3061 }
3062 }
3063 }
3064 return true;
3065}
3066
3068 switch (CC) {
3069 // Comparisons which don't examine the CF flag.
3070 case X86::COND_O: case X86::COND_NO:
3071 case X86::COND_E: case X86::COND_NE:
3072 case X86::COND_S: case X86::COND_NS:
3073 case X86::COND_P: case X86::COND_NP:
3074 case X86::COND_L: case X86::COND_GE:
3075 case X86::COND_G: case X86::COND_LE:
3076 return false;
3077 // Anything else: assume conservatively.
3078 default:
3079 return true;
3080 }
3081}
3082
3083/// Test whether the given node which sets flags has any uses which require the
3084/// CF flag to be accurate.
3085 bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const {
3086 // Examine each user of the node.
3087 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end();
3088 UI != UE; ++UI) {
3089 // Only check things that use the flags.
3090 if (UI.getUse().getResNo() != Flags.getResNo())
3091 continue;
3092
3093 unsigned UIOpc = UI->getOpcode();
3094
3095 if (UIOpc == ISD::CopyToReg) {
3096 // Only examine CopyToReg uses that copy to EFLAGS.
3097 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS)
3098 return false;
3099 // Examine each user of the CopyToReg use.
3100 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end();
3101 FlagUI != FlagUE; ++FlagUI) {
3102 // Only examine the Flag result.
3103 if (FlagUI.getUse().getResNo() != 1)
3104 continue;
3105 // Anything unusual: assume conservatively.
3106 if (!FlagUI->isMachineOpcode())
3107 return false;
3108 // Examine the condition code of the user.
3109 X86::CondCode CC = getCondFromNode(*FlagUI);
3110
3111 if (mayUseCarryFlag(CC))
3112 return false;
3113 }
3114
3115 // This CopyToReg is ok. Move on to the next user.
3116 continue;
3117 }
3118
3119 // This might be an unselected node. So look for the pre-isel opcodes that
3120 // use flags.
3121 unsigned CCOpNo;
3122 switch (UIOpc) {
3123 default:
3124 // Something unusual. Be conservative.
3125 return false;
3126 case X86ISD::SETCC: CCOpNo = 0; break;
3127 case X86ISD::SETCC_CARRY: CCOpNo = 0; break;
3128 case X86ISD::CMOV: CCOpNo = 2; break;
3129 case X86ISD::BRCOND: CCOpNo = 2; break;
3130 }
3131
3132 X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo);
3133 if (mayUseCarryFlag(CC))
3134 return false;
3135 }
3136 return true;
3137}
3138
3139/// Check whether or not the chain ending in StoreNode is suitable for doing
3140/// the {load; op; store} to modify transformation.
3142 SDValue StoredVal, SelectionDAG *CurDAG,
3143 unsigned LoadOpNo,
3144 LoadSDNode *&LoadNode,
3145 SDValue &InputChain) {
3146 // Is the stored value result 0 of the operation?
3147 if (StoredVal.getResNo() != 0) return false;
3148
3149 // Are there other uses of the operation other than the store?
3150 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false;
3151
3152 // Is the store non-extending and non-indexed?
3153 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal())
3154 return false;
3155
3156 SDValue Load = StoredVal->getOperand(LoadOpNo);
3157 // Is the stored value a non-extending and non-indexed load?
3158 if (!ISD::isNormalLoad(Load.getNode())) return false;
3159
3160 // Return LoadNode by reference.
3161 LoadNode = cast<LoadSDNode>(Load);
3162
3163 // Is store the only read of the loaded value?
3164 if (!Load.hasOneUse())
3165 return false;
3166
3167 // Is the address of the store the same as the load?
3168 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() ||
3169 LoadNode->getOffset() != StoreNode->getOffset())
3170 return false;
3171
3172 bool FoundLoad = false;
3173 SmallVector<SDValue, 4> ChainOps;
3174 SmallVector<const SDNode *, 4> LoopWorklist;
3176 const unsigned int Max = 1024;
3177
3178 // Visualization of Load-Op-Store fusion:
3179 // -------------------------
3180 // Legend:
3181 // *-lines = Chain operand dependencies.
3182 // |-lines = Normal operand dependencies.
3183 // Dependencies flow down and right. n-suffix references multiple nodes.
3184 //
3185 // C Xn C
3186 // * * *
3187 // * * *
3188 // Xn A-LD Yn TF Yn
3189 // * * \ | * |
3190 // * * \ | * |
3191 // * * \ | => A--LD_OP_ST
3192 // * * \| \
3193 // TF OP \
3194 // * | \ Zn
3195 // * | \
3196 // A-ST Zn
3197 //
3198
3199 // This merge induced dependences from: #1: Xn -> LD, OP, Zn
3200 // #2: Yn -> LD
3201 // #3: ST -> Zn
3202
3203 // Ensure the transform is safe by checking for the dual
3204 // dependencies to make sure we do not induce a loop.
3205
3206 // As LD is a predecessor to both OP and ST we can do this by checking:
3207 // a). if LD is a predecessor to a member of Xn or Yn.
3208 // b). if a Zn is a predecessor to ST.
3209
3210 // However, (b) can only occur through being a chain predecessor to
3211 // ST, which is the same as Zn being a member or predecessor of Xn,
3212 // which is a subset of LD being a predecessor of Xn. So it's
3213 // subsumed by check (a).
3214
3215 SDValue Chain = StoreNode->getChain();
3216
3217 // Gather X elements in ChainOps.
3218 if (Chain == Load.getValue(1)) {
3219 FoundLoad = true;
3220 ChainOps.push_back(Load.getOperand(0));
3221 } else if (Chain.getOpcode() == ISD::TokenFactor) {
3222 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) {
3223 SDValue Op = Chain.getOperand(i);
3224 if (Op == Load.getValue(1)) {
3225 FoundLoad = true;
3226 // Drop Load, but keep its chain. No cycle check necessary.
3227 ChainOps.push_back(Load.getOperand(0));
3228 continue;
3229 }
3230 LoopWorklist.push_back(Op.getNode());
3231 ChainOps.push_back(Op);
3232 }
3233 }
3234
3235 if (!FoundLoad)
3236 return false;
3237
3238 // Worklist is currently Xn. Add Yn to worklist.
3239 for (SDValue Op : StoredVal->ops())
3240 if (Op.getNode() != LoadNode)
3241 LoopWorklist.push_back(Op.getNode());
3242
3243 // Check (a) if Load is a predecessor to Xn + Yn
3244 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max,
3245 true))
3246 return false;
3247
3248 InputChain =
3249 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps);
3250 return true;
3251}
3252
3253// Change a chain of {load; op; store} of the same value into a simple op
3254// through memory of that value, if the uses of the modified value and its
3255// address are suitable.
3256//
3257// The tablegen pattern memory operand pattern is currently not able to match
3258// the case where the EFLAGS on the original operation are used.
3259//
3260// To move this to tablegen, we'll need to improve tablegen to allow flags to
3261// be transferred from a node in the pattern to the result node, probably with
3262// a new keyword. For example, we have this
3263// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
3264// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
3265// (implicit EFLAGS)]>;
3266// but maybe need something like this
3267// def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst",
3268// [(store (add (loadi64 addr:$dst), -1), addr:$dst),
3269// (transferrable EFLAGS)]>;
3270//
3271// Until then, we manually fold these and instruction select the operation
3272// here.
3273bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) {
3274 auto *StoreNode = cast<StoreSDNode>(Node);
3275 SDValue StoredVal = StoreNode->getOperand(1);
3276 unsigned Opc = StoredVal->getOpcode();
3277
3278 // Before we try to select anything, make sure this is memory operand size
3279 // and opcode we can handle. Note that this must match the code below that
3280 // actually lowers the opcodes.
3281 EVT MemVT = StoreNode->getMemoryVT();
3282 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 &&
3283 MemVT != MVT::i8)
3284 return false;
3285
3286 bool IsCommutable = false;
3287 bool IsNegate = false;
3288 switch (Opc) {
3289 default:
3290 return false;
3291 case X86ISD::SUB:
3292 IsNegate = isNullConstant(StoredVal.getOperand(0));
3293 break;
3294 case X86ISD::SBB:
3295 break;
3296 case X86ISD::ADD:
3297 case X86ISD::ADC:
3298 case X86ISD::AND:
3299 case X86ISD::OR:
3300 case X86ISD::XOR:
3301 IsCommutable = true;
3302 break;
3303 }
3304
3305 unsigned LoadOpNo = IsNegate ? 1 : 0;
3306 LoadSDNode *LoadNode = nullptr;
3307 SDValue InputChain;
3308 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
3309 LoadNode, InputChain)) {
3310 if (!IsCommutable)
3311 return false;
3312
3313 // This operation is commutable, try the other operand.
3314 LoadOpNo = 1;
3315 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo,
3316 LoadNode, InputChain))
3317 return false;
3318 }
3319
3320 SDValue Base, Scale, Index, Disp, Segment;
3321 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp,
3322 Segment))
3323 return false;
3324
3325 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16,
3326 unsigned Opc8) {
3327 switch (MemVT.getSimpleVT().SimpleTy) {
3328 case MVT::i64:
3329 return Opc64;
3330 case MVT::i32:
3331 return Opc32;
3332 case MVT::i16:
3333 return Opc16;
3334 case MVT::i8:
3335 return Opc8;
3336 default:
3337 llvm_unreachable("Invalid size!");
3338 }
3339 };
3340
3342 switch (Opc) {
3343 case X86ISD::SUB:
3344 // Handle negate.
3345 if (IsNegate) {
3346 unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m,
3347 X86::NEG8m);
3348 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
3349 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
3350 MVT::Other, Ops);
3351 break;
3352 }
3353 [[fallthrough]];
3354 case X86ISD::ADD:
3355 // Try to match inc/dec.
3356 if (!Subtarget->slowIncDec() || CurDAG->shouldOptForSize()) {
3357 bool IsOne = isOneConstant(StoredVal.getOperand(1));
3358 bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1));
3359 // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec.
3360 if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) {
3361 unsigned NewOpc =
3362 ((Opc == X86ISD::ADD) == IsOne)
3363 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m)
3364 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m);
3365 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain};
3366 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32,
3367 MVT::Other, Ops);
3368 break;
3369 }
3370 }
3371 [[fallthrough]];
3372 case X86ISD::ADC:
3373 case X86ISD::SBB:
3374 case X86ISD::AND:
3375 case X86ISD::OR:
3376 case X86ISD::XOR: {
3377 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) {
3378 switch (Opc) {
3379 case X86ISD::ADD:
3380 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr,
3381 X86::ADD8mr);
3382 case X86ISD::ADC:
3383 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr,
3384 X86::ADC8mr);
3385 case X86ISD::SUB:
3386 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr,
3387 X86::SUB8mr);
3388 case X86ISD::SBB:
3389 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr,
3390 X86::SBB8mr);
3391 case X86ISD::AND:
3392 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr,
3393 X86::AND8mr);
3394 case X86ISD::OR:
3395 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr);
3396 case X86ISD::XOR:
3397 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr,
3398 X86::XOR8mr);
3399 default:
3400 llvm_unreachable("Invalid opcode!");
3401 }
3402 };
3403 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) {
3404 switch (Opc) {
3405 case X86ISD::ADD:
3406 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi,
3407 X86::ADD8mi);
3408 case X86ISD::ADC:
3409 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi,
3410 X86::ADC8mi);
3411 case X86ISD::SUB:
3412 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi,
3413 X86::SUB8mi);
3414 case X86ISD::SBB:
3415 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi,
3416 X86::SBB8mi);
3417 case X86ISD::AND:
3418 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi,
3419 X86::AND8mi);
3420 case X86ISD::OR:
3421 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi,
3422 X86::OR8mi);
3423 case X86ISD::XOR:
3424 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi,
3425 X86::XOR8mi);
3426 default:
3427 llvm_unreachable("Invalid opcode!");
3428 }
3429 };
3430
3431 unsigned NewOpc = SelectRegOpcode(Opc);
3432 SDValue Operand = StoredVal->getOperand(1-LoadOpNo);
3433
3434 // See if the operand is a constant that we can fold into an immediate
3435 // operand.
3436 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) {
3437 int64_t OperandV = OperandC->getSExtValue();
3438
3439 // Check if we can shrink the operand enough to fit in an immediate (or
3440 // fit into a smaller immediate) by negating it and switching the
3441 // operation.
3442 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) &&
3443 ((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) ||
3444 (MemVT == MVT::i64 && !isInt<32>(OperandV) &&
3445 isInt<32>(-OperandV))) &&
3446 hasNoCarryFlagUses(StoredVal.getValue(1))) {
3447 OperandV = -OperandV;
3448 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD;
3449 }
3450
3451 if (MemVT != MVT::i64 || isInt<32>(OperandV)) {
3452 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT);
3453 NewOpc = SelectImmOpcode(Opc);
3454 }
3455 }
3456
3457 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) {
3458 SDValue CopyTo =
3459 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS,
3460 StoredVal.getOperand(2), SDValue());
3461
3462 const SDValue Ops[] = {Base, Scale, Index, Disp,
3463 Segment, Operand, CopyTo, CopyTo.getValue(1)};
3464 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
3465 Ops);
3466 } else {
3467 const SDValue Ops[] = {Base, Scale, Index, Disp,
3468 Segment, Operand, InputChain};
3469 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other,
3470 Ops);
3471 }
3472 break;
3473 }
3474 default:
3475 llvm_unreachable("Invalid opcode!");
3476 }
3477
3478 MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(),
3479 LoadNode->getMemOperand()};
3480 CurDAG->setNodeMemRefs(Result, MemOps);
3481
3482 // Update Load Chain uses as well.
3483 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1));
3484 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1));
3485 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0));
3486 CurDAG->RemoveDeadNode(Node);
3487 return true;
3488}
3489
3490// See if this is an X & Mask that we can match to BEXTR/BZHI.
3491// Where Mask is one of the following patterns:
3492// a) x & (1 << nbits) - 1
3493// b) x & ~(-1 << nbits)
3494// c) x & (-1 >> (32 - y))
3495// d) x << (32 - y) >> (32 - y)
3496bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) {
3497 assert(
3498 (Node->getOpcode() == ISD::AND || Node->getOpcode() == ISD::SRL) &&
3499 "Should be either an and-mask, or right-shift after clearing high bits.");
3500
3501 // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one.
3502 if (!Subtarget->hasBMI() && !Subtarget->hasBMI2())
3503 return false;
3504
3505 MVT NVT = Node->getSimpleValueType(0);
3506
3507 // Only supported for 32 and 64 bits.
3508 if (NVT != MVT::i32 && NVT != MVT::i64)
3509 return false;
3510
3511 SDValue NBits;
3512 bool NegateNBits;
3513
3514 // If we have BMI2's BZHI, we are ok with muti-use patterns.
3515 // Else, if we only have BMI1's BEXTR, we require one-use.
3516 const bool AllowExtraUsesByDefault = Subtarget->hasBMI2();
3517 auto checkUses = [AllowExtraUsesByDefault](
3518 SDValue Op, unsigned NUses,
3519 std::optional<bool> AllowExtraUses) {
3520 return AllowExtraUses.value_or(AllowExtraUsesByDefault) ||
3521 Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo());
3522 };
3523 auto checkOneUse = [checkUses](SDValue Op,
3524 std::optional<bool> AllowExtraUses =
3525 std::nullopt) {
3526 return checkUses(Op, 1, AllowExtraUses);
3527 };
3528 auto checkTwoUse = [checkUses](SDValue Op,
3529 std::optional<bool> AllowExtraUses =
3530 std::nullopt) {
3531 return checkUses(Op, 2, AllowExtraUses);
3532 };
3533
3534 auto peekThroughOneUseTruncation = [checkOneUse](SDValue V) {
3535 if (V->getOpcode() == ISD::TRUNCATE && checkOneUse(V)) {
3536 assert(V.getSimpleValueType() == MVT::i32 &&
3537 V.getOperand(0).getSimpleValueType() == MVT::i64 &&
3538 "Expected i64 -> i32 truncation");
3539 V = V.getOperand(0);
3540 }
3541 return V;
3542 };
3543
3544 // a) x & ((1 << nbits) + (-1))
3545 auto matchPatternA = [checkOneUse, peekThroughOneUseTruncation, &NBits,
3546 &NegateNBits](SDValue Mask) -> bool {
3547 // Match `add`. Must only have one use!
3548 if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask))
3549 return false;
3550 // We should be adding all-ones constant (i.e. subtracting one.)
3551 if (!isAllOnesConstant(Mask->getOperand(1)))
3552 return false;
3553 // Match `1 << nbits`. Might be truncated. Must only have one use!
3554 SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
3555 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
3556 return false;
3557 if (!isOneConstant(M0->getOperand(0)))
3558 return false;
3559 NBits = M0->getOperand(1);
3560 NegateNBits = false;
3561 return true;
3562 };
3563
3564 auto isAllOnes = [this, peekThroughOneUseTruncation, NVT](SDValue V) {
3565 V = peekThroughOneUseTruncation(V);
3566 return CurDAG->MaskedValueIsAllOnes(
3567 V, APInt::getLowBitsSet(V.getSimpleValueType().getSizeInBits(),
3568 NVT.getSizeInBits()));
3569 };
3570
3571 // b) x & ~(-1 << nbits)
3572 auto matchPatternB = [checkOneUse, isAllOnes, peekThroughOneUseTruncation,
3573 &NBits, &NegateNBits](SDValue Mask) -> bool {
3574 // Match `~()`. Must only have one use!
3575 if (Mask.getOpcode() != ISD::XOR || !checkOneUse(Mask))
3576 return false;
3577 // The -1 only has to be all-ones for the final Node's NVT.
3578 if (!isAllOnes(Mask->getOperand(1)))
3579 return false;
3580 // Match `-1 << nbits`. Might be truncated. Must only have one use!
3581 SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0));
3582 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0))
3583 return false;
3584 // The -1 only has to be all-ones for the final Node's NVT.
3585 if (!isAllOnes(M0->getOperand(0)))
3586 return false;
3587 NBits = M0->getOperand(1);
3588 NegateNBits = false;
3589 return true;
3590 };
3591
3592 // Try to match potentially-truncated shift amount as `(bitwidth - y)`,
3593 // or leave the shift amount as-is, but then we'll have to negate it.
3594 auto canonicalizeShiftAmt = [&NBits, &NegateNBits](SDValue ShiftAmt,
3595 unsigned Bitwidth) {
3596 NBits = ShiftAmt;
3597 NegateNBits = true;
3598 // Skip over a truncate of the shift amount, if any.
3599 if (NBits.getOpcode() == ISD::TRUNCATE)
3600 NBits = NBits.getOperand(0);
3601 // Try to match the shift amount as (bitwidth - y). It should go away, too.
3602 // If it doesn't match, that's fine, we'll just negate it ourselves.
3603 if (NBits.getOpcode() != ISD::SUB)
3604 return;
3605 auto *V0 = dyn_cast<ConstantSDNode>(NBits.getOperand(0));
3606 if (!V0 || V0->getZExtValue() != Bitwidth)
3607 return;
3608 NBits = NBits.getOperand(1);
3609 NegateNBits = false;
3610 };
3611
3612 // c) x & (-1 >> z) but then we'll have to subtract z from bitwidth
3613 // or
3614 // c) x & (-1 >> (32 - y))
3615 auto matchPatternC = [checkOneUse, peekThroughOneUseTruncation, &NegateNBits,
3616 canonicalizeShiftAmt](SDValue Mask) -> bool {
3617 // The mask itself may be truncated.
3618 Mask = peekThroughOneUseTruncation(Mask);
3619 unsigned Bitwidth = Mask.getSimpleValueType().getSizeInBits();
3620 // Match `l>>`. Must only have one use!
3621 if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask))
3622 return false;
3623 // We should be shifting truly all-ones constant.
3624 if (!isAllOnesConstant(Mask.getOperand(0)))
3625 return false;
3626 SDValue M1 = Mask.getOperand(1);
3627 // The shift amount should not be used externally.
3628 if (!checkOneUse(M1))
3629 return false;
3630 canonicalizeShiftAmt(M1, Bitwidth);
3631 // Pattern c. is non-canonical, and is expanded into pattern d. iff there
3632 // is no extra use of the mask. Clearly, there was one since we are here.
3633 // But at the same time, if we need to negate the shift amount,
3634 // then we don't want the mask to stick around, else it's unprofitable.
3635 return !NegateNBits;
3636 };
3637
3638 SDValue X;
3639
3640 // d) x << z >> z but then we'll have to subtract z from bitwidth
3641 // or
3642 // d) x << (32 - y) >> (32 - y)
3643 auto matchPatternD = [checkOneUse, checkTwoUse, canonicalizeShiftAmt,
3644 AllowExtraUsesByDefault, &NegateNBits,
3645 &X](SDNode *Node) -> bool {
3646 if (Node->getOpcode() != ISD::SRL)
3647 return false;
3648 SDValue N0 = Node->getOperand(0);
3649 if (N0->getOpcode() != ISD::SHL)
3650 return false;
3651 unsigned Bitwidth = N0.getSimpleValueType().getSizeInBits();
3652 SDValue N1 = Node->getOperand(1);
3653 SDValue N01 = N0->getOperand(1);
3654 // Both of the shifts must be by the exact same value.
3655 if (N1 != N01)
3656 return false;
3657 canonicalizeShiftAmt(N1, Bitwidth);
3658 // There should not be any external uses of the inner shift / shift amount.
3659 // Note that while we are generally okay with external uses given BMI2,
3660 // iff we need to negate the shift amount, we are not okay with extra uses.
3661 const bool AllowExtraUses = AllowExtraUsesByDefault && !NegateNBits;
3662 if (!checkOneUse(N0, AllowExtraUses) || !checkTwoUse(N1, AllowExtraUses))
3663 return false;
3664 X = N0->getOperand(0);
3665 return true;
3666 };
3667
3668 auto matchLowBitMask = [matchPatternA, matchPatternB,
3669 matchPatternC](SDValue Mask) -> bool {
3670 return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask);
3671 };
3672
3673 if (Node->getOpcode() == ISD::AND) {
3674 X = Node->getOperand(0);
3675 SDValue Mask = Node->getOperand(1);
3676
3677 if (matchLowBitMask(Mask)) {
3678 // Great.
3679 } else {
3680 std::swap(X, Mask);
3681 if (!matchLowBitMask(Mask))
3682 return false;
3683 }
3684 } else if (!matchPatternD(Node))
3685 return false;
3686
3687 // If we need to negate the shift amount, require BMI2 BZHI support.
3688 // It's just too unprofitable for BMI1 BEXTR.
3689 if (NegateNBits && !Subtarget->hasBMI2())
3690 return false;
3691
3692 SDLoc DL(Node);
3693
3694 // Truncate the shift amount.
3695 NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits);
3696 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3697
3698 // Insert 8-bit NBits into lowest 8 bits of 32-bit register.
3699 // All the other bits are undefined, we do not care about them.
3700 SDValue ImplDef = SDValue(
3701 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0);
3702 insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef);
3703
3704 SDValue SRIdxVal = CurDAG->getTargetConstant(X86::sub_8bit, DL, MVT::i32);
3705 insertDAGNode(*CurDAG, SDValue(Node, 0), SRIdxVal);
3706 NBits = SDValue(CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
3707 MVT::i32, ImplDef, NBits, SRIdxVal),
3708 0);
3709 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3710
3711 // We might have matched the amount of high bits to be cleared,
3712 // but we want the amount of low bits to be kept, so negate it then.
3713 if (NegateNBits) {
3714 SDValue BitWidthC = CurDAG->getConstant(NVT.getSizeInBits(), DL, MVT::i32);
3715 insertDAGNode(*CurDAG, SDValue(Node, 0), BitWidthC);
3716
3717 NBits = CurDAG->getNode(ISD::SUB, DL, MVT::i32, BitWidthC, NBits);
3718 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3719 }
3720
3721 if (Subtarget->hasBMI2()) {
3722 // Great, just emit the the BZHI..
3723 if (NVT != MVT::i32) {
3724 // But have to place the bit count into the wide-enough register first.
3725 NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, NVT, NBits);
3726 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits);
3727 }
3728
3729 SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits);
3730 ReplaceNode(Node, Extract.getNode());
3731 SelectCode(Extract.getNode());
3732 return true;
3733 }
3734
3735 // Else, if we do *NOT* have BMI2, let's find out if the if the 'X' is
3736 // *logically* shifted (potentially with one-use trunc inbetween),
3737 // and the truncation was the only use of the shift,
3738 // and if so look past one-use truncation.
3739 {
3740 SDValue RealX = peekThroughOneUseTruncation(X);
3741 // FIXME: only if the shift is one-use?
3742 if (RealX != X && RealX.getOpcode() == ISD::SRL)
3743 X = RealX;
3744 }
3745
3746 MVT XVT = X.getSimpleValueType();
3747
3748 // Else, emitting BEXTR requires one more step.
3749 // The 'control' of BEXTR has the pattern of:
3750 // [15...8 bit][ 7...0 bit] location
3751 // [ bit count][ shift] name
3752 // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11
3753
3754 // Shift NBits left by 8 bits, thus producing 'control'.
3755 // This makes the low 8 bits to be zero.
3756 SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8);
3757 insertDAGNode(*CurDAG, SDValue(Node, 0), C8);
3758 SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8);
3759 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3760
3761 // If the 'X' is *logically* shifted, we can fold that shift into 'control'.
3762 // FIXME: only if the shift is one-use?
3763 if (X.getOpcode() == ISD::SRL) {
3764 SDValue ShiftAmt = X.getOperand(1);
3765 X = X.getOperand(0);
3766
3767 assert(ShiftAmt.getValueType() == MVT::i8 &&
3768 "Expected shift amount to be i8");
3769
3770 // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero!
3771 // We could zext to i16 in some form, but we intentionally don't do that.
3772 SDValue OrigShiftAmt = ShiftAmt;
3773 ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt);
3774 insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt);
3775
3776 // And now 'or' these low 8 bits of shift amount into the 'control'.
3777 Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt);
3778 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3779 }
3780
3781 // But have to place the 'control' into the wide-enough register first.
3782 if (XVT != MVT::i32) {
3783 Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control);
3784 insertDAGNode(*CurDAG, SDValue(Node, 0), Control);
3785 }
3786
3787 // And finally, form the BEXTR itself.
3788 SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control);
3789
3790 // The 'X' was originally truncated. Do that now.
3791 if (XVT != NVT) {
3792 insertDAGNode(*CurDAG, SDValue(Node, 0), Extract);
3793 Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract);
3794 }
3795
3796 ReplaceNode(Node, Extract.getNode());
3797 SelectCode(Extract.getNode());
3798
3799 return true;
3800}
3801
3802// See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI.
3803MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) {
3804 MVT NVT = Node->getSimpleValueType(0);
3805 SDLoc dl(Node);
3806
3807 SDValue N0 = Node->getOperand(0);
3808 SDValue N1 = Node->getOperand(1);
3809
3810 // If we have TBM we can use an immediate for the control. If we have BMI
3811 // we should only do this if the BEXTR instruction is implemented well.
3812 // Otherwise moving the control into a register makes this more costly.
3813 // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM
3814 // hoisting the move immediate would make it worthwhile with a less optimal
3815 // BEXTR?
3816 bool PreferBEXTR =
3817 Subtarget->hasTBM() || (Subtarget->hasBMI() && Subtarget->hasFastBEXTR());
3818 if (!PreferBEXTR && !Subtarget->hasBMI2())
3819 return nullptr;
3820
3821 // Must have a shift right.
3822 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA)
3823 return nullptr;
3824
3825 // Shift can't have additional users.
3826 if (!N0->hasOneUse())
3827 return nullptr;
3828
3829 // Only supported for 32 and 64 bits.
3830 if (NVT != MVT::i32 && NVT != MVT::i64)
3831 return nullptr;
3832
3833 // Shift amount and RHS of and must be constant.
3834 auto *MaskCst = dyn_cast<ConstantSDNode>(N1);
3835 auto *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1));
3836 if (!MaskCst || !ShiftCst)
3837 return nullptr;
3838
3839 // And RHS must be a mask.
3840 uint64_t Mask = MaskCst->getZExtValue();
3841 if (!isMask_64(Mask))
3842 return nullptr;
3843
3844 uint64_t Shift = ShiftCst->getZExtValue();
3845 uint64_t MaskSize = llvm::popcount(Mask);
3846
3847 // Don't interfere with something that can be handled by extracting AH.
3848 // TODO: If we are able to fold a load, BEXTR might still be better than AH.
3849 if (Shift == 8 && MaskSize == 8)
3850 return nullptr;
3851
3852 // Make sure we are only using bits that were in the original value, not
3853 // shifted in.
3854 if (Shift + MaskSize > NVT.getSizeInBits())
3855 return nullptr;
3856
3857 // BZHI, if available, is always fast, unlike BEXTR. But even if we decide
3858 // that we can't use BEXTR, it is only worthwhile using BZHI if the mask
3859 // does not fit into 32 bits. Load folding is not a sufficient reason.
3860 if (!PreferBEXTR && MaskSize <= 32)
3861 return nullptr;
3862
3863 SDValue Control;
3864 unsigned ROpc, MOpc;
3865
3866 if (!PreferBEXTR) {
3867 assert(Subtarget->hasBMI2() && "We must have BMI2's BZHI then.");
3868 // If we can't make use of BEXTR then we can't fuse shift+mask stages.
3869 // Let's perform the mask first, and apply shift later. Note that we need to
3870 // widen the mask to account for the fact that we'll apply shift afterwards!
3871 Control = CurDAG->getTargetConstant(Shift + MaskSize, dl, NVT);
3872 ROpc = NVT == MVT::i64 ? X86::BZHI64rr : X86::BZHI32rr;
3873 MOpc = NVT == MVT::i64 ? X86::BZHI64rm : X86::BZHI32rm;
3874 unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
3875 Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
3876 } else {
3877 // The 'control' of BEXTR has the pattern of:
3878 // [15...8 bit][ 7...0 bit] location
3879 // [ bit count][ shift] name
3880 // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11
3881 Control = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT);
3882 if (Subtarget->hasTBM()) {
3883 ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri;
3884 MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi;
3885 } else {
3886 assert(Subtarget->hasBMI() && "We must have BMI1's BEXTR then.");
3887 // BMI requires the immediate to placed in a register.
3888 ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr;
3889 MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm;
3890 unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri;
3891 Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0);
3892 }
3893 }
3894
3895 MachineSDNode *NewNode;
3896 SDValue Input = N0->getOperand(0);
3897 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3898 if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3899 SDValue Ops[] = {
3900 Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Control, Input.getOperand(0)};
3901 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other);
3902 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3903 // Update the chain.
3904 ReplaceUses(Input.getValue(1), SDValue(NewNode, 2));
3905 // Record the mem-refs
3906 CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()});
3907 } else {
3908 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, Control);
3909 }
3910
3911 if (!PreferBEXTR) {
3912 // We still need to apply the shift.
3913 SDValue ShAmt = CurDAG->getTargetConstant(Shift, dl, NVT);
3914 unsigned NewOpc = NVT == MVT::i64 ? X86::SHR64ri : X86::SHR32ri;
3915 NewNode =
3916 CurDAG->getMachineNode(NewOpc, dl, NVT, SDValue(NewNode, 0), ShAmt);
3917 }
3918
3919 return NewNode;
3920}
3921
3922// Emit a PCMISTR(I/M) instruction.
3923MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc,
3924 bool MayFoldLoad, const SDLoc &dl,
3925 MVT VT, SDNode *Node) {
3926 SDValue N0 = Node->getOperand(0);
3927 SDValue N1 = Node->getOperand(1);
3928 SDValue Imm = Node->getOperand(2);
3929 auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3930 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3931
3932 // Try to fold a load. No need to check alignment.
3933 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3934 if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3935 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3936 N1.getOperand(0) };
3937 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other);
3938 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3939 // Update the chain.
3940 ReplaceUses(N1.getValue(1), SDValue(CNode, 2));
3941 // Record the mem-refs
3942 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()});
3943 return CNode;
3944 }
3945
3946 SDValue Ops[] = { N0, N1, Imm };
3947 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32);
3948 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3949 return CNode;
3950}
3951
3952// Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need
3953// to emit a second instruction after this one. This is needed since we have two
3954// copyToReg nodes glued before this and we need to continue that glue through.
3955MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc,
3956 bool MayFoldLoad, const SDLoc &dl,
3957 MVT VT, SDNode *Node,
3958 SDValue &InGlue) {
3959 SDValue N0 = Node->getOperand(0);
3960 SDValue N2 = Node->getOperand(2);
3961 SDValue Imm = Node->getOperand(4);
3962 auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue();
3963 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType());
3964
3965 // Try to fold a load. No need to check alignment.
3966 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
3967 if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
3968 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm,
3969 N2.getOperand(0), InGlue };
3970 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue);
3971 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops);
3972 InGlue = SDValue(CNode, 3);
3973 // Update the chain.
3974 ReplaceUses(N2.getValue(1), SDValue(CNode, 2));
3975 // Record the mem-refs
3976 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()});
3977 return CNode;
3978 }
3979
3980 SDValue Ops[] = { N0, N2, Imm, InGlue };
3981 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue);
3982 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops);
3983 InGlue = SDValue(CNode, 2);
3984 return CNode;
3985}
3986
3987bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
3988 EVT VT = N->getValueType(0);
3989
3990 // Only handle scalar shifts.
3991 if (VT.isVector())
3992 return false;
3993
3994 // Narrower shifts only mask to 5 bits in hardware.
3995 unsigned Size = VT == MVT::i64 ? 64 : 32;
3996
3997 SDValue OrigShiftAmt = N->getOperand(1);
3998 SDValue ShiftAmt = OrigShiftAmt;
3999 SDLoc DL(N);
4000
4001 // Skip over a truncate of the shift amount.
4002 if (ShiftAmt->getOpcode() == ISD::TRUNCATE)
4003 ShiftAmt = ShiftAmt->getOperand(0);
4004
4005 // This function is called after X86DAGToDAGISel::matchBitExtract(),
4006 // so we are not afraid that we might mess up BZHI/BEXTR pattern.
4007
4008 SDValue NewShiftAmt;
4009 if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB ||
4010 ShiftAmt->getOpcode() == ISD::XOR) {
4011 SDValue Add0 = ShiftAmt->getOperand(0);
4012 SDValue Add1 = ShiftAmt->getOperand(1);
4013 auto *Add0C = dyn_cast<ConstantSDNode>(Add0);
4014 auto *Add1C = dyn_cast<ConstantSDNode>(Add1);
4015 // If we are shifting by X+/-/^N where N == 0 mod Size, then just shift by X
4016 // to avoid the ADD/SUB/XOR.
4017 if (Add1C && Add1C->getAPIntValue().urem(Size) == 0) {
4018 NewShiftAmt = Add0;
4019
4020 } else if (ShiftAmt->getOpcode() != ISD::ADD && ShiftAmt.hasOneUse() &&
4021 ((Add0C && Add0C->getAPIntValue().urem(Size) == Size - 1) ||
4022 (Add1C && Add1C->getAPIntValue().urem(Size) == Size - 1))) {
4023 // If we are doing a NOT on just the lower bits with (Size*N-1) -/^ X
4024 // we can replace it with a NOT. In the XOR case it may save some code
4025 // size, in the SUB case it also may save a move.
4026 assert(Add0C == nullptr || Add1C == nullptr);
4027
4028 // We can only do N-X, not X-N
4029 if (ShiftAmt->getOpcode() == ISD::SUB && Add0C == nullptr)
4030 return false;
4031
4032 EVT OpVT = ShiftAmt.getValueType();
4033
4034 SDValue AllOnes = CurDAG->getAllOnesConstant(DL, OpVT);
4035 NewShiftAmt = CurDAG->getNode(ISD::XOR, DL, OpVT,
4036 Add0C == nullptr ? Add0 : Add1, AllOnes);
4037 insertDAGNode(*CurDAG, OrigShiftAmt, AllOnes);
4038 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
4039 // If we are shifting by N-X where N == 0 mod Size, then just shift by
4040 // -X to generate a NEG instead of a SUB of a constant.
4041 } else if (ShiftAmt->getOpcode() == ISD::SUB && Add0C &&
4042 Add0C->getZExtValue() != 0) {
4043 EVT SubVT = ShiftAmt.getValueType();
4044 SDValue X;
4045 if (Add0C->getZExtValue() % Size == 0)
4046 X = Add1;
4047 else if (ShiftAmt.hasOneUse() && Size == 64 &&
4048 Add0C->getZExtValue() % 32 == 0) {
4049 // We have a 64-bit shift by (n*32-x), turn it into -(x+n*32).
4050 // This is mainly beneficial if we already compute (x+n*32).
4051 if (Add1.getOpcode() == ISD::TRUNCATE) {
4052 Add1 = Add1.getOperand(0);
4053 SubVT = Add1.getValueType();
4054 }
4055 if (Add0.getValueType() != SubVT) {
4056 Add0 = CurDAG->getZExtOrTrunc(Add0, DL, SubVT);
4057 insertDAGNode(*CurDAG, OrigShiftAmt, Add0);
4058 }
4059
4060 X = CurDAG->getNode(ISD::ADD, DL, SubVT, Add1, Add0);
4061 insertDAGNode(*CurDAG, OrigShiftAmt, X);
4062 } else
4063 return false;
4064 // Insert a negate op.
4065 // TODO: This isn't guaranteed to replace the sub if there is a logic cone
4066 // that uses it that's not a shift.
4067 SDValue Zero = CurDAG->getConstant(0, DL, SubVT);
4068 SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, X);
4069 NewShiftAmt = Neg;
4070
4071 // Insert these operands into a valid topological order so they can
4072 // get selected independently.
4073 insertDAGNode(*CurDAG, OrigShiftAmt, Zero);
4074 insertDAGNode(*CurDAG, OrigShiftAmt, Neg);
4075 } else
4076 return false;
4077 } else
4078 return false;
4079
4080 if (NewShiftAmt.getValueType() != MVT::i8) {
4081 // Need to truncate the shift amount.
4082 NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt);
4083 // Add to a correct topological ordering.
4084 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
4085 }
4086
4087 // Insert a new mask to keep the shift amount legal. This should be removed
4088 // by isel patterns.
4089 NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt,
4090 CurDAG->getConstant(Size - 1, DL, MVT::i8));
4091 // Place in a correct topological ordering.
4092 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt);
4093
4094 SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0),
4095 NewShiftAmt);
4096 if (UpdatedNode != N) {
4097 // If we found an existing node, we should replace ourselves with that node
4098 // and wait for it to be selected after its other users.
4099 ReplaceNode(N, UpdatedNode);
4100 return true;
4101 }
4102
4103 // If the original shift amount is now dead, delete it so that we don't run
4104 // it through isel.
4105 if (OrigShiftAmt.getNode()->use_empty())
4106 CurDAG->RemoveDeadNode(OrigShiftAmt.getNode());
4107
4108 // Now that we've optimized the shift amount, defer to normal isel to get
4109 // load folding and legacy vs BMI2 selection without repeating it here.
4110 SelectCode(N);
4111 return true;
4112}
4113
4114bool X86DAGToDAGISel::tryShrinkShlLogicImm(SDNode *N) {
4115 MVT NVT = N->getSimpleValueType(0);
4116 unsigned Opcode = N->getOpcode();
4117 SDLoc dl(N);
4118
4119 // For operations of the form (x << C1) op C2, check if we can use a smaller
4120 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1.
4121 SDValue Shift = N->getOperand(0);
4122 SDValue N1 = N->getOperand(1);
4123
4124 auto *Cst = dyn_cast<ConstantSDNode>(N1);
4125 if (!Cst)
4126 return false;
4127
4128 int64_t Val = Cst->getSExtValue();
4129
4130 // If we have an any_extend feeding the AND, look through it to see if there
4131 // is a shift behind it. But only if the AND doesn't use the extended bits.
4132 // FIXME: Generalize this to other ANY_EXTEND than i32 to i64?
4133 bool FoundAnyExtend = false;
4134 if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() &&
4135 Shift.getOperand(0).getSimpleValueType() == MVT::i32 &&
4136 isUInt<32>(Val)) {
4137 FoundAnyExtend = true;
4138 Shift = Shift.getOperand(0);
4139 }
4140
4141 if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse())
4142 return false;
4143
4144 // i8 is unshrinkable, i16 should be promoted to i32.
4145 if (NVT != MVT::i32 && NVT != MVT::i64)
4146 return false;
4147
4148 auto *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4149 if (!ShlCst)
4150 return false;
4151
4152 uint64_t ShAmt = ShlCst->getZExtValue();
4153
4154 // Make sure that we don't change the operation by removing bits.
4155 // This only matters for OR and XOR, AND is unaffected.
4156 uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1;
4157 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0)
4158 return false;
4159
4160 // Check the minimum bitwidth for the new constant.
4161 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32.
4162 auto CanShrinkImmediate = [&](int64_t &ShiftedVal) {
4163 if (Opcode == ISD::AND) {
4164 // AND32ri is the same as AND64ri32 with zext imm.
4165 // Try this before sign extended immediates below.
4166 ShiftedVal = (uint64_t)Val >> ShAmt;
4167 if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
4168 return true;
4169 // Also swap order when the AND can become MOVZX.
4170 if (ShiftedVal == UINT8_MAX || ShiftedVal == UINT16_MAX)
4171 return true;
4172 }
4173 ShiftedVal = Val >> ShAmt;
4174 if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) ||
4175 (!isInt<32>(Val) && isInt<32>(ShiftedVal)))
4176 return true;
4177 if (Opcode != ISD::AND) {
4178 // MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr
4179 ShiftedVal = (uint64_t)Val >> ShAmt;
4180 if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal))
4181 return true;
4182 }
4183 return false;
4184 };
4185
4186 int64_t ShiftedVal;
4187 if (!CanShrinkImmediate(ShiftedVal))
4188 return false;
4189
4190 // Ok, we can reorder to get a smaller immediate.
4191
4192 // But, its possible the original immediate allowed an AND to become MOVZX.
4193 // Doing this late due to avoid the MakedValueIsZero call as late as
4194 // possible.
4195 if (Opcode == ISD::AND) {
4196 // Find the smallest zext this could possibly be.
4197 unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits();
4198 ZExtWidth = llvm::bit_ceil(std::max(ZExtWidth, 8U));
4199
4200 // Figure out which bits need to be zero to achieve that mask.
4201 APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(),
4202 ZExtWidth);
4203 NeededMask &= ~Cst->getAPIntValue();
4204
4205 if (CurDAG->MaskedValueIsZero(N->getOperand(0), NeededMask))
4206 return false;
4207 }
4208
4209 SDValue X = Shift.getOperand(0);
4210 if (FoundAnyExtend) {
4211 SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X);
4212 insertDAGNode(*CurDAG, SDValue(N, 0), NewX);
4213 X = NewX;
4214 }
4215
4216 SDValue NewCst = CurDAG->getConstant(ShiftedVal, dl, NVT);
4217 insertDAGNode(*CurDAG, SDValue(N, 0), NewCst);
4218 SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst);
4219 insertDAGNode(*CurDAG, SDValue(N, 0), NewBinOp);
4220 SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp,
4221 Shift.getOperand(1));
4222 ReplaceNode(N, NewSHL.getNode());
4223 SelectCode(NewSHL.getNode());
4224 return true;
4225}
4226
4227bool X86DAGToDAGISel::matchVPTERNLOG(SDNode *Root, SDNode *ParentA,
4228 SDNode *ParentB, SDNode *ParentC,
4230 uint8_t Imm) {
4231 assert(A.isOperandOf(ParentA) && B.isOperandOf(ParentB) &&
4232 C.isOperandOf(ParentC) && "Incorrect parent node");
4233
4234 auto tryFoldLoadOrBCast =
4235 [this](SDNode *Root, SDNode *P, SDValue &L, SDValue &Base, SDValue &Scale,
4236 SDValue &Index, SDValue &Disp, SDValue &Segment) {
4237 if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))
4238 return true;
4239
4240 // Not a load, check for broadcast which may be behind a bitcast.
4241 if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {
4242 P = L.getNode();
4243 L = L.getOperand(0);
4244 }
4245
4246 if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)
4247 return false;
4248
4249 // Only 32 and 64 bit broadcasts are supported.
4250 auto *MemIntr = cast<MemIntrinsicSDNode>(L);
4251 unsigned Size = MemIntr->getMemoryVT().getSizeInBits();
4252 if (Size != 32 && Size != 64)
4253 return false;
4254
4255 return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);
4256 };
4257
4258 bool FoldedLoad = false;
4259 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4260 if (tryFoldLoadOrBCast(Root, ParentC, C, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) {
4261 FoldedLoad = true;
4262 } else if (tryFoldLoadOrBCast(Root, ParentA, A, Tmp0, Tmp1, Tmp2, Tmp3,
4263 Tmp4)) {
4264 FoldedLoad = true;
4265 std::swap(A, C);
4266 // Swap bits 1/4 and 3/6.
4267 uint8_t OldImm = Imm;
4268 Imm = OldImm & 0xa5;
4269 if (OldImm & 0x02) Imm |= 0x10;
4270 if (OldImm & 0x10) Imm |= 0x02;
4271 if (OldImm & 0x08) Imm |= 0x40;
4272 if (OldImm & 0x40) Imm |= 0x08;
4273 } else if (tryFoldLoadOrBCast(Root, ParentB, B, Tmp0, Tmp1, Tmp2, Tmp3,
4274 Tmp4)) {
4275 FoldedLoad = true;
4276 std::swap(B, C);
4277 // Swap bits 1/2 and 5/6.
4278 uint8_t OldImm = Imm;
4279 Imm = OldImm & 0x99;
4280 if (OldImm & 0x02) Imm |= 0x04;
4281 if (OldImm & 0x04) Imm |= 0x02;
4282 if (OldImm & 0x20) Imm |= 0x40;
4283 if (OldImm & 0x40) Imm |= 0x20;
4284 }
4285
4286 SDLoc DL(Root);
4287
4288 SDValue TImm = CurDAG->getTargetConstant(Imm, DL, MVT::i8);
4289
4290 MVT NVT = Root->getSimpleValueType(0);
4291
4292 MachineSDNode *MNode;
4293 if (FoldedLoad) {
4294 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other);
4295
4296 unsigned Opc;
4297 if (C.getOpcode() == X86ISD::VBROADCAST_LOAD) {
4298 auto *MemIntr = cast<MemIntrinsicSDNode>(C);
4299 unsigned EltSize = MemIntr->getMemoryVT().getSizeInBits();
4300 assert((EltSize == 32 || EltSize == 64) && "Unexpected broadcast size!");
4301
4302 bool UseD = EltSize == 32;
4303 if (NVT.is128BitVector())
4304 Opc = UseD ? X86::VPTERNLOGDZ128rmbi : X86::VPTERNLOGQZ128rmbi;
4305 else if (NVT.is256BitVector())
4306 Opc = UseD ? X86::VPTERNLOGDZ256rmbi : X86::VPTERNLOGQZ256rmbi;
4307 else if (NVT.is512BitVector())
4308 Opc = UseD ? X86::VPTERNLOGDZrmbi : X86::VPTERNLOGQZrmbi;
4309 else
4310 llvm_unreachable("Unexpected vector size!");
4311 } else {
4312 bool UseD = NVT.getVectorElementType() == MVT::i32;
4313 if (NVT.is128BitVector())
4314 Opc = UseD ? X86::VPTERNLOGDZ128rmi : X86::VPTERNLOGQZ128rmi;
4315 else if (NVT.is256BitVector())
4316 Opc = UseD ? X86::VPTERNLOGDZ256rmi : X86::VPTERNLOGQZ256rmi;
4317 else if (NVT.is512BitVector())
4318 Opc = UseD ? X86::VPTERNLOGDZrmi : X86::VPTERNLOGQZrmi;
4319 else
4320 llvm_unreachable("Unexpected vector size!");
4321 }
4322
4323 SDValue Ops[] = {A, B, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, TImm, C.getOperand(0)};
4324 MNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops);
4325
4326 // Update the chain.
4327 ReplaceUses(C.getValue(1), SDValue(MNode, 1));
4328 // Record the mem-refs
4329 CurDAG->setNodeMemRefs(MNode, {cast<MemSDNode>(C)->getMemOperand()});
4330 } else {
4331 bool UseD = NVT.getVectorElementType() == MVT::i32;
4332 unsigned Opc;
4333 if (NVT.is128BitVector())
4334 Opc = UseD ? X86::VPTERNLOGDZ128rri : X86::VPTERNLOGQZ128rri;
4335 else if (NVT.is256BitVector())
4336 Opc = UseD ? X86::VPTERNLOGDZ256rri : X86::VPTERNLOGQZ256rri;
4337 else if (NVT.is512BitVector())
4338 Opc = UseD ? X86::VPTERNLOGDZrri : X86::VPTERNLOGQZrri;
4339 else
4340 llvm_unreachable("Unexpected vector size!");
4341
4342 MNode = CurDAG->getMachineNode(Opc, DL, NVT, {A, B, C, TImm});
4343 }
4344
4345 ReplaceUses(SDValue(Root, 0), SDValue(MNode, 0));
4346 CurDAG->RemoveDeadNode(Root);
4347 return true;
4348}
4349
4350// Try to match two logic ops to a VPTERNLOG.
4351// FIXME: Handle more complex patterns that use an operand more than once?
4352bool X86DAGToDAGISel::tryVPTERNLOG(SDNode *N) {
4353 MVT NVT = N->getSimpleValueType(0);
4354
4355 // Make sure we support VPTERNLOG.
4356 if (!NVT.isVector() || !Subtarget->hasAVX512() ||
4357 NVT.getVectorElementType() == MVT::i1)
4358 return false;
4359
4360 // We need VLX for 128/256-bit.
4361 if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
4362 return false;
4363
4364 SDValue N0 = N->getOperand(0);
4365 SDValue N1 = N->getOperand(1);
4366
4367 auto getFoldableLogicOp = [](SDValue Op) {
4368 // Peek through single use bitcast.
4369 if (Op.getOpcode() == ISD::BITCAST && Op.hasOneUse())
4370 Op = Op.getOperand(0);
4371
4372 if (!Op.hasOneUse())
4373 return SDValue();
4374
4375 unsigned Opc = Op.getOpcode();
4376 if (Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR ||
4377 Opc == X86ISD::ANDNP)
4378 return Op;
4379
4380 return SDValue();
4381 };
4382
4383 SDValue A, FoldableOp;
4384 if ((FoldableOp = getFoldableLogicOp(N1))) {
4385 A = N0;
4386 } else if ((FoldableOp = getFoldableLogicOp(N0))) {
4387 A = N1;
4388 } else
4389 return false;
4390
4391 SDValue B = FoldableOp.getOperand(0);
4392 SDValue C = FoldableOp.getOperand(1);
4393 SDNode *ParentA = N;
4394 SDNode *ParentB = FoldableOp.getNode();
4395 SDNode *ParentC = FoldableOp.getNode();
4396
4397 // We can build the appropriate control immediate by performing the logic
4398 // operation we're matching using these constants for A, B, and C.
4399 uint8_t TernlogMagicA = 0xf0;
4400 uint8_t TernlogMagicB = 0xcc;
4401 uint8_t TernlogMagicC = 0xaa;
4402
4403 // Some of the inputs may be inverted, peek through them and invert the
4404 // magic values accordingly.
4405 // TODO: There may be a bitcast before the xor that we should peek through.
4406 auto PeekThroughNot = [](SDValue &Op, SDNode *&Parent, uint8_t &Magic) {
4407 if (Op.getOpcode() == ISD::XOR && Op.hasOneUse() &&
4408 ISD::isBuildVectorAllOnes(Op.getOperand(1).getNode())) {
4409 Magic = ~Magic;
4410 Parent = Op.getNode();
4411 Op = Op.getOperand(0);
4412 }
4413 };
4414
4415 PeekThroughNot(A, ParentA, TernlogMagicA);
4416 PeekThroughNot(B, ParentB, TernlogMagicB);
4417 PeekThroughNot(C, ParentC, TernlogMagicC);
4418
4419 uint8_t Imm;
4420 switch (FoldableOp.getOpcode()) {
4421 default: llvm_unreachable("Unexpected opcode!");
4422 case ISD::AND: Imm = TernlogMagicB & TernlogMagicC; break;
4423 case ISD::OR: Imm = TernlogMagicB | TernlogMagicC; break;
4424 case ISD::XOR: Imm = TernlogMagicB ^ TernlogMagicC; break;
4425 case X86ISD::ANDNP: Imm = ~(TernlogMagicB) & TernlogMagicC; break;
4426 }
4427
4428 switch (N->getOpcode()) {
4429 default: llvm_unreachable("Unexpected opcode!");
4430 case X86ISD::ANDNP:
4431 if (A == N0)
4432 Imm &= ~TernlogMagicA;
4433 else
4434 Imm = ~(Imm) & TernlogMagicA;
4435 break;
4436 case ISD::AND: Imm &= TernlogMagicA; break;
4437 case ISD::OR: Imm |= TernlogMagicA; break;
4438 case ISD::XOR: Imm ^= TernlogMagicA; break;
4439 }
4440
4441 return matchVPTERNLOG(N, ParentA, ParentB, ParentC, A, B, C, Imm);
4442}
4443
4444/// If the high bits of an 'and' operand are known zero, try setting the
4445/// high bits of an 'and' constant operand to produce a smaller encoding by
4446/// creating a small, sign-extended negative immediate rather than a large
4447/// positive one. This reverses a transform in SimplifyDemandedBits that
4448/// shrinks mask constants by clearing bits. There is also a possibility that
4449/// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that
4450/// case, just replace the 'and'. Return 'true' if the node is replaced.
4451bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) {
4452 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't
4453 // have immediate operands.
4454 MVT VT = And->getSimpleValueType(0);
4455 if (VT != MVT::i32 && VT != MVT::i64)
4456 return false;
4457
4458 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1));
4459 if (!And1C)
4460 return false;
4461
4462 // Bail out if the mask constant is already negative. It's can't shrink more.
4463 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel
4464 // patterns to use a 32-bit and instead of a 64-bit and by relying on the
4465 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits
4466 // are negative too.
4467 APInt MaskVal = And1C->getAPIntValue();
4468 unsigned MaskLZ = MaskVal.countl_zero();
4469 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32))
4470 return false;
4471
4472 // Don't extend into the upper 32 bits of a 64 bit mask.
4473 if (VT == MVT::i64 && MaskLZ >= 32) {
4474 MaskLZ -= 32;
4475 MaskVal = MaskVal.trunc(32);
4476 }
4477
4478 SDValue And0 = And->getOperand(0);
4479 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ);
4480 APInt NegMaskVal = MaskVal | HighZeros;
4481
4482 // If a negative constant would not allow a smaller encoding, there's no need
4483 // to continue. Only change the constant when we know it's a win.
4484 unsigned MinWidth = NegMaskVal.getSignificantBits();
4485 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getSignificantBits() <= 32))
4486 return false;
4487
4488 // Extend masks if we truncated above.
4489 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) {
4490 NegMaskVal = NegMaskVal.zext(64);
4491 HighZeros = HighZeros.zext(64);
4492 }
4493
4494 // The variable operand must be all zeros in the top bits to allow using the
4495 // new, negative constant as the mask.
4496 if (!CurDAG->MaskedValueIsZero(And0, HighZeros))
4497 return false;
4498
4499 // Check if the mask is -1. In that case, this is an unnecessary instruction
4500 // that escaped earlier analysis.
4501 if (NegMaskVal.isAllOnes()) {
4502 ReplaceNode(And, And0.getNode());
4503 return true;
4504 }
4505
4506 // A negative mask allows a smaller encoding. Create a new 'and' node.
4507 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT);
4508 insertDAGNode(*CurDAG, SDValue(And, 0), NewMask);
4509 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask);
4510 ReplaceNode(And, NewAnd.getNode());
4511 SelectCode(NewAnd.getNode());
4512 return true;
4513}
4514
4515static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad,
4516 bool FoldedBCast, bool Masked) {
4517#define VPTESTM_CASE(VT, SUFFIX) \
4518case MVT::VT: \
4519 if (Masked) \
4520 return IsTestN ? X86::VPTESTNM##SUFFIX##k: X86::VPTESTM##SUFFIX##k; \
4521 return IsTestN ? X86::VPTESTNM##SUFFIX : X86::VPTESTM##SUFFIX;
4522
4523
4524#define VPTESTM_BROADCAST_CASES(SUFFIX) \
4525default: llvm_unreachable("Unexpected VT!"); \
4526VPTESTM_CASE(v4i32, DZ128##SUFFIX) \
4527VPTESTM_CASE(v2i64, QZ128##SUFFIX) \
4528VPTESTM_CASE(v8i32, DZ256##SUFFIX) \
4529VPTESTM_CASE(v4i64, QZ256##SUFFIX) \
4530VPTESTM_CASE(v16i32, DZ##SUFFIX) \
4531VPTESTM_CASE(v8i64, QZ##SUFFIX)
4532
4533#define VPTESTM_FULL_CASES(SUFFIX) \
4534VPTESTM_BROADCAST_CASES(SUFFIX) \
4535VPTESTM_CASE(v16i8, BZ128##SUFFIX) \
4536VPTESTM_CASE(v8i16, WZ128##SUFFIX) \
4537VPTESTM_CASE(v32i8, BZ256##SUFFIX) \
4538VPTESTM_CASE(v16i16, WZ256##SUFFIX) \
4539VPTESTM_CASE(v64i8, BZ##SUFFIX) \
4540VPTESTM_CASE(v32i16, WZ##SUFFIX)
4541
4542 if (FoldedBCast) {
4543 switch (TestVT.SimpleTy) {
4545 }
4546 }
4547
4548 if (FoldedLoad) {
4549 switch (TestVT.SimpleTy) {
4551 }
4552 }
4553
4554 switch (TestVT.SimpleTy) {
4556 }
4557
4558#undef VPTESTM_FULL_CASES
4559#undef VPTESTM_BROADCAST_CASES
4560#undef VPTESTM_CASE
4561}
4562
4563// Try to create VPTESTM instruction. If InMask is not null, it will be used
4564// to form a masked operation.
4565bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc,
4566 SDValue InMask) {
4567 assert(Subtarget->hasAVX512() && "Expected AVX512!");
4568 assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 &&
4569 "Unexpected VT!");
4570
4571 // Look for equal and not equal compares.
4572 ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get();
4573 if (CC != ISD::SETEQ && CC != ISD::SETNE)
4574 return false;
4575
4576 SDValue SetccOp0 = Setcc.getOperand(0);
4577 SDValue SetccOp1 = Setcc.getOperand(1);
4578
4579 // Canonicalize the all zero vector to the RHS.
4580 if (ISD::isBuildVectorAllZeros(SetccOp0.getNode()))
4581 std::swap(SetccOp0, SetccOp1);
4582
4583 // See if we're comparing against zero.
4584 if (!ISD::isBuildVectorAllZeros(SetccOp1.getNode()))
4585 return false;
4586
4587 SDValue N0 = SetccOp0;
4588
4589 MVT CmpVT = N0.getSimpleValueType();
4590 MVT CmpSVT = CmpVT.getVectorElementType();
4591
4592 // Start with both operands the same. We'll try to refine this.
4593 SDValue Src0 = N0;
4594 SDValue Src1 = N0;
4595
4596 {
4597 // Look through single use bitcasts.
4598 SDValue N0Temp = N0;
4599 if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse())
4600 N0Temp = N0.getOperand(0);
4601
4602 // Look for single use AND.
4603 if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) {
4604 Src0 = N0Temp.getOperand(0);
4605 Src1 = N0Temp.getOperand(1);
4606 }
4607 }
4608
4609 // Without VLX we need to widen the operation.
4610 bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector();
4611
4612 auto tryFoldLoadOrBCast = [&](SDNode *Root, SDNode *P, SDValue &L,
4613 SDValue &Base, SDValue &Scale, SDValue &Index,
4614 SDValue &Disp, SDValue &Segment) {
4615 // If we need to widen, we can't fold the load.
4616 if (!Widen)
4617 if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment))
4618 return true;
4619
4620 // If we didn't fold a load, try to match broadcast. No widening limitation
4621 // for this. But only 32 and 64 bit types are supported.
4622 if (CmpSVT != MVT::i32 && CmpSVT != MVT::i64)
4623 return false;
4624
4625 // Look through single use bitcasts.
4626 if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) {
4627 P = L.getNode();
4628 L = L.getOperand(0);
4629 }
4630
4631 if (L.getOpcode() != X86ISD::VBROADCAST_LOAD)
4632 return false;
4633
4634 auto *MemIntr = cast<MemIntrinsicSDNode>(L);
4635 if (MemIntr->getMemoryVT().getSizeInBits() != CmpSVT.getSizeInBits())
4636 return false;
4637
4638 return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment);
4639 };
4640
4641 // We can only fold loads if the sources are unique.
4642 bool CanFoldLoads = Src0 != Src1;
4643
4644 bool FoldedLoad = false;
4645 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4;
4646 if (CanFoldLoads) {
4647 FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src1, Tmp0, Tmp1, Tmp2,
4648 Tmp3, Tmp4);
4649 if (!FoldedLoad) {
4650 // And is commutative.
4651 FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src0, Tmp0, Tmp1,
4652 Tmp2, Tmp3, Tmp4);
4653 if (FoldedLoad)
4654 std::swap(Src0, Src1);
4655 }
4656 }
4657
4658 bool FoldedBCast = FoldedLoad && Src1.getOpcode() == X86ISD::VBROADCAST_LOAD;
4659
4660 bool IsMasked = InMask.getNode() != nullptr;
4661
4662 SDLoc dl(Root);
4663
4664 MVT ResVT = Setcc.getSimpleValueType();
4665 MVT MaskVT = ResVT;
4666 if (Widen) {
4667 // Widen the inputs using insert_subreg or copy_to_regclass.
4668 unsigned Scale = CmpVT.is128BitVector() ? 4 : 2;
4669 unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm;
4670 unsigned NumElts = CmpVT.getVectorNumElements() * Scale;
4671 CmpVT = MVT::getVectorVT(CmpSVT, NumElts);
4672 MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
4673 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl,
4674 CmpVT), 0);
4675 Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0);
4676
4677 if (!FoldedBCast)
4678 Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1);
4679
4680 if (IsMasked) {
4681 // Widen the mask.
4682 unsigned RegClass = TLI->getRegClassFor(MaskVT)->getID();
4683 SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
4684 InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4685 dl, MaskVT, InMask, RC), 0);
4686 }
4687 }
4688
4689 bool IsTestN = CC == ISD::SETEQ;
4690 unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast,
4691 IsMasked);
4692
4693 MachineSDNode *CNode;
4694 if (FoldedLoad) {
4695 SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other);
4696
4697 if (IsMasked) {
4698 SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
4699 Src1.getOperand(0) };
4700 CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4701 } else {
4702 SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4,
4703 Src1.getOperand(0) };
4704 CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops);
4705 }
4706
4707 // Update the chain.
4708 ReplaceUses(Src1.getValue(1), SDValue(CNode, 1));
4709 // Record the mem-refs
4710 CurDAG->setNodeMemRefs(CNode, {cast<MemSDNode>(Src1)->getMemOperand()});
4711 } else {
4712 if (IsMasked)
4713 CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1);
4714 else
4715 CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1);
4716 }
4717
4718 // If we widened, we need to shrink the mask VT.
4719 if (Widen) {
4720 unsigned RegClass = TLI->getRegClassFor(ResVT)->getID();
4721 SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32);
4722 CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
4723 dl, ResVT, SDValue(CNode, 0), RC);
4724 }
4725
4726 ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0));
4727 CurDAG->RemoveDeadNode(Root);
4728 return true;
4729}
4730
4731// Try to match the bitselect pattern (or (and A, B), (andn A, C)). Turn it
4732// into vpternlog.
4733bool X86DAGToDAGISel::tryMatchBitSelect(SDNode *N) {
4734 assert(N->getOpcode() == ISD::OR && "Unexpected opcode!");
4735
4736 MVT NVT = N->getSimpleValueType(0);
4737
4738 // Make sure we support VPTERNLOG.
4739 if (!NVT.isVector() || !Subtarget->hasAVX512())
4740 return false;
4741
4742 // We need VLX for 128/256-bit.
4743 if (!(Subtarget->hasVLX() || NVT.is512BitVector()))
4744 return false;
4745
4746 SDValue N0 = N->getOperand(0);
4747 SDValue N1 = N->getOperand(1);
4748
4749 // Canonicalize AND to LHS.
4750 if (N1.getOpcode() == ISD::AND)
4751 std::swap(N0, N1);
4752
4753 if (N0.getOpcode() != ISD::AND ||
4754 N1.getOpcode() != X86ISD::ANDNP ||
4755 !N0.hasOneUse() || !N1.hasOneUse())
4756 return false;
4757
4758 // ANDN is not commutable, use it to pick down A and C.
4759 SDValue A = N1.getOperand(0);
4760 SDValue C = N1.getOperand(1);
4761
4762 // AND is commutable, if one operand matches A, the other operand is B.
4763 // Otherwise this isn't a match.
4764 SDValue B;
4765 if (N0.getOperand(0) == A)
4766 B = N0.getOperand(1);
4767 else if (N0.getOperand(1) == A)
4768 B = N0.getOperand(0);
4769 else
4770 return false;
4771
4772 SDLoc dl(N);
4773 SDValue Imm = CurDAG->getTargetConstant(0xCA, dl, MVT::i8);
4774 SDValue Ternlog = CurDAG->getNode(X86ISD::VPTERNLOG, dl, NVT, A, B, C, Imm);
4775 ReplaceNode(N, Ternlog.getNode());
4776
4777 return matchVPTERNLOG(Ternlog.getNode(), Ternlog.getNode(), Ternlog.getNode(),
4778 Ternlog.getNode(), A, B, C, 0xCA);
4779}
4780
4781void X86DAGToDAGISel::Select(SDNode *Node) {
4782 MVT NVT = Node->getSimpleValueType(0);
4783 unsigned Opcode = Node->getOpcode();
4784 SDLoc dl(Node);
4785
4786 if (Node->isMachineOpcode()) {
4787 LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n');
4788 Node->setNodeId(-1);
4789 return; // Already selected.
4790 }
4791
4792 switch (Opcode) {
4793 default: break;
4795 unsigned IntNo = Node->getConstantOperandVal(1);
4796 switch (IntNo) {
4797 default: break;
4798 case Intrinsic::x86_encodekey128:
4799 case Intrinsic::x86_encodekey256: {
4800 if (!Subtarget->hasKL())
4801 break;
4802
4803 unsigned Opcode;
4804 switch (IntNo) {
4805 default: llvm_unreachable("Impossible intrinsic");
4806 case Intrinsic::x86_encodekey128: Opcode = X86::ENCODEKEY128; break;
4807 case Intrinsic::x86_encodekey256: Opcode = X86::ENCODEKEY256; break;
4808 }
4809
4810 SDValue Chain = Node->getOperand(0);
4811 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(3),
4812 SDValue());
4813 if (Opcode == X86::ENCODEKEY256)
4814 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(4),
4815 Chain.getValue(1));
4816
4817 MachineSDNode *Res = CurDAG->getMachineNode(
4818 Opcode, dl, Node->getVTList(),
4819 {Node->getOperand(2), Chain, Chain.getValue(1)});
4820 ReplaceNode(Node, Res);
4821 return;
4822 }
4823 case Intrinsic::x86_tileloadd64_internal:
4824 case Intrinsic::x86_tileloaddt164_internal: {
4825 if (!Subtarget->hasAMXTILE())
4826 break;
4827 unsigned Opc = IntNo == Intrinsic::x86_tileloadd64_internal
4828 ? X86::PTILELOADDV
4829 : X86::PTILELOADDT1V;
4830 // _tile_loadd_internal(row, col, buf, STRIDE)
4831 SDValue Base = Node->getOperand(4);
4832 SDValue Scale = getI8Imm(1, dl);
4833 SDValue Index = Node->getOperand(5);
4834 SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
4835 SDValue Segment = CurDAG->getRegister(0, MVT::i16);
4836 SDValue Chain = Node->getOperand(0);
4837 MachineSDNode *CNode;
4838 SDValue Ops[] = {Node->getOperand(2),
4839 Node->getOperand(3),
4840 Base,
4841 Scale,
4842 Index,
4843 Disp,
4844 Segment,
4845 Chain};
4846 CNode = CurDAG->getMachineNode(Opc, dl, {MVT::x86amx, MVT::Other}, Ops);
4847 ReplaceNode(Node, CNode);
4848 return;
4849 }
4850 }
4851 break;
4852 }
4853 case ISD::INTRINSIC_VOID: {
4854 unsigned IntNo = Node->getConstantOperandVal(1);
4855 switch (IntNo) {
4856 default: break;
4857 case Intrinsic::x86_sse3_monitor:
4858 case Intrinsic::x86_monitorx:
4859 case Intrinsic::x86_clzero: {
4860 bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64;
4861
4862 unsigned Opc = 0;
4863 switch (IntNo) {
4864 default: llvm_unreachable("Unexpected intrinsic!");
4865 case Intrinsic::x86_sse3_monitor:
4866 if (!Subtarget->hasSSE3())
4867 break;
4868 Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr;
4869 break;
4870 case Intrinsic::x86_monitorx:
4871 if (!Subtarget->hasMWAITX())
4872 break;
4873 Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr;
4874 break;
4875 case Intrinsic::x86_clzero:
4876 if (!Subtarget->hasCLZERO())
4877 break;
4878 Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r;
4879 break;
4880 }
4881
4882 if (Opc) {
4883 unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX;
4884 SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg,
4885 Node->getOperand(2), SDValue());
4886 SDValue InGlue = Chain.getValue(1);
4887
4888 if (IntNo == Intrinsic::x86_sse3_monitor ||
4889 IntNo == Intrinsic::x86_monitorx) {
4890 // Copy the other two operands to ECX and EDX.
4891 Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3),
4892 InGlue);
4893 InGlue = Chain.getValue(1);
4894 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4),
4895 InGlue);
4896 InGlue = Chain.getValue(1);
4897 }
4898
4899 MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
4900 { Chain, InGlue});
4901 ReplaceNode(Node, CNode);
4902 return;
4903 }
4904
4905 break;
4906 }
4907 case Intrinsic::x86_tilestored64_internal: {
4908 unsigned Opc = X86::PTILESTOREDV;
4909 // _tile_stored_internal(row, col, buf, STRIDE, c)
4910 SDValue Base = Node->getOperand(4);
4911 SDValue Scale = getI8Imm(1, dl);
4912 SDValue Index = Node->getOperand(5);
4913 SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32);
4914 SDValue Segment = CurDAG->getRegister(0, MVT::i16);
4915 SDValue Chain = Node->getOperand(0);
4916 MachineSDNode *CNode;
4917 SDValue Ops[] = {Node->getOperand(2),
4918 Node->getOperand(3),
4919