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