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