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