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" 15 #include "X86MachineFunctionInfo.h" 16 #include "X86RegisterInfo.h" 17 #include "X86Subtarget.h" 18 #include "X86TargetMachine.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/CodeGen/MachineModuleInfo.h" 21 #include "llvm/CodeGen/SelectionDAGISel.h" 22 #include "llvm/Config/llvm-config.h" 23 #include "llvm/IR/ConstantRange.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/Instructions.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" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/KnownBits.h" 32 #include "llvm/Support/MathExtras.h" 33 #include <cstdint> 34 35 using namespace llvm; 36 37 #define DEBUG_TYPE "x86-isel" 38 #define PASS_NAME "X86 DAG->DAG Instruction Selection" 39 40 STATISTIC(NumLoadMoved, "Number of loads moved below TokenFactor"); 41 42 static cl::opt<bool> AndImmShrink("x86-and-imm-shrink", cl::init(true), 43 cl::desc("Enable setting constant bits to reduce size of mask immediates"), 44 cl::Hidden); 45 46 static cl::opt<bool> EnablePromoteAnyextLoad( 47 "x86-promote-anyext-load", cl::init(true), 48 cl::desc("Enable promoting aligned anyext load to wider load"), cl::Hidden); 49 50 extern cl::opt<bool> IndirectBranchTracking; 51 52 //===----------------------------------------------------------------------===// 53 // Pattern Matcher Implementation 54 //===----------------------------------------------------------------------===// 55 56 namespace { 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 155 namespace { 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 191 SelectionDAGISel::runOnMachineFunction(MF); 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. 261 bool SelectInlineAsmMemoryOperand(const SDValue &Op, 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); 455 SDValue Zero = SDValue( 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 = N->getConstantOperandAPInt(1); 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 580 char X86DAGToDAGISel::ID = 0; 581 582 INITIALIZE_PASS(X86DAGToDAGISel, DEBUG_TYPE, PASS_NAME, false, false) 583 584 // Returns true if this masked compare can be implemented legally with this 585 // type. 586 static 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. 614 bool 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 625 bool 626 X86DAGToDAGISel::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); 715 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress) 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() || 769 ISD::isBuildVectorAllZeros(Root->getOperand(0).getNode()))) 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. 778 bool 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. 791 static void moveBelowOrigChain(SelectionDAG *CurDAG, SDValue Load, 792 SDValue Call, SDValue OrigChain) { 793 SmallVector<SDValue, 8> Ops; 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. 826 static 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 863 static 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 884 static bool needBWI(MVT VT) { 885 return (VT == MVT::v32i16 || VT == MVT::v32f16 || VT == MVT::v64i8); 886 } 887 888 void X86DAGToDAGISel::PreprocessISelDAG() { 889 bool MadeChange = false; 890 for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(), 891 E = CurDAG->allnodes_end(); I != E; ) { 892 SDNode *N = &*I++; // Preincrement iterator to avoid invalidation issues. 893 894 // This is for CET enhancement. 895 // 896 // ENDBR32 and ENDBR64 have specific opcodes: 897 // ENDBR32: F3 0F 1E FB 898 // ENDBR64: F3 0F 1E FA 899 // And we want that attackers won’t find unintended ENDBR32/64 900 // opcode matches in the binary 901 // Here’s an example: 902 // If the compiler had to generate asm for the following code: 903 // a = 0xF30F1EFA 904 // it could, for example, generate: 905 // mov 0xF30F1EFA, dword ptr[a] 906 // In such a case, the binary would include a gadget that starts 907 // with a fake ENDBR64 opcode. Therefore, we split such generation 908 // into multiple operations, let it not shows in the binary 909 if (N->getOpcode() == ISD::Constant) { 910 MVT VT = N->getSimpleValueType(0); 911 int64_t Imm = cast<ConstantSDNode>(N)->getSExtValue(); 912 int32_t EndbrImm = Subtarget->is64Bit() ? 0xF30F1EFA : 0xF30F1EFB; 913 if (Imm == EndbrImm || isEndbrImm64(Imm)) { 914 // Check that the cf-protection-branch is enabled. 915 Metadata *CFProtectionBranch = 916 MF->getMMI().getModule()->getModuleFlag("cf-protection-branch"); 917 if (CFProtectionBranch || IndirectBranchTracking) { 918 SDLoc dl(N); 919 SDValue Complement = CurDAG->getConstant(~Imm, dl, VT, false, true); 920 Complement = CurDAG->getNOT(dl, Complement, VT); 921 --I; 922 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Complement); 923 ++I; 924 MadeChange = true; 925 continue; 926 } 927 } 928 } 929 930 // If this is a target specific AND node with no flag usages, turn it back 931 // into ISD::AND to enable test instruction matching. 932 if (N->getOpcode() == X86ISD::AND && !N->hasAnyUseOfValue(1)) { 933 SDValue Res = CurDAG->getNode(ISD::AND, SDLoc(N), N->getValueType(0), 934 N->getOperand(0), N->getOperand(1)); 935 --I; 936 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); 937 ++I; 938 MadeChange = true; 939 continue; 940 } 941 942 // Convert vector increment or decrement to sub/add with an all-ones 943 // constant: 944 // add X, <1, 1...> --> sub X, <-1, -1...> 945 // sub X, <1, 1...> --> add X, <-1, -1...> 946 // The all-ones vector constant can be materialized using a pcmpeq 947 // instruction that is commonly recognized as an idiom (has no register 948 // dependency), so that's better/smaller than loading a splat 1 constant. 949 // 950 // But don't do this if it would inhibit a potentially profitable load 951 // folding opportunity for the other operand. That only occurs with the 952 // intersection of: 953 // (1) The other operand (op0) is load foldable. 954 // (2) The op is an add (otherwise, we are *creating* an add and can still 955 // load fold the other op). 956 // (3) The target has AVX (otherwise, we have a destructive add and can't 957 // load fold the other op without killing the constant op). 958 // (4) The constant 1 vector has multiple uses (so it is profitable to load 959 // into a register anyway). 960 auto mayPreventLoadFold = [&]() { 961 return X86::mayFoldLoad(N->getOperand(0), *Subtarget) && 962 N->getOpcode() == ISD::ADD && Subtarget->hasAVX() && 963 !N->getOperand(1).hasOneUse(); 964 }; 965 if ((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) && 966 N->getSimpleValueType(0).isVector() && !mayPreventLoadFold()) { 967 APInt SplatVal; 968 if (X86::isConstantSplat(N->getOperand(1), SplatVal) && 969 SplatVal.isOne()) { 970 SDLoc DL(N); 971 972 MVT VT = N->getSimpleValueType(0); 973 unsigned NumElts = VT.getSizeInBits() / 32; 974 SDValue AllOnes = 975 CurDAG->getAllOnesConstant(DL, MVT::getVectorVT(MVT::i32, NumElts)); 976 AllOnes = CurDAG->getBitcast(VT, AllOnes); 977 978 unsigned NewOpcode = N->getOpcode() == ISD::ADD ? ISD::SUB : ISD::ADD; 979 SDValue Res = 980 CurDAG->getNode(NewOpcode, DL, VT, N->getOperand(0), AllOnes); 981 --I; 982 CurDAG->ReplaceAllUsesWith(N, Res.getNode()); 983 ++I; 984 MadeChange = true; 985 continue; 986 } 987 } 988 989 switch (N->getOpcode()) { 990 case X86ISD::VBROADCAST: { 991 MVT VT = N->getSimpleValueType(0); 992 // Emulate v32i16/v64i8 broadcast without BWI. 993 if (!Subtarget->hasBWI() && needBWI(VT)) { 994 MVT NarrowVT = VT.getHalfNumVectorElementsVT(); 995 SDLoc dl(N); 996 SDValue NarrowBCast = 997 CurDAG->getNode(X86ISD::VBROADCAST, dl, NarrowVT, N->getOperand(0)); 998 SDValue Res = 999 CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT), 1000 NarrowBCast, CurDAG->getIntPtrConstant(0, dl)); 1001 unsigned Index = NarrowVT.getVectorMinNumElements(); 1002 Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast, 1003 CurDAG->getIntPtrConstant(Index, dl)); 1004 1005 --I; 1006 CurDAG->ReplaceAllUsesWith(N, Res.getNode()); 1007 ++I; 1008 MadeChange = true; 1009 continue; 1010 } 1011 1012 break; 1013 } 1014 case X86ISD::VBROADCAST_LOAD: { 1015 MVT VT = N->getSimpleValueType(0); 1016 // Emulate v32i16/v64i8 broadcast without BWI. 1017 if (!Subtarget->hasBWI() && needBWI(VT)) { 1018 MVT NarrowVT = VT.getHalfNumVectorElementsVT(); 1019 auto *MemNode = cast<MemSDNode>(N); 1020 SDLoc dl(N); 1021 SDVTList VTs = CurDAG->getVTList(NarrowVT, MVT::Other); 1022 SDValue Ops[] = {MemNode->getChain(), MemNode->getBasePtr()}; 1023 SDValue NarrowBCast = CurDAG->getMemIntrinsicNode( 1024 X86ISD::VBROADCAST_LOAD, dl, VTs, Ops, MemNode->getMemoryVT(), 1025 MemNode->getMemOperand()); 1026 SDValue Res = 1027 CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, CurDAG->getUNDEF(VT), 1028 NarrowBCast, CurDAG->getIntPtrConstant(0, dl)); 1029 unsigned Index = NarrowVT.getVectorMinNumElements(); 1030 Res = CurDAG->getNode(ISD::INSERT_SUBVECTOR, dl, VT, Res, NarrowBCast, 1031 CurDAG->getIntPtrConstant(Index, dl)); 1032 1033 --I; 1034 SDValue To[] = {Res, NarrowBCast.getValue(1)}; 1035 CurDAG->ReplaceAllUsesWith(N, To); 1036 ++I; 1037 MadeChange = true; 1038 continue; 1039 } 1040 1041 break; 1042 } 1043 case ISD::LOAD: { 1044 // If this is a XMM/YMM load of the same lower bits as another YMM/ZMM 1045 // load, then just extract the lower subvector and avoid the second load. 1046 auto *Ld = cast<LoadSDNode>(N); 1047 MVT VT = N->getSimpleValueType(0); 1048 if (!ISD::isNormalLoad(Ld) || !Ld->isSimple() || 1049 !(VT.is128BitVector() || VT.is256BitVector())) 1050 break; 1051 1052 MVT MaxVT = VT; 1053 SDNode *MaxLd = nullptr; 1054 SDValue Ptr = Ld->getBasePtr(); 1055 SDValue Chain = Ld->getChain(); 1056 for (SDNode *User : Ptr->uses()) { 1057 auto *UserLd = dyn_cast<LoadSDNode>(User); 1058 MVT UserVT = User->getSimpleValueType(0); 1059 if (User != N && UserLd && ISD::isNormalLoad(User) && 1060 UserLd->getBasePtr() == Ptr && UserLd->getChain() == Chain && 1061 !User->hasAnyUseOfValue(1) && 1062 (UserVT.is256BitVector() || UserVT.is512BitVector()) && 1063 UserVT.getSizeInBits() > VT.getSizeInBits() && 1064 (!MaxLd || UserVT.getSizeInBits() > MaxVT.getSizeInBits())) { 1065 MaxLd = User; 1066 MaxVT = UserVT; 1067 } 1068 } 1069 if (MaxLd) { 1070 SDLoc dl(N); 1071 unsigned NumSubElts = VT.getSizeInBits() / MaxVT.getScalarSizeInBits(); 1072 MVT SubVT = MVT::getVectorVT(MaxVT.getScalarType(), NumSubElts); 1073 SDValue Extract = CurDAG->getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, 1074 SDValue(MaxLd, 0), 1075 CurDAG->getIntPtrConstant(0, dl)); 1076 SDValue Res = CurDAG->getBitcast(VT, Extract); 1077 1078 --I; 1079 SDValue To[] = {Res, SDValue(MaxLd, 1)}; 1080 CurDAG->ReplaceAllUsesWith(N, To); 1081 ++I; 1082 MadeChange = true; 1083 continue; 1084 } 1085 break; 1086 } 1087 case ISD::VSELECT: { 1088 // Replace VSELECT with non-mask conditions with with BLENDV/VPTERNLOG. 1089 EVT EleVT = N->getOperand(0).getValueType().getVectorElementType(); 1090 if (EleVT == MVT::i1) 1091 break; 1092 1093 assert(Subtarget->hasSSE41() && "Expected SSE4.1 support!"); 1094 assert(N->getValueType(0).getVectorElementType() != MVT::i16 && 1095 "We can't replace VSELECT with BLENDV in vXi16!"); 1096 SDValue R; 1097 if (Subtarget->hasVLX() && CurDAG->ComputeNumSignBits(N->getOperand(0)) == 1098 EleVT.getSizeInBits()) { 1099 R = CurDAG->getNode(X86ISD::VPTERNLOG, SDLoc(N), N->getValueType(0), 1100 N->getOperand(0), N->getOperand(1), N->getOperand(2), 1101 CurDAG->getTargetConstant(0xCA, SDLoc(N), MVT::i8)); 1102 } else { 1103 R = CurDAG->getNode(X86ISD::BLENDV, SDLoc(N), N->getValueType(0), 1104 N->getOperand(0), N->getOperand(1), 1105 N->getOperand(2)); 1106 } 1107 --I; 1108 CurDAG->ReplaceAllUsesWith(N, R.getNode()); 1109 ++I; 1110 MadeChange = true; 1111 continue; 1112 } 1113 case ISD::FP_ROUND: 1114 case ISD::STRICT_FP_ROUND: 1115 case ISD::FP_TO_SINT: 1116 case ISD::FP_TO_UINT: 1117 case ISD::STRICT_FP_TO_SINT: 1118 case ISD::STRICT_FP_TO_UINT: { 1119 // Replace vector fp_to_s/uint with their X86 specific equivalent so we 1120 // don't need 2 sets of patterns. 1121 if (!N->getSimpleValueType(0).isVector()) 1122 break; 1123 1124 unsigned NewOpc; 1125 switch (N->getOpcode()) { 1126 default: llvm_unreachable("Unexpected opcode!"); 1127 case ISD::FP_ROUND: NewOpc = X86ISD::VFPROUND; break; 1128 case ISD::STRICT_FP_ROUND: NewOpc = X86ISD::STRICT_VFPROUND; break; 1129 case ISD::STRICT_FP_TO_SINT: NewOpc = X86ISD::STRICT_CVTTP2SI; break; 1130 case ISD::FP_TO_SINT: NewOpc = X86ISD::CVTTP2SI; break; 1131 case ISD::STRICT_FP_TO_UINT: NewOpc = X86ISD::STRICT_CVTTP2UI; break; 1132 case ISD::FP_TO_UINT: NewOpc = X86ISD::CVTTP2UI; break; 1133 } 1134 SDValue Res; 1135 if (N->isStrictFPOpcode()) 1136 Res = 1137 CurDAG->getNode(NewOpc, SDLoc(N), {N->getValueType(0), MVT::Other}, 1138 {N->getOperand(0), N->getOperand(1)}); 1139 else 1140 Res = 1141 CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0), 1142 N->getOperand(0)); 1143 --I; 1144 CurDAG->ReplaceAllUsesWith(N, Res.getNode()); 1145 ++I; 1146 MadeChange = true; 1147 continue; 1148 } 1149 case ISD::SHL: 1150 case ISD::SRA: 1151 case ISD::SRL: { 1152 // Replace vector shifts with their X86 specific equivalent so we don't 1153 // need 2 sets of patterns. 1154 if (!N->getValueType(0).isVector()) 1155 break; 1156 1157 unsigned NewOpc; 1158 switch (N->getOpcode()) { 1159 default: llvm_unreachable("Unexpected opcode!"); 1160 case ISD::SHL: NewOpc = X86ISD::VSHLV; break; 1161 case ISD::SRA: NewOpc = X86ISD::VSRAV; break; 1162 case ISD::SRL: NewOpc = X86ISD::VSRLV; break; 1163 } 1164 SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0), 1165 N->getOperand(0), N->getOperand(1)); 1166 --I; 1167 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); 1168 ++I; 1169 MadeChange = true; 1170 continue; 1171 } 1172 case ISD::ANY_EXTEND: 1173 case ISD::ANY_EXTEND_VECTOR_INREG: { 1174 // Replace vector any extend with the zero extend equivalents so we don't 1175 // need 2 sets of patterns. Ignore vXi1 extensions. 1176 if (!N->getValueType(0).isVector()) 1177 break; 1178 1179 unsigned NewOpc; 1180 if (N->getOperand(0).getScalarValueSizeInBits() == 1) { 1181 assert(N->getOpcode() == ISD::ANY_EXTEND && 1182 "Unexpected opcode for mask vector!"); 1183 NewOpc = ISD::SIGN_EXTEND; 1184 } else { 1185 NewOpc = N->getOpcode() == ISD::ANY_EXTEND 1186 ? ISD::ZERO_EXTEND 1187 : ISD::ZERO_EXTEND_VECTOR_INREG; 1188 } 1189 1190 SDValue Res = CurDAG->getNode(NewOpc, SDLoc(N), N->getValueType(0), 1191 N->getOperand(0)); 1192 --I; 1193 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); 1194 ++I; 1195 MadeChange = true; 1196 continue; 1197 } 1198 case ISD::FCEIL: 1199 case ISD::STRICT_FCEIL: 1200 case ISD::FFLOOR: 1201 case ISD::STRICT_FFLOOR: 1202 case ISD::FTRUNC: 1203 case ISD::STRICT_FTRUNC: 1204 case ISD::FROUNDEVEN: 1205 case ISD::STRICT_FROUNDEVEN: 1206 case ISD::FNEARBYINT: 1207 case ISD::STRICT_FNEARBYINT: 1208 case ISD::FRINT: 1209 case ISD::STRICT_FRINT: { 1210 // Replace fp rounding with their X86 specific equivalent so we don't 1211 // need 2 sets of patterns. 1212 unsigned Imm; 1213 switch (N->getOpcode()) { 1214 default: llvm_unreachable("Unexpected opcode!"); 1215 case ISD::STRICT_FCEIL: 1216 case ISD::FCEIL: Imm = 0xA; break; 1217 case ISD::STRICT_FFLOOR: 1218 case ISD::FFLOOR: Imm = 0x9; break; 1219 case ISD::STRICT_FTRUNC: 1220 case ISD::FTRUNC: Imm = 0xB; break; 1221 case ISD::STRICT_FROUNDEVEN: 1222 case ISD::FROUNDEVEN: Imm = 0x8; break; 1223 case ISD::STRICT_FNEARBYINT: 1224 case ISD::FNEARBYINT: Imm = 0xC; break; 1225 case ISD::STRICT_FRINT: 1226 case ISD::FRINT: Imm = 0x4; break; 1227 } 1228 SDLoc dl(N); 1229 bool IsStrict = N->isStrictFPOpcode(); 1230 SDValue Res; 1231 if (IsStrict) 1232 Res = CurDAG->getNode(X86ISD::STRICT_VRNDSCALE, dl, 1233 {N->getValueType(0), MVT::Other}, 1234 {N->getOperand(0), N->getOperand(1), 1235 CurDAG->getTargetConstant(Imm, dl, MVT::i32)}); 1236 else 1237 Res = CurDAG->getNode(X86ISD::VRNDSCALE, dl, N->getValueType(0), 1238 N->getOperand(0), 1239 CurDAG->getTargetConstant(Imm, dl, MVT::i32)); 1240 --I; 1241 CurDAG->ReplaceAllUsesWith(N, Res.getNode()); 1242 ++I; 1243 MadeChange = true; 1244 continue; 1245 } 1246 case X86ISD::FANDN: 1247 case X86ISD::FAND: 1248 case X86ISD::FOR: 1249 case X86ISD::FXOR: { 1250 // Widen scalar fp logic ops to vector to reduce isel patterns. 1251 // FIXME: Can we do this during lowering/combine. 1252 MVT VT = N->getSimpleValueType(0); 1253 if (VT.isVector() || VT == MVT::f128) 1254 break; 1255 1256 MVT VecVT = VT == MVT::f64 ? MVT::v2f64 1257 : VT == MVT::f32 ? MVT::v4f32 1258 : MVT::v8f16; 1259 1260 SDLoc dl(N); 1261 SDValue Op0 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, 1262 N->getOperand(0)); 1263 SDValue Op1 = CurDAG->getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, 1264 N->getOperand(1)); 1265 1266 SDValue Res; 1267 if (Subtarget->hasSSE2()) { 1268 EVT IntVT = EVT(VecVT).changeVectorElementTypeToInteger(); 1269 Op0 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op0); 1270 Op1 = CurDAG->getNode(ISD::BITCAST, dl, IntVT, Op1); 1271 unsigned Opc; 1272 switch (N->getOpcode()) { 1273 default: llvm_unreachable("Unexpected opcode!"); 1274 case X86ISD::FANDN: Opc = X86ISD::ANDNP; break; 1275 case X86ISD::FAND: Opc = ISD::AND; break; 1276 case X86ISD::FOR: Opc = ISD::OR; break; 1277 case X86ISD::FXOR: Opc = ISD::XOR; break; 1278 } 1279 Res = CurDAG->getNode(Opc, dl, IntVT, Op0, Op1); 1280 Res = CurDAG->getNode(ISD::BITCAST, dl, VecVT, Res); 1281 } else { 1282 Res = CurDAG->getNode(N->getOpcode(), dl, VecVT, Op0, Op1); 1283 } 1284 Res = CurDAG->getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Res, 1285 CurDAG->getIntPtrConstant(0, dl)); 1286 --I; 1287 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); 1288 ++I; 1289 MadeChange = true; 1290 continue; 1291 } 1292 } 1293 1294 if (OptLevel != CodeGenOptLevel::None && 1295 // Only do this when the target can fold the load into the call or 1296 // jmp. 1297 !Subtarget->useIndirectThunkCalls() && 1298 ((N->getOpcode() == X86ISD::CALL && !Subtarget->slowTwoMemOps()) || 1299 (N->getOpcode() == X86ISD::TC_RETURN && 1300 (Subtarget->is64Bit() || 1301 !getTargetMachine().isPositionIndependent())))) { 1302 /// Also try moving call address load from outside callseq_start to just 1303 /// before the call to allow it to be folded. 1304 /// 1305 /// [Load chain] 1306 /// ^ 1307 /// | 1308 /// [Load] 1309 /// ^ ^ 1310 /// | | 1311 /// / \-- 1312 /// / | 1313 ///[CALLSEQ_START] | 1314 /// ^ | 1315 /// | | 1316 /// [LOAD/C2Reg] | 1317 /// | | 1318 /// \ / 1319 /// \ / 1320 /// [CALL] 1321 bool HasCallSeq = N->getOpcode() == X86ISD::CALL; 1322 SDValue Chain = N->getOperand(0); 1323 SDValue Load = N->getOperand(1); 1324 if (!isCalleeLoad(Load, Chain, HasCallSeq)) 1325 continue; 1326 moveBelowOrigChain(CurDAG, Load, SDValue(N, 0), Chain); 1327 ++NumLoadMoved; 1328 MadeChange = true; 1329 continue; 1330 } 1331 1332 // Lower fpround and fpextend nodes that target the FP stack to be store and 1333 // load to the stack. This is a gross hack. We would like to simply mark 1334 // these as being illegal, but when we do that, legalize produces these when 1335 // it expands calls, then expands these in the same legalize pass. We would 1336 // like dag combine to be able to hack on these between the call expansion 1337 // and the node legalization. As such this pass basically does "really 1338 // late" legalization of these inline with the X86 isel pass. 1339 // FIXME: This should only happen when not compiled with -O0. 1340 switch (N->getOpcode()) { 1341 default: continue; 1342 case ISD::FP_ROUND: 1343 case ISD::FP_EXTEND: 1344 { 1345 MVT SrcVT = N->getOperand(0).getSimpleValueType(); 1346 MVT DstVT = N->getSimpleValueType(0); 1347 1348 // If any of the sources are vectors, no fp stack involved. 1349 if (SrcVT.isVector() || DstVT.isVector()) 1350 continue; 1351 1352 // If the source and destination are SSE registers, then this is a legal 1353 // conversion that should not be lowered. 1354 const X86TargetLowering *X86Lowering = 1355 static_cast<const X86TargetLowering *>(TLI); 1356 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT); 1357 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT); 1358 if (SrcIsSSE && DstIsSSE) 1359 continue; 1360 1361 if (!SrcIsSSE && !DstIsSSE) { 1362 // If this is an FPStack extension, it is a noop. 1363 if (N->getOpcode() == ISD::FP_EXTEND) 1364 continue; 1365 // If this is a value-preserving FPStack truncation, it is a noop. 1366 if (N->getConstantOperandVal(1)) 1367 continue; 1368 } 1369 1370 // Here we could have an FP stack truncation or an FPStack <-> SSE convert. 1371 // FPStack has extload and truncstore. SSE can fold direct loads into other 1372 // operations. Based on this, decide what we want to do. 1373 MVT MemVT = (N->getOpcode() == ISD::FP_ROUND) ? DstVT : SrcVT; 1374 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT); 1375 int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex(); 1376 MachinePointerInfo MPI = 1377 MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI); 1378 SDLoc dl(N); 1379 1380 // FIXME: optimize the case where the src/dest is a load or store? 1381 1382 SDValue Store = CurDAG->getTruncStore( 1383 CurDAG->getEntryNode(), dl, N->getOperand(0), MemTmp, MPI, MemVT); 1384 SDValue Result = CurDAG->getExtLoad(ISD::EXTLOAD, dl, DstVT, Store, 1385 MemTmp, MPI, MemVT); 1386 1387 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the 1388 // extload we created. This will cause general havok on the dag because 1389 // anything below the conversion could be folded into other existing nodes. 1390 // To avoid invalidating 'I', back it up to the convert node. 1391 --I; 1392 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Result); 1393 break; 1394 } 1395 1396 //The sequence of events for lowering STRICT_FP versions of these nodes requires 1397 //dealing with the chain differently, as there is already a preexisting chain. 1398 case ISD::STRICT_FP_ROUND: 1399 case ISD::STRICT_FP_EXTEND: 1400 { 1401 MVT SrcVT = N->getOperand(1).getSimpleValueType(); 1402 MVT DstVT = N->getSimpleValueType(0); 1403 1404 // If any of the sources are vectors, no fp stack involved. 1405 if (SrcVT.isVector() || DstVT.isVector()) 1406 continue; 1407 1408 // If the source and destination are SSE registers, then this is a legal 1409 // conversion that should not be lowered. 1410 const X86TargetLowering *X86Lowering = 1411 static_cast<const X86TargetLowering *>(TLI); 1412 bool SrcIsSSE = X86Lowering->isScalarFPTypeInSSEReg(SrcVT); 1413 bool DstIsSSE = X86Lowering->isScalarFPTypeInSSEReg(DstVT); 1414 if (SrcIsSSE && DstIsSSE) 1415 continue; 1416 1417 if (!SrcIsSSE && !DstIsSSE) { 1418 // If this is an FPStack extension, it is a noop. 1419 if (N->getOpcode() == ISD::STRICT_FP_EXTEND) 1420 continue; 1421 // If this is a value-preserving FPStack truncation, it is a noop. 1422 if (N->getConstantOperandVal(2)) 1423 continue; 1424 } 1425 1426 // Here we could have an FP stack truncation or an FPStack <-> SSE convert. 1427 // FPStack has extload and truncstore. SSE can fold direct loads into other 1428 // operations. Based on this, decide what we want to do. 1429 MVT MemVT = (N->getOpcode() == ISD::STRICT_FP_ROUND) ? DstVT : SrcVT; 1430 SDValue MemTmp = CurDAG->CreateStackTemporary(MemVT); 1431 int SPFI = cast<FrameIndexSDNode>(MemTmp)->getIndex(); 1432 MachinePointerInfo MPI = 1433 MachinePointerInfo::getFixedStack(CurDAG->getMachineFunction(), SPFI); 1434 SDLoc dl(N); 1435 1436 // FIXME: optimize the case where the src/dest is a load or store? 1437 1438 //Since the operation is StrictFP, use the preexisting chain. 1439 SDValue Store, Result; 1440 if (!SrcIsSSE) { 1441 SDVTList VTs = CurDAG->getVTList(MVT::Other); 1442 SDValue Ops[] = {N->getOperand(0), N->getOperand(1), MemTmp}; 1443 Store = CurDAG->getMemIntrinsicNode(X86ISD::FST, dl, VTs, Ops, MemVT, 1444 MPI, /*Align*/ std::nullopt, 1445 MachineMemOperand::MOStore); 1446 if (N->getFlags().hasNoFPExcept()) { 1447 SDNodeFlags Flags = Store->getFlags(); 1448 Flags.setNoFPExcept(true); 1449 Store->setFlags(Flags); 1450 } 1451 } else { 1452 assert(SrcVT == MemVT && "Unexpected VT!"); 1453 Store = CurDAG->getStore(N->getOperand(0), dl, N->getOperand(1), MemTmp, 1454 MPI); 1455 } 1456 1457 if (!DstIsSSE) { 1458 SDVTList VTs = CurDAG->getVTList(DstVT, MVT::Other); 1459 SDValue Ops[] = {Store, MemTmp}; 1460 Result = CurDAG->getMemIntrinsicNode( 1461 X86ISD::FLD, dl, VTs, Ops, MemVT, MPI, 1462 /*Align*/ std::nullopt, MachineMemOperand::MOLoad); 1463 if (N->getFlags().hasNoFPExcept()) { 1464 SDNodeFlags Flags = Result->getFlags(); 1465 Flags.setNoFPExcept(true); 1466 Result->setFlags(Flags); 1467 } 1468 } else { 1469 assert(DstVT == MemVT && "Unexpected VT!"); 1470 Result = CurDAG->getLoad(DstVT, dl, Store, MemTmp, MPI); 1471 } 1472 1473 // We're about to replace all uses of the FP_ROUND/FP_EXTEND with the 1474 // extload we created. This will cause general havok on the dag because 1475 // anything below the conversion could be folded into other existing nodes. 1476 // To avoid invalidating 'I', back it up to the convert node. 1477 --I; 1478 CurDAG->ReplaceAllUsesWith(N, Result.getNode()); 1479 break; 1480 } 1481 } 1482 1483 1484 // Now that we did that, the node is dead. Increment the iterator to the 1485 // next node to process, then delete N. 1486 ++I; 1487 MadeChange = true; 1488 } 1489 1490 // Remove any dead nodes that may have been left behind. 1491 if (MadeChange) 1492 CurDAG->RemoveDeadNodes(); 1493 } 1494 1495 // Look for a redundant movzx/movsx that can occur after an 8-bit divrem. 1496 bool X86DAGToDAGISel::tryOptimizeRem8Extend(SDNode *N) { 1497 unsigned Opc = N->getMachineOpcode(); 1498 if (Opc != X86::MOVZX32rr8 && Opc != X86::MOVSX32rr8 && 1499 Opc != X86::MOVSX64rr8) 1500 return false; 1501 1502 SDValue N0 = N->getOperand(0); 1503 1504 // We need to be extracting the lower bit of an extend. 1505 if (!N0.isMachineOpcode() || 1506 N0.getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG || 1507 N0.getConstantOperandVal(1) != X86::sub_8bit) 1508 return false; 1509 1510 // We're looking for either a movsx or movzx to match the original opcode. 1511 unsigned ExpectedOpc = Opc == X86::MOVZX32rr8 ? X86::MOVZX32rr8_NOREX 1512 : X86::MOVSX32rr8_NOREX; 1513 SDValue N00 = N0.getOperand(0); 1514 if (!N00.isMachineOpcode() || N00.getMachineOpcode() != ExpectedOpc) 1515 return false; 1516 1517 if (Opc == X86::MOVSX64rr8) { 1518 // If we had a sign extend from 8 to 64 bits. We still need to go from 32 1519 // to 64. 1520 MachineSDNode *Extend = CurDAG->getMachineNode(X86::MOVSX64rr32, SDLoc(N), 1521 MVT::i64, N00); 1522 ReplaceUses(N, Extend); 1523 } else { 1524 // Ok we can drop this extend and just use the original extend. 1525 ReplaceUses(N, N00.getNode()); 1526 } 1527 1528 return true; 1529 } 1530 1531 void X86DAGToDAGISel::PostprocessISelDAG() { 1532 // Skip peepholes at -O0. 1533 if (TM.getOptLevel() == CodeGenOptLevel::None) 1534 return; 1535 1536 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end(); 1537 1538 bool MadeChange = false; 1539 while (Position != CurDAG->allnodes_begin()) { 1540 SDNode *N = &*--Position; 1541 // Skip dead nodes and any non-machine opcodes. 1542 if (N->use_empty() || !N->isMachineOpcode()) 1543 continue; 1544 1545 if (tryOptimizeRem8Extend(N)) { 1546 MadeChange = true; 1547 continue; 1548 } 1549 1550 // Look for a TESTrr+ANDrr pattern where both operands of the test are 1551 // the same. Rewrite to remove the AND. 1552 unsigned Opc = N->getMachineOpcode(); 1553 if ((Opc == X86::TEST8rr || Opc == X86::TEST16rr || 1554 Opc == X86::TEST32rr || Opc == X86::TEST64rr) && 1555 N->getOperand(0) == N->getOperand(1) && 1556 N->getOperand(0)->hasNUsesOfValue(2, N->getOperand(0).getResNo()) && 1557 N->getOperand(0).isMachineOpcode()) { 1558 SDValue And = N->getOperand(0); 1559 unsigned N0Opc = And.getMachineOpcode(); 1560 if ((N0Opc == X86::AND8rr || N0Opc == X86::AND16rr || 1561 N0Opc == X86::AND32rr || N0Opc == X86::AND64rr) && 1562 !And->hasAnyUseOfValue(1)) { 1563 MachineSDNode *Test = CurDAG->getMachineNode(Opc, SDLoc(N), 1564 MVT::i32, 1565 And.getOperand(0), 1566 And.getOperand(1)); 1567 ReplaceUses(N, Test); 1568 MadeChange = true; 1569 continue; 1570 } 1571 if ((N0Opc == X86::AND8rm || N0Opc == X86::AND16rm || 1572 N0Opc == X86::AND32rm || N0Opc == X86::AND64rm) && 1573 !And->hasAnyUseOfValue(1)) { 1574 unsigned NewOpc; 1575 switch (N0Opc) { 1576 case X86::AND8rm: NewOpc = X86::TEST8mr; break; 1577 case X86::AND16rm: NewOpc = X86::TEST16mr; break; 1578 case X86::AND32rm: NewOpc = X86::TEST32mr; break; 1579 case X86::AND64rm: NewOpc = X86::TEST64mr; break; 1580 } 1581 1582 // Need to swap the memory and register operand. 1583 SDValue Ops[] = { And.getOperand(1), 1584 And.getOperand(2), 1585 And.getOperand(3), 1586 And.getOperand(4), 1587 And.getOperand(5), 1588 And.getOperand(0), 1589 And.getOperand(6) /* Chain */ }; 1590 MachineSDNode *Test = CurDAG->getMachineNode(NewOpc, SDLoc(N), 1591 MVT::i32, MVT::Other, Ops); 1592 CurDAG->setNodeMemRefs( 1593 Test, cast<MachineSDNode>(And.getNode())->memoperands()); 1594 ReplaceUses(And.getValue(2), SDValue(Test, 1)); 1595 ReplaceUses(SDValue(N, 0), SDValue(Test, 0)); 1596 MadeChange = true; 1597 continue; 1598 } 1599 } 1600 1601 // Look for a KAND+KORTEST and turn it into KTEST if only the zero flag is 1602 // used. We're doing this late so we can prefer to fold the AND into masked 1603 // comparisons. Doing that can be better for the live range of the mask 1604 // register. 1605 if ((Opc == X86::KORTESTBrr || Opc == X86::KORTESTWrr || 1606 Opc == X86::KORTESTDrr || Opc == X86::KORTESTQrr) && 1607 N->getOperand(0) == N->getOperand(1) && 1608 N->isOnlyUserOf(N->getOperand(0).getNode()) && 1609 N->getOperand(0).isMachineOpcode() && 1610 onlyUsesZeroFlag(SDValue(N, 0))) { 1611 SDValue And = N->getOperand(0); 1612 unsigned N0Opc = And.getMachineOpcode(); 1613 // KANDW is legal with AVX512F, but KTESTW requires AVX512DQ. The other 1614 // KAND instructions and KTEST use the same ISA feature. 1615 if (N0Opc == X86::KANDBrr || 1616 (N0Opc == X86::KANDWrr && Subtarget->hasDQI()) || 1617 N0Opc == X86::KANDDrr || N0Opc == X86::KANDQrr) { 1618 unsigned NewOpc; 1619 switch (Opc) { 1620 default: llvm_unreachable("Unexpected opcode!"); 1621 case X86::KORTESTBrr: NewOpc = X86::KTESTBrr; break; 1622 case X86::KORTESTWrr: NewOpc = X86::KTESTWrr; break; 1623 case X86::KORTESTDrr: NewOpc = X86::KTESTDrr; break; 1624 case X86::KORTESTQrr: NewOpc = X86::KTESTQrr; break; 1625 } 1626 MachineSDNode *KTest = CurDAG->getMachineNode(NewOpc, SDLoc(N), 1627 MVT::i32, 1628 And.getOperand(0), 1629 And.getOperand(1)); 1630 ReplaceUses(N, KTest); 1631 MadeChange = true; 1632 continue; 1633 } 1634 } 1635 1636 // Attempt to remove vectors moves that were inserted to zero upper bits. 1637 if (Opc != TargetOpcode::SUBREG_TO_REG) 1638 continue; 1639 1640 unsigned SubRegIdx = N->getConstantOperandVal(2); 1641 if (SubRegIdx != X86::sub_xmm && SubRegIdx != X86::sub_ymm) 1642 continue; 1643 1644 SDValue Move = N->getOperand(1); 1645 if (!Move.isMachineOpcode()) 1646 continue; 1647 1648 // Make sure its one of the move opcodes we recognize. 1649 switch (Move.getMachineOpcode()) { 1650 default: 1651 continue; 1652 case X86::VMOVAPDrr: case X86::VMOVUPDrr: 1653 case X86::VMOVAPSrr: case X86::VMOVUPSrr: 1654 case X86::VMOVDQArr: case X86::VMOVDQUrr: 1655 case X86::VMOVAPDYrr: case X86::VMOVUPDYrr: 1656 case X86::VMOVAPSYrr: case X86::VMOVUPSYrr: 1657 case X86::VMOVDQAYrr: case X86::VMOVDQUYrr: 1658 case X86::VMOVAPDZ128rr: case X86::VMOVUPDZ128rr: 1659 case X86::VMOVAPSZ128rr: case X86::VMOVUPSZ128rr: 1660 case X86::VMOVDQA32Z128rr: case X86::VMOVDQU32Z128rr: 1661 case X86::VMOVDQA64Z128rr: case X86::VMOVDQU64Z128rr: 1662 case X86::VMOVAPDZ256rr: case X86::VMOVUPDZ256rr: 1663 case X86::VMOVAPSZ256rr: case X86::VMOVUPSZ256rr: 1664 case X86::VMOVDQA32Z256rr: case X86::VMOVDQU32Z256rr: 1665 case X86::VMOVDQA64Z256rr: case X86::VMOVDQU64Z256rr: 1666 break; 1667 } 1668 1669 SDValue In = Move.getOperand(0); 1670 if (!In.isMachineOpcode() || 1671 In.getMachineOpcode() <= TargetOpcode::GENERIC_OP_END) 1672 continue; 1673 1674 // Make sure the instruction has a VEX, XOP, or EVEX prefix. This covers 1675 // the SHA instructions which use a legacy encoding. 1676 uint64_t TSFlags = getInstrInfo()->get(In.getMachineOpcode()).TSFlags; 1677 if ((TSFlags & X86II::EncodingMask) != X86II::VEX && 1678 (TSFlags & X86II::EncodingMask) != X86II::EVEX && 1679 (TSFlags & X86II::EncodingMask) != X86II::XOP) 1680 continue; 1681 1682 // Producing instruction is another vector instruction. We can drop the 1683 // move. 1684 CurDAG->UpdateNodeOperands(N, N->getOperand(0), In, N->getOperand(2)); 1685 MadeChange = true; 1686 } 1687 1688 if (MadeChange) 1689 CurDAG->RemoveDeadNodes(); 1690 } 1691 1692 1693 /// Emit any code that needs to be executed only in the main function. 1694 void X86DAGToDAGISel::emitSpecialCodeForMain() { 1695 if (Subtarget->isTargetCygMing()) { 1696 TargetLowering::ArgListTy Args; 1697 auto &DL = CurDAG->getDataLayout(); 1698 1699 TargetLowering::CallLoweringInfo CLI(*CurDAG); 1700 CLI.setChain(CurDAG->getRoot()) 1701 .setCallee(CallingConv::C, Type::getVoidTy(*CurDAG->getContext()), 1702 CurDAG->getExternalSymbol("__main", TLI->getPointerTy(DL)), 1703 std::move(Args)); 1704 const TargetLowering &TLI = CurDAG->getTargetLoweringInfo(); 1705 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI); 1706 CurDAG->setRoot(Result.second); 1707 } 1708 } 1709 1710 void X86DAGToDAGISel::emitFunctionEntryCode() { 1711 // If this is main, emit special code for main. 1712 const Function &F = MF->getFunction(); 1713 if (F.hasExternalLinkage() && F.getName() == "main") 1714 emitSpecialCodeForMain(); 1715 } 1716 1717 static bool isDispSafeForFrameIndex(int64_t Val) { 1718 // On 64-bit platforms, we can run into an issue where a frame index 1719 // includes a displacement that, when added to the explicit displacement, 1720 // will overflow the displacement field. Assuming that the frame index 1721 // displacement fits into a 31-bit integer (which is only slightly more 1722 // aggressive than the current fundamental assumption that it fits into 1723 // a 32-bit integer), a 31-bit disp should always be safe. 1724 return isInt<31>(Val); 1725 } 1726 1727 bool X86DAGToDAGISel::foldOffsetIntoAddress(uint64_t Offset, 1728 X86ISelAddressMode &AM) { 1729 // We may have already matched a displacement and the caller just added the 1730 // symbolic displacement. So we still need to do the checks even if Offset 1731 // is zero. 1732 1733 int64_t Val = AM.Disp + Offset; 1734 1735 // Cannot combine ExternalSymbol displacements with integer offsets. 1736 if (Val != 0 && (AM.ES || AM.MCSym)) 1737 return true; 1738 1739 CodeModel::Model M = TM.getCodeModel(); 1740 if (Subtarget->is64Bit()) { 1741 if (Val != 0 && 1742 !X86::isOffsetSuitableForCodeModel(Val, M, 1743 AM.hasSymbolicDisplacement())) 1744 return true; 1745 // In addition to the checks required for a register base, check that 1746 // we do not try to use an unsafe Disp with a frame index. 1747 if (AM.BaseType == X86ISelAddressMode::FrameIndexBase && 1748 !isDispSafeForFrameIndex(Val)) 1749 return true; 1750 // In ILP32 (x32) mode, pointers are 32 bits and need to be zero-extended to 1751 // 64 bits. Instructions with 32-bit register addresses perform this zero 1752 // extension for us and we can safely ignore the high bits of Offset. 1753 // Instructions with only a 32-bit immediate address do not, though: they 1754 // sign extend instead. This means only address the low 2GB of address space 1755 // is directly addressable, we need indirect addressing for the high 2GB of 1756 // address space. 1757 // TODO: Some of the earlier checks may be relaxed for ILP32 mode as the 1758 // implicit zero extension of instructions would cover up any problem. 1759 // However, we have asserts elsewhere that get triggered if we do, so keep 1760 // the checks for now. 1761 // TODO: We would actually be able to accept these, as well as the same 1762 // addresses in LP64 mode, by adding the EIZ pseudo-register as an operand 1763 // to get an address size override to be emitted. However, this 1764 // pseudo-register is not part of any register class and therefore causes 1765 // MIR verification to fail. 1766 if (Subtarget->isTarget64BitILP32() && !isUInt<31>(Val) && 1767 !AM.hasBaseOrIndexReg()) 1768 return true; 1769 } 1770 AM.Disp = Val; 1771 return false; 1772 } 1773 1774 bool X86DAGToDAGISel::matchLoadInAddress(LoadSDNode *N, X86ISelAddressMode &AM, 1775 bool AllowSegmentRegForX32) { 1776 SDValue Address = N->getOperand(1); 1777 1778 // load gs:0 -> GS segment register. 1779 // load fs:0 -> FS segment register. 1780 // 1781 // This optimization is generally valid because the GNU TLS model defines that 1782 // gs:0 (or fs:0 on X86-64) contains its own address. However, for X86-64 mode 1783 // with 32-bit registers, as we get in ILP32 mode, those registers are first 1784 // zero-extended to 64 bits and then added it to the base address, which gives 1785 // unwanted results when the register holds a negative value. 1786 // For more information see http://people.redhat.com/drepper/tls.pdf 1787 if (isNullConstant(Address) && AM.Segment.getNode() == nullptr && 1788 !IndirectTlsSegRefs && 1789 (Subtarget->isTargetGlibc() || Subtarget->isTargetAndroid() || 1790 Subtarget->isTargetFuchsia())) { 1791 if (Subtarget->isTarget64BitILP32() && !AllowSegmentRegForX32) 1792 return true; 1793 switch (N->getPointerInfo().getAddrSpace()) { 1794 case X86AS::GS: 1795 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16); 1796 return false; 1797 case X86AS::FS: 1798 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16); 1799 return false; 1800 // Address space X86AS::SS is not handled here, because it is not used to 1801 // address TLS areas. 1802 } 1803 } 1804 1805 return true; 1806 } 1807 1808 /// Try to match X86ISD::Wrapper and X86ISD::WrapperRIP nodes into an addressing 1809 /// mode. These wrap things that will resolve down into a symbol reference. 1810 /// If no match is possible, this returns true, otherwise it returns false. 1811 bool X86DAGToDAGISel::matchWrapper(SDValue N, X86ISelAddressMode &AM) { 1812 // If the addressing mode already has a symbol as the displacement, we can 1813 // never match another symbol. 1814 if (AM.hasSymbolicDisplacement()) 1815 return true; 1816 1817 bool IsRIPRelTLS = false; 1818 bool IsRIPRel = N.getOpcode() == X86ISD::WrapperRIP; 1819 if (IsRIPRel) { 1820 SDValue Val = N.getOperand(0); 1821 if (Val.getOpcode() == ISD::TargetGlobalTLSAddress) 1822 IsRIPRelTLS = true; 1823 } 1824 1825 // We can't use an addressing mode in the 64-bit large code model. 1826 // Global TLS addressing is an exception. In the medium code model, 1827 // we use can use a mode when RIP wrappers are present. 1828 // That signifies access to globals that are known to be "near", 1829 // such as the GOT itself. 1830 CodeModel::Model M = TM.getCodeModel(); 1831 if (Subtarget->is64Bit() && M == CodeModel::Large && !IsRIPRelTLS) 1832 return true; 1833 1834 // Base and index reg must be 0 in order to use %rip as base. 1835 if (IsRIPRel && AM.hasBaseOrIndexReg()) 1836 return true; 1837 1838 // Make a local copy in case we can't do this fold. 1839 X86ISelAddressMode Backup = AM; 1840 1841 int64_t Offset = 0; 1842 SDValue N0 = N.getOperand(0); 1843 if (auto *G = dyn_cast<GlobalAddressSDNode>(N0)) { 1844 AM.GV = G->getGlobal(); 1845 AM.SymbolFlags = G->getTargetFlags(); 1846 Offset = G->getOffset(); 1847 } else if (auto *CP = dyn_cast<ConstantPoolSDNode>(N0)) { 1848 AM.CP = CP->getConstVal(); 1849 AM.Alignment = CP->getAlign(); 1850 AM.SymbolFlags = CP->getTargetFlags(); 1851 Offset = CP->getOffset(); 1852 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(N0)) { 1853 AM.ES = S->getSymbol(); 1854 AM.SymbolFlags = S->getTargetFlags(); 1855 } else if (auto *S = dyn_cast<MCSymbolSDNode>(N0)) { 1856 AM.MCSym = S->getMCSymbol(); 1857 } else if (auto *J = dyn_cast<JumpTableSDNode>(N0)) { 1858 AM.JT = J->getIndex(); 1859 AM.SymbolFlags = J->getTargetFlags(); 1860 } else if (auto *BA = dyn_cast<BlockAddressSDNode>(N0)) { 1861 AM.BlockAddr = BA->getBlockAddress(); 1862 AM.SymbolFlags = BA->getTargetFlags(); 1863 Offset = BA->getOffset(); 1864 } else 1865 llvm_unreachable("Unhandled symbol reference node."); 1866 1867 // Can't use an addressing mode with large globals. 1868 if (Subtarget->is64Bit() && !IsRIPRel && AM.GV && 1869 TM.isLargeGlobalValue(AM.GV)) { 1870 AM = Backup; 1871 return true; 1872 } 1873 1874 if (foldOffsetIntoAddress(Offset, AM)) { 1875 AM = Backup; 1876 return true; 1877 } 1878 1879 if (IsRIPRel) 1880 AM.setBaseReg(CurDAG->getRegister(X86::RIP, MVT::i64)); 1881 1882 // Commit the changes now that we know this fold is safe. 1883 return false; 1884 } 1885 1886 /// Add the specified node to the specified addressing mode, returning true if 1887 /// it cannot be done. This just pattern matches for the addressing mode. 1888 bool X86DAGToDAGISel::matchAddress(SDValue N, X86ISelAddressMode &AM) { 1889 if (matchAddressRecursively(N, AM, 0)) 1890 return true; 1891 1892 // Post-processing: Make a second attempt to fold a load, if we now know 1893 // that there will not be any other register. This is only performed for 1894 // 64-bit ILP32 mode since 32-bit mode and 64-bit LP64 mode will have folded 1895 // any foldable load the first time. 1896 if (Subtarget->isTarget64BitILP32() && 1897 AM.BaseType == X86ISelAddressMode::RegBase && 1898 AM.Base_Reg.getNode() != nullptr && AM.IndexReg.getNode() == nullptr) { 1899 SDValue Save_Base_Reg = AM.Base_Reg; 1900 if (auto *LoadN = dyn_cast<LoadSDNode>(Save_Base_Reg)) { 1901 AM.Base_Reg = SDValue(); 1902 if (matchLoadInAddress(LoadN, AM, /*AllowSegmentRegForX32=*/true)) 1903 AM.Base_Reg = Save_Base_Reg; 1904 } 1905 } 1906 1907 // Post-processing: Convert lea(,%reg,2) to lea(%reg,%reg), which has 1908 // a smaller encoding and avoids a scaled-index. 1909 if (AM.Scale == 2 && 1910 AM.BaseType == X86ISelAddressMode::RegBase && 1911 AM.Base_Reg.getNode() == nullptr) { 1912 AM.Base_Reg = AM.IndexReg; 1913 AM.Scale = 1; 1914 } 1915 1916 // Post-processing: Convert foo to foo(%rip), even in non-PIC mode, 1917 // because it has a smaller encoding. 1918 if (TM.getCodeModel() != CodeModel::Large && 1919 (!AM.GV || !TM.isLargeGlobalValue(AM.GV)) && Subtarget->is64Bit() && 1920 AM.Scale == 1 && AM.BaseType == X86ISelAddressMode::RegBase && 1921 AM.Base_Reg.getNode() == nullptr && AM.IndexReg.getNode() == nullptr && 1922 AM.SymbolFlags == X86II::MO_NO_FLAG && AM.hasSymbolicDisplacement()) { 1923 AM.Base_Reg = CurDAG->getRegister(X86::RIP, MVT::i64); 1924 } 1925 1926 return false; 1927 } 1928 1929 bool X86DAGToDAGISel::matchAdd(SDValue &N, X86ISelAddressMode &AM, 1930 unsigned Depth) { 1931 // Add an artificial use to this node so that we can keep track of 1932 // it if it gets CSE'd with a different node. 1933 HandleSDNode Handle(N); 1934 1935 X86ISelAddressMode Backup = AM; 1936 if (!matchAddressRecursively(N.getOperand(0), AM, Depth+1) && 1937 !matchAddressRecursively(Handle.getValue().getOperand(1), AM, Depth+1)) 1938 return false; 1939 AM = Backup; 1940 1941 // Try again after commutating the operands. 1942 if (!matchAddressRecursively(Handle.getValue().getOperand(1), AM, 1943 Depth + 1) && 1944 !matchAddressRecursively(Handle.getValue().getOperand(0), AM, Depth + 1)) 1945 return false; 1946 AM = Backup; 1947 1948 // If we couldn't fold both operands into the address at the same time, 1949 // see if we can just put each operand into a register and fold at least 1950 // the add. 1951 if (AM.BaseType == X86ISelAddressMode::RegBase && 1952 !AM.Base_Reg.getNode() && 1953 !AM.IndexReg.getNode()) { 1954 N = Handle.getValue(); 1955 AM.Base_Reg = N.getOperand(0); 1956 AM.IndexReg = N.getOperand(1); 1957 AM.Scale = 1; 1958 return false; 1959 } 1960 N = Handle.getValue(); 1961 return true; 1962 } 1963 1964 // Insert a node into the DAG at least before the Pos node's position. This 1965 // will reposition the node as needed, and will assign it a node ID that is <= 1966 // the Pos node's ID. Note that this does *not* preserve the uniqueness of node 1967 // IDs! The selection DAG must no longer depend on their uniqueness when this 1968 // is used. 1969 static void insertDAGNode(SelectionDAG &DAG, SDValue Pos, SDValue N) { 1970 if (N->getNodeId() == -1 || 1971 (SelectionDAGISel::getUninvalidatedNodeId(N.getNode()) > 1972 SelectionDAGISel::getUninvalidatedNodeId(Pos.getNode()))) { 1973 DAG.RepositionNode(Pos->getIterator(), N.getNode()); 1974 // Mark Node as invalid for pruning as after this it may be a successor to a 1975 // selected node but otherwise be in the same position of Pos. 1976 // Conservatively mark it with the same -abs(Id) to assure node id 1977 // invariant is preserved. 1978 N->setNodeId(Pos->getNodeId()); 1979 SelectionDAGISel::InvalidateNodeId(N.getNode()); 1980 } 1981 } 1982 1983 // Transform "(X >> (8-C1)) & (0xff << C1)" to "((X >> 8) & 0xff) << C1" if 1984 // safe. This allows us to convert the shift and and into an h-register 1985 // extract and a scaled index. Returns false if the simplification is 1986 // performed. 1987 static bool foldMaskAndShiftToExtract(SelectionDAG &DAG, SDValue N, 1988 uint64_t Mask, 1989 SDValue Shift, SDValue X, 1990 X86ISelAddressMode &AM) { 1991 if (Shift.getOpcode() != ISD::SRL || 1992 !isa<ConstantSDNode>(Shift.getOperand(1)) || 1993 !Shift.hasOneUse()) 1994 return true; 1995 1996 int ScaleLog = 8 - Shift.getConstantOperandVal(1); 1997 if (ScaleLog <= 0 || ScaleLog >= 4 || 1998 Mask != (0xffu << ScaleLog)) 1999 return true; 2000 2001 MVT XVT = X.getSimpleValueType(); 2002 MVT VT = N.getSimpleValueType(); 2003 SDLoc DL(N); 2004 SDValue Eight = DAG.getConstant(8, DL, MVT::i8); 2005 SDValue NewMask = DAG.getConstant(0xff, DL, XVT); 2006 SDValue Srl = DAG.getNode(ISD::SRL, DL, XVT, X, Eight); 2007 SDValue And = DAG.getNode(ISD::AND, DL, XVT, Srl, NewMask); 2008 SDValue Ext = DAG.getZExtOrTrunc(And, DL, VT); 2009 SDValue ShlCount = DAG.getConstant(ScaleLog, DL, MVT::i8); 2010 SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, Ext, ShlCount); 2011 2012 // Insert the new nodes into the topological ordering. We must do this in 2013 // a valid topological ordering as nothing is going to go back and re-sort 2014 // these nodes. We continually insert before 'N' in sequence as this is 2015 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no 2016 // hierarchy left to express. 2017 insertDAGNode(DAG, N, Eight); 2018 insertDAGNode(DAG, N, NewMask); 2019 insertDAGNode(DAG, N, Srl); 2020 insertDAGNode(DAG, N, And); 2021 insertDAGNode(DAG, N, Ext); 2022 insertDAGNode(DAG, N, ShlCount); 2023 insertDAGNode(DAG, N, Shl); 2024 DAG.ReplaceAllUsesWith(N, Shl); 2025 DAG.RemoveDeadNode(N.getNode()); 2026 AM.IndexReg = Ext; 2027 AM.Scale = (1 << ScaleLog); 2028 return false; 2029 } 2030 2031 // Transforms "(X << C1) & C2" to "(X & (C2>>C1)) << C1" if safe and if this 2032 // allows us to fold the shift into this addressing mode. Returns false if the 2033 // transform succeeded. 2034 static bool foldMaskedShiftToScaledMask(SelectionDAG &DAG, SDValue N, 2035 X86ISelAddressMode &AM) { 2036 SDValue Shift = N.getOperand(0); 2037 2038 // Use a signed mask so that shifting right will insert sign bits. These 2039 // bits will be removed when we shift the result left so it doesn't matter 2040 // what we use. This might allow a smaller immediate encoding. 2041 int64_t Mask = cast<ConstantSDNode>(N->getOperand(1))->getSExtValue(); 2042 2043 // If we have an any_extend feeding the AND, look through it to see if there 2044 // is a shift behind it. But only if the AND doesn't use the extended bits. 2045 // FIXME: Generalize this to other ANY_EXTEND than i32 to i64? 2046 bool FoundAnyExtend = false; 2047 if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() && 2048 Shift.getOperand(0).getSimpleValueType() == MVT::i32 && 2049 isUInt<32>(Mask)) { 2050 FoundAnyExtend = true; 2051 Shift = Shift.getOperand(0); 2052 } 2053 2054 if (Shift.getOpcode() != ISD::SHL || 2055 !isa<ConstantSDNode>(Shift.getOperand(1))) 2056 return true; 2057 2058 SDValue X = Shift.getOperand(0); 2059 2060 // Not likely to be profitable if either the AND or SHIFT node has more 2061 // than one use (unless all uses are for address computation). Besides, 2062 // isel mechanism requires their node ids to be reused. 2063 if (!N.hasOneUse() || !Shift.hasOneUse()) 2064 return true; 2065 2066 // Verify that the shift amount is something we can fold. 2067 unsigned ShiftAmt = Shift.getConstantOperandVal(1); 2068 if (ShiftAmt != 1 && ShiftAmt != 2 && ShiftAmt != 3) 2069 return true; 2070 2071 MVT VT = N.getSimpleValueType(); 2072 SDLoc DL(N); 2073 if (FoundAnyExtend) { 2074 SDValue NewX = DAG.getNode(ISD::ANY_EXTEND, DL, VT, X); 2075 insertDAGNode(DAG, N, NewX); 2076 X = NewX; 2077 } 2078 2079 SDValue NewMask = DAG.getConstant(Mask >> ShiftAmt, DL, VT); 2080 SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, NewMask); 2081 SDValue NewShift = DAG.getNode(ISD::SHL, DL, VT, NewAnd, Shift.getOperand(1)); 2082 2083 // Insert the new nodes into the topological ordering. We must do this in 2084 // a valid topological ordering as nothing is going to go back and re-sort 2085 // these nodes. We continually insert before 'N' in sequence as this is 2086 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no 2087 // hierarchy left to express. 2088 insertDAGNode(DAG, N, NewMask); 2089 insertDAGNode(DAG, N, NewAnd); 2090 insertDAGNode(DAG, N, NewShift); 2091 DAG.ReplaceAllUsesWith(N, NewShift); 2092 DAG.RemoveDeadNode(N.getNode()); 2093 2094 AM.Scale = 1 << ShiftAmt; 2095 AM.IndexReg = NewAnd; 2096 return false; 2097 } 2098 2099 // Implement some heroics to detect shifts of masked values where the mask can 2100 // be replaced by extending the shift and undoing that in the addressing mode 2101 // scale. Patterns such as (shl (srl x, c1), c2) are canonicalized into (and 2102 // (srl x, SHIFT), MASK) by DAGCombines that don't know the shl can be done in 2103 // the addressing mode. This results in code such as: 2104 // 2105 // int f(short *y, int *lookup_table) { 2106 // ... 2107 // return *y + lookup_table[*y >> 11]; 2108 // } 2109 // 2110 // Turning into: 2111 // movzwl (%rdi), %eax 2112 // movl %eax, %ecx 2113 // shrl $11, %ecx 2114 // addl (%rsi,%rcx,4), %eax 2115 // 2116 // Instead of: 2117 // movzwl (%rdi), %eax 2118 // movl %eax, %ecx 2119 // shrl $9, %ecx 2120 // andl $124, %rcx 2121 // addl (%rsi,%rcx), %eax 2122 // 2123 // Note that this function assumes the mask is provided as a mask *after* the 2124 // value is shifted. The input chain may or may not match that, but computing 2125 // such a mask is trivial. 2126 static bool foldMaskAndShiftToScale(SelectionDAG &DAG, SDValue N, 2127 uint64_t Mask, 2128 SDValue Shift, SDValue X, 2129 X86ISelAddressMode &AM) { 2130 if (Shift.getOpcode() != ISD::SRL || !Shift.hasOneUse() || 2131 !isa<ConstantSDNode>(Shift.getOperand(1))) 2132 return true; 2133 2134 // We need to ensure that mask is a continuous run of bits. 2135 unsigned MaskIdx, MaskLen; 2136 if (!isShiftedMask_64(Mask, MaskIdx, MaskLen)) 2137 return true; 2138 unsigned MaskLZ = 64 - (MaskIdx + MaskLen); 2139 2140 unsigned ShiftAmt = Shift.getConstantOperandVal(1); 2141 2142 // The amount of shift we're trying to fit into the addressing mode is taken 2143 // from the shifted mask index (number of trailing zeros of the mask). 2144 unsigned AMShiftAmt = MaskIdx; 2145 2146 // There is nothing we can do here unless the mask is removing some bits. 2147 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits. 2148 if (AMShiftAmt == 0 || AMShiftAmt > 3) return true; 2149 2150 // Scale the leading zero count down based on the actual size of the value. 2151 // Also scale it down based on the size of the shift. 2152 unsigned ScaleDown = (64 - X.getSimpleValueType().getSizeInBits()) + ShiftAmt; 2153 if (MaskLZ < ScaleDown) 2154 return true; 2155 MaskLZ -= ScaleDown; 2156 2157 // The final check is to ensure that any masked out high bits of X are 2158 // already known to be zero. Otherwise, the mask has a semantic impact 2159 // other than masking out a couple of low bits. Unfortunately, because of 2160 // the mask, zero extensions will be removed from operands in some cases. 2161 // This code works extra hard to look through extensions because we can 2162 // replace them with zero extensions cheaply if necessary. 2163 bool ReplacingAnyExtend = false; 2164 if (X.getOpcode() == ISD::ANY_EXTEND) { 2165 unsigned ExtendBits = X.getSimpleValueType().getSizeInBits() - 2166 X.getOperand(0).getSimpleValueType().getSizeInBits(); 2167 // Assume that we'll replace the any-extend with a zero-extend, and 2168 // narrow the search to the extended value. 2169 X = X.getOperand(0); 2170 MaskLZ = ExtendBits > MaskLZ ? 0 : MaskLZ - ExtendBits; 2171 ReplacingAnyExtend = true; 2172 } 2173 APInt MaskedHighBits = 2174 APInt::getHighBitsSet(X.getSimpleValueType().getSizeInBits(), MaskLZ); 2175 if (!DAG.MaskedValueIsZero(X, MaskedHighBits)) 2176 return true; 2177 2178 // We've identified a pattern that can be transformed into a single shift 2179 // and an addressing mode. Make it so. 2180 MVT VT = N.getSimpleValueType(); 2181 if (ReplacingAnyExtend) { 2182 assert(X.getValueType() != VT); 2183 // We looked through an ANY_EXTEND node, insert a ZERO_EXTEND. 2184 SDValue NewX = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(X), VT, X); 2185 insertDAGNode(DAG, N, NewX); 2186 X = NewX; 2187 } 2188 2189 MVT XVT = X.getSimpleValueType(); 2190 SDLoc DL(N); 2191 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8); 2192 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, XVT, X, NewSRLAmt); 2193 SDValue NewExt = DAG.getZExtOrTrunc(NewSRL, DL, VT); 2194 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8); 2195 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewExt, NewSHLAmt); 2196 2197 // Insert the new nodes into the topological ordering. We must do this in 2198 // a valid topological ordering as nothing is going to go back and re-sort 2199 // these nodes. We continually insert before 'N' in sequence as this is 2200 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no 2201 // hierarchy left to express. 2202 insertDAGNode(DAG, N, NewSRLAmt); 2203 insertDAGNode(DAG, N, NewSRL); 2204 insertDAGNode(DAG, N, NewExt); 2205 insertDAGNode(DAG, N, NewSHLAmt); 2206 insertDAGNode(DAG, N, NewSHL); 2207 DAG.ReplaceAllUsesWith(N, NewSHL); 2208 DAG.RemoveDeadNode(N.getNode()); 2209 2210 AM.Scale = 1 << AMShiftAmt; 2211 AM.IndexReg = NewExt; 2212 return false; 2213 } 2214 2215 // Transform "(X >> SHIFT) & (MASK << C1)" to 2216 // "((X >> (SHIFT + C1)) & (MASK)) << C1". Everything before the SHL will be 2217 // matched to a BEXTR later. Returns false if the simplification is performed. 2218 static bool foldMaskedShiftToBEXTR(SelectionDAG &DAG, SDValue N, 2219 uint64_t Mask, 2220 SDValue Shift, SDValue X, 2221 X86ISelAddressMode &AM, 2222 const X86Subtarget &Subtarget) { 2223 if (Shift.getOpcode() != ISD::SRL || 2224 !isa<ConstantSDNode>(Shift.getOperand(1)) || 2225 !Shift.hasOneUse() || !N.hasOneUse()) 2226 return true; 2227 2228 // Only do this if BEXTR will be matched by matchBEXTRFromAndImm. 2229 if (!Subtarget.hasTBM() && 2230 !(Subtarget.hasBMI() && Subtarget.hasFastBEXTR())) 2231 return true; 2232 2233 // We need to ensure that mask is a continuous run of bits. 2234 unsigned MaskIdx, MaskLen; 2235 if (!isShiftedMask_64(Mask, MaskIdx, MaskLen)) 2236 return true; 2237 2238 unsigned ShiftAmt = Shift.getConstantOperandVal(1); 2239 2240 // The amount of shift we're trying to fit into the addressing mode is taken 2241 // from the shifted mask index (number of trailing zeros of the mask). 2242 unsigned AMShiftAmt = MaskIdx; 2243 2244 // There is nothing we can do here unless the mask is removing some bits. 2245 // Also, the addressing mode can only represent shifts of 1, 2, or 3 bits. 2246 if (AMShiftAmt == 0 || AMShiftAmt > 3) return true; 2247 2248 MVT XVT = X.getSimpleValueType(); 2249 MVT VT = N.getSimpleValueType(); 2250 SDLoc DL(N); 2251 SDValue NewSRLAmt = DAG.getConstant(ShiftAmt + AMShiftAmt, DL, MVT::i8); 2252 SDValue NewSRL = DAG.getNode(ISD::SRL, DL, XVT, X, NewSRLAmt); 2253 SDValue NewMask = DAG.getConstant(Mask >> AMShiftAmt, DL, XVT); 2254 SDValue NewAnd = DAG.getNode(ISD::AND, DL, XVT, NewSRL, NewMask); 2255 SDValue NewExt = DAG.getZExtOrTrunc(NewAnd, DL, VT); 2256 SDValue NewSHLAmt = DAG.getConstant(AMShiftAmt, DL, MVT::i8); 2257 SDValue NewSHL = DAG.getNode(ISD::SHL, DL, VT, NewExt, NewSHLAmt); 2258 2259 // Insert the new nodes into the topological ordering. We must do this in 2260 // a valid topological ordering as nothing is going to go back and re-sort 2261 // these nodes. We continually insert before 'N' in sequence as this is 2262 // essentially a pre-flattened and pre-sorted sequence of nodes. There is no 2263 // hierarchy left to express. 2264 insertDAGNode(DAG, N, NewSRLAmt); 2265 insertDAGNode(DAG, N, NewSRL); 2266 insertDAGNode(DAG, N, NewMask); 2267 insertDAGNode(DAG, N, NewAnd); 2268 insertDAGNode(DAG, N, NewExt); 2269 insertDAGNode(DAG, N, NewSHLAmt); 2270 insertDAGNode(DAG, N, NewSHL); 2271 DAG.ReplaceAllUsesWith(N, NewSHL); 2272 DAG.RemoveDeadNode(N.getNode()); 2273 2274 AM.Scale = 1 << AMShiftAmt; 2275 AM.IndexReg = NewExt; 2276 return false; 2277 } 2278 2279 // Attempt to peek further into a scaled index register, collecting additional 2280 // extensions / offsets / etc. Returns /p N if we can't peek any further. 2281 SDValue X86DAGToDAGISel::matchIndexRecursively(SDValue N, 2282 X86ISelAddressMode &AM, 2283 unsigned Depth) { 2284 assert(AM.IndexReg.getNode() == nullptr && "IndexReg already matched"); 2285 assert((AM.Scale == 1 || AM.Scale == 2 || AM.Scale == 4 || AM.Scale == 8) && 2286 "Illegal index scale"); 2287 2288 // Limit recursion. 2289 if (Depth >= SelectionDAG::MaxRecursionDepth) 2290 return N; 2291 2292 EVT VT = N.getValueType(); 2293 unsigned Opc = N.getOpcode(); 2294 2295 // index: add(x,c) -> index: x, disp + c 2296 if (CurDAG->isBaseWithConstantOffset(N)) { 2297 auto *AddVal = cast<ConstantSDNode>(N.getOperand(1)); 2298 uint64_t Offset = (uint64_t)AddVal->getSExtValue() * AM.Scale; 2299 if (!foldOffsetIntoAddress(Offset, AM)) 2300 return matchIndexRecursively(N.getOperand(0), AM, Depth + 1); 2301 } 2302 2303 // index: add(x,x) -> index: x, scale * 2 2304 if (Opc == ISD::ADD && N.getOperand(0) == N.getOperand(1)) { 2305 if (AM.Scale <= 4) { 2306 AM.Scale *= 2; 2307 return matchIndexRecursively(N.getOperand(0), AM, Depth + 1); 2308 } 2309 } 2310 2311 // index: shl(x,i) -> index: x, scale * (1 << i) 2312 if (Opc == X86ISD::VSHLI) { 2313 uint64_t ShiftAmt = N.getConstantOperandVal(1); 2314 uint64_t ScaleAmt = 1ULL << ShiftAmt; 2315 if ((AM.Scale * ScaleAmt) <= 8) { 2316 AM.Scale *= ScaleAmt; 2317 return matchIndexRecursively(N.getOperand(0), AM, Depth + 1); 2318 } 2319 } 2320 2321 // index: sext(add_nsw(x,c)) -> index: sext(x), disp + sext(c) 2322 // TODO: call matchIndexRecursively(AddSrc) if we won't corrupt sext? 2323 if (Opc == ISD::SIGN_EXTEND && !VT.isVector() && N.hasOneUse()) { 2324 SDValue Src = N.getOperand(0); 2325 if (Src.getOpcode() == ISD::ADD && Src->getFlags().hasNoSignedWrap() && 2326 Src.hasOneUse()) { 2327 if (CurDAG->isBaseWithConstantOffset(Src)) { 2328 SDValue AddSrc = Src.getOperand(0); 2329 auto *AddVal = cast<ConstantSDNode>(Src.getOperand(1)); 2330 uint64_t Offset = (uint64_t)AddVal->getSExtValue(); 2331 if (!foldOffsetIntoAddress(Offset * AM.Scale, AM)) { 2332 SDLoc DL(N); 2333 SDValue ExtSrc = CurDAG->getNode(Opc, DL, VT, AddSrc); 2334 SDValue ExtVal = CurDAG->getConstant(Offset, DL, VT); 2335 SDValue ExtAdd = CurDAG->getNode(ISD::ADD, DL, VT, ExtSrc, ExtVal); 2336 insertDAGNode(*CurDAG, N, ExtSrc); 2337 insertDAGNode(*CurDAG, N, ExtVal); 2338 insertDAGNode(*CurDAG, N, ExtAdd); 2339 CurDAG->ReplaceAllUsesWith(N, ExtAdd); 2340 CurDAG->RemoveDeadNode(N.getNode()); 2341 return ExtSrc; 2342 } 2343 } 2344 } 2345 } 2346 2347 // index: zext(add_nuw(x,c)) -> index: zext(x), disp + zext(c) 2348 // index: zext(addlike(x,c)) -> index: zext(x), disp + zext(c) 2349 // TODO: call matchIndexRecursively(AddSrc) if we won't corrupt sext? 2350 if (Opc == ISD::ZERO_EXTEND && !VT.isVector() && N.hasOneUse()) { 2351 SDValue Src = N.getOperand(0); 2352 unsigned SrcOpc = Src.getOpcode(); 2353 if (((SrcOpc == ISD::ADD && Src->getFlags().hasNoUnsignedWrap()) || 2354 CurDAG->isADDLike(Src)) && 2355 Src.hasOneUse()) { 2356 if (CurDAG->isBaseWithConstantOffset(Src)) { 2357 SDValue AddSrc = Src.getOperand(0); 2358 auto *AddVal = cast<ConstantSDNode>(Src.getOperand(1)); 2359 uint64_t Offset = (uint64_t)AddVal->getZExtValue(); 2360 if (!foldOffsetIntoAddress(Offset * AM.Scale, AM)) { 2361 SDLoc DL(N); 2362 SDValue Res; 2363 // If we're also scaling, see if we can use that as well. 2364 if (AddSrc.getOpcode() == ISD::SHL && 2365 isa<ConstantSDNode>(AddSrc.getOperand(1))) { 2366 SDValue ShVal = AddSrc.getOperand(0); 2367 uint64_t ShAmt = AddSrc.getConstantOperandVal(1); 2368 APInt HiBits = 2369 APInt::getHighBitsSet(AddSrc.getScalarValueSizeInBits(), ShAmt); 2370 uint64_t ScaleAmt = 1ULL << ShAmt; 2371 if ((AM.Scale * ScaleAmt) <= 8 && 2372 (AddSrc->getFlags().hasNoUnsignedWrap() || 2373 CurDAG->MaskedValueIsZero(ShVal, HiBits))) { 2374 AM.Scale *= ScaleAmt; 2375 SDValue ExtShVal = CurDAG->getNode(Opc, DL, VT, ShVal); 2376 SDValue ExtShift = CurDAG->getNode(ISD::SHL, DL, VT, ExtShVal, 2377 AddSrc.getOperand(1)); 2378 insertDAGNode(*CurDAG, N, ExtShVal); 2379 insertDAGNode(*CurDAG, N, ExtShift); 2380 AddSrc = ExtShift; 2381 Res = ExtShVal; 2382 } 2383 } 2384 SDValue ExtSrc = CurDAG->getNode(Opc, DL, VT, AddSrc); 2385 SDValue ExtVal = CurDAG->getConstant(Offset, DL, VT); 2386 SDValue ExtAdd = CurDAG->getNode(SrcOpc, DL, VT, ExtSrc, ExtVal); 2387 insertDAGNode(*CurDAG, N, ExtSrc); 2388 insertDAGNode(*CurDAG, N, ExtVal); 2389 insertDAGNode(*CurDAG, N, ExtAdd); 2390 CurDAG->ReplaceAllUsesWith(N, ExtAdd); 2391 CurDAG->RemoveDeadNode(N.getNode()); 2392 return Res ? Res : ExtSrc; 2393 } 2394 } 2395 } 2396 } 2397 2398 // TODO: Handle extensions, shifted masks etc. 2399 return N; 2400 } 2401 2402 bool X86DAGToDAGISel::matchAddressRecursively(SDValue N, X86ISelAddressMode &AM, 2403 unsigned Depth) { 2404 SDLoc dl(N); 2405 LLVM_DEBUG({ 2406 dbgs() << "MatchAddress: "; 2407 AM.dump(CurDAG); 2408 }); 2409 // Limit recursion. 2410 if (Depth >= SelectionDAG::MaxRecursionDepth) 2411 return matchAddressBase(N, AM); 2412 2413 // If this is already a %rip relative address, we can only merge immediates 2414 // into it. Instead of handling this in every case, we handle it here. 2415 // RIP relative addressing: %rip + 32-bit displacement! 2416 if (AM.isRIPRelative()) { 2417 // FIXME: JumpTable and ExternalSymbol address currently don't like 2418 // displacements. It isn't very important, but this should be fixed for 2419 // consistency. 2420 if (!(AM.ES || AM.MCSym) && AM.JT != -1) 2421 return true; 2422 2423 if (auto *Cst = dyn_cast<ConstantSDNode>(N)) 2424 if (!foldOffsetIntoAddress(Cst->getSExtValue(), AM)) 2425 return false; 2426 return true; 2427 } 2428 2429 switch (N.getOpcode()) { 2430 default: break; 2431 case ISD::LOCAL_RECOVER: { 2432 if (!AM.hasSymbolicDisplacement() && AM.Disp == 0) 2433 if (const auto *ESNode = dyn_cast<MCSymbolSDNode>(N.getOperand(0))) { 2434 // Use the symbol and don't prefix it. 2435 AM.MCSym = ESNode->getMCSymbol(); 2436 return false; 2437 } 2438 break; 2439 } 2440 case ISD::Constant: { 2441 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue(); 2442 if (!foldOffsetIntoAddress(Val, AM)) 2443 return false; 2444 break; 2445 } 2446 2447 case X86ISD::Wrapper: 2448 case X86ISD::WrapperRIP: 2449 if (!matchWrapper(N, AM)) 2450 return false; 2451 break; 2452 2453 case ISD::LOAD: 2454 if (!matchLoadInAddress(cast<LoadSDNode>(N), AM)) 2455 return false; 2456 break; 2457 2458 case ISD::FrameIndex: 2459 if (AM.BaseType == X86ISelAddressMode::RegBase && 2460 AM.Base_Reg.getNode() == nullptr && 2461 (!Subtarget->is64Bit() || isDispSafeForFrameIndex(AM.Disp))) { 2462 AM.BaseType = X86ISelAddressMode::FrameIndexBase; 2463 AM.Base_FrameIndex = cast<FrameIndexSDNode>(N)->getIndex(); 2464 return false; 2465 } 2466 break; 2467 2468 case ISD::SHL: 2469 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) 2470 break; 2471 2472 if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) { 2473 unsigned Val = CN->getZExtValue(); 2474 // Note that we handle x<<1 as (,x,2) rather than (x,x) here so 2475 // that the base operand remains free for further matching. If 2476 // the base doesn't end up getting used, a post-processing step 2477 // in MatchAddress turns (,x,2) into (x,x), which is cheaper. 2478 if (Val == 1 || Val == 2 || Val == 3) { 2479 SDValue ShVal = N.getOperand(0); 2480 AM.Scale = 1 << Val; 2481 AM.IndexReg = matchIndexRecursively(ShVal, AM, Depth + 1); 2482 return false; 2483 } 2484 } 2485 break; 2486 2487 case ISD::SRL: { 2488 // Scale must not be used already. 2489 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break; 2490 2491 // We only handle up to 64-bit values here as those are what matter for 2492 // addressing mode optimizations. 2493 assert(N.getSimpleValueType().getSizeInBits() <= 64 && 2494 "Unexpected value size!"); 2495 2496 SDValue And = N.getOperand(0); 2497 if (And.getOpcode() != ISD::AND) break; 2498 SDValue X = And.getOperand(0); 2499 2500 // The mask used for the transform is expected to be post-shift, but we 2501 // found the shift first so just apply the shift to the mask before passing 2502 // it down. 2503 if (!isa<ConstantSDNode>(N.getOperand(1)) || 2504 !isa<ConstantSDNode>(And.getOperand(1))) 2505 break; 2506 uint64_t Mask = And.getConstantOperandVal(1) >> N.getConstantOperandVal(1); 2507 2508 // Try to fold the mask and shift into the scale, and return false if we 2509 // succeed. 2510 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, N, X, AM)) 2511 return false; 2512 break; 2513 } 2514 2515 case ISD::SMUL_LOHI: 2516 case ISD::UMUL_LOHI: 2517 // A mul_lohi where we need the low part can be folded as a plain multiply. 2518 if (N.getResNo() != 0) break; 2519 [[fallthrough]]; 2520 case ISD::MUL: 2521 case X86ISD::MUL_IMM: 2522 // X*[3,5,9] -> X+X*[2,4,8] 2523 if (AM.BaseType == X86ISelAddressMode::RegBase && 2524 AM.Base_Reg.getNode() == nullptr && 2525 AM.IndexReg.getNode() == nullptr) { 2526 if (auto *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) 2527 if (CN->getZExtValue() == 3 || CN->getZExtValue() == 5 || 2528 CN->getZExtValue() == 9) { 2529 AM.Scale = unsigned(CN->getZExtValue())-1; 2530 2531 SDValue MulVal = N.getOperand(0); 2532 SDValue Reg; 2533 2534 // Okay, we know that we have a scale by now. However, if the scaled 2535 // value is an add of something and a constant, we can fold the 2536 // constant into the disp field here. 2537 if (MulVal.getNode()->getOpcode() == ISD::ADD && MulVal.hasOneUse() && 2538 isa<ConstantSDNode>(MulVal.getOperand(1))) { 2539 Reg = MulVal.getOperand(0); 2540 auto *AddVal = cast<ConstantSDNode>(MulVal.getOperand(1)); 2541 uint64_t Disp = AddVal->getSExtValue() * CN->getZExtValue(); 2542 if (foldOffsetIntoAddress(Disp, AM)) 2543 Reg = N.getOperand(0); 2544 } else { 2545 Reg = N.getOperand(0); 2546 } 2547 2548 AM.IndexReg = AM.Base_Reg = Reg; 2549 return false; 2550 } 2551 } 2552 break; 2553 2554 case ISD::SUB: { 2555 // Given A-B, if A can be completely folded into the address and 2556 // the index field with the index field unused, use -B as the index. 2557 // This is a win if a has multiple parts that can be folded into 2558 // the address. Also, this saves a mov if the base register has 2559 // other uses, since it avoids a two-address sub instruction, however 2560 // it costs an additional mov if the index register has other uses. 2561 2562 // Add an artificial use to this node so that we can keep track of 2563 // it if it gets CSE'd with a different node. 2564 HandleSDNode Handle(N); 2565 2566 // Test if the LHS of the sub can be folded. 2567 X86ISelAddressMode Backup = AM; 2568 if (matchAddressRecursively(N.getOperand(0), AM, Depth+1)) { 2569 N = Handle.getValue(); 2570 AM = Backup; 2571 break; 2572 } 2573 N = Handle.getValue(); 2574 // Test if the index field is free for use. 2575 if (AM.IndexReg.getNode() || AM.isRIPRelative()) { 2576 AM = Backup; 2577 break; 2578 } 2579 2580 int Cost = 0; 2581 SDValue RHS = N.getOperand(1); 2582 // If the RHS involves a register with multiple uses, this 2583 // transformation incurs an extra mov, due to the neg instruction 2584 // clobbering its operand. 2585 if (!RHS.getNode()->hasOneUse() || 2586 RHS.getNode()->getOpcode() == ISD::CopyFromReg || 2587 RHS.getNode()->getOpcode() == ISD::TRUNCATE || 2588 RHS.getNode()->getOpcode() == ISD::ANY_EXTEND || 2589 (RHS.getNode()->getOpcode() == ISD::ZERO_EXTEND && 2590 RHS.getOperand(0).getValueType() == MVT::i32)) 2591 ++Cost; 2592 // If the base is a register with multiple uses, this 2593 // transformation may save a mov. 2594 if ((AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode() && 2595 !AM.Base_Reg.getNode()->hasOneUse()) || 2596 AM.BaseType == X86ISelAddressMode::FrameIndexBase) 2597 --Cost; 2598 // If the folded LHS was interesting, this transformation saves 2599 // address arithmetic. 2600 if ((AM.hasSymbolicDisplacement() && !Backup.hasSymbolicDisplacement()) + 2601 ((AM.Disp != 0) && (Backup.Disp == 0)) + 2602 (AM.Segment.getNode() && !Backup.Segment.getNode()) >= 2) 2603 --Cost; 2604 // If it doesn't look like it may be an overall win, don't do it. 2605 if (Cost >= 0) { 2606 AM = Backup; 2607 break; 2608 } 2609 2610 // Ok, the transformation is legal and appears profitable. Go for it. 2611 // Negation will be emitted later to avoid creating dangling nodes if this 2612 // was an unprofitable LEA. 2613 AM.IndexReg = RHS; 2614 AM.NegateIndex = true; 2615 AM.Scale = 1; 2616 return false; 2617 } 2618 2619 case ISD::OR: 2620 case ISD::XOR: 2621 // See if we can treat the OR/XOR node as an ADD node. 2622 if (!CurDAG->isADDLike(N)) 2623 break; 2624 [[fallthrough]]; 2625 case ISD::ADD: 2626 if (!matchAdd(N, AM, Depth)) 2627 return false; 2628 break; 2629 2630 case ISD::AND: { 2631 // Perform some heroic transforms on an and of a constant-count shift 2632 // with a constant to enable use of the scaled offset field. 2633 2634 // Scale must not be used already. 2635 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) break; 2636 2637 // We only handle up to 64-bit values here as those are what matter for 2638 // addressing mode optimizations. 2639 assert(N.getSimpleValueType().getSizeInBits() <= 64 && 2640 "Unexpected value size!"); 2641 2642 if (!isa<ConstantSDNode>(N.getOperand(1))) 2643 break; 2644 2645 if (N.getOperand(0).getOpcode() == ISD::SRL) { 2646 SDValue Shift = N.getOperand(0); 2647 SDValue X = Shift.getOperand(0); 2648 2649 uint64_t Mask = N.getConstantOperandVal(1); 2650 2651 // Try to fold the mask and shift into an extract and scale. 2652 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask, Shift, X, AM)) 2653 return false; 2654 2655 // Try to fold the mask and shift directly into the scale. 2656 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask, Shift, X, AM)) 2657 return false; 2658 2659 // Try to fold the mask and shift into BEXTR and scale. 2660 if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask, Shift, X, AM, *Subtarget)) 2661 return false; 2662 } 2663 2664 // Try to swap the mask and shift to place shifts which can be done as 2665 // a scale on the outside of the mask. 2666 if (!foldMaskedShiftToScaledMask(*CurDAG, N, AM)) 2667 return false; 2668 2669 break; 2670 } 2671 case ISD::ZERO_EXTEND: { 2672 // Try to widen a zexted shift left to the same size as its use, so we can 2673 // match the shift as a scale factor. 2674 if (AM.IndexReg.getNode() != nullptr || AM.Scale != 1) 2675 break; 2676 2677 SDValue Src = N.getOperand(0); 2678 2679 // See if we can match a zext(addlike(x,c)). 2680 // TODO: Move more ZERO_EXTEND patterns into matchIndexRecursively. 2681 if (Src.getOpcode() == ISD::ADD || Src.getOpcode() == ISD::OR) 2682 if (SDValue Index = matchIndexRecursively(N, AM, Depth + 1)) 2683 if (Index != N) { 2684 AM.IndexReg = Index; 2685 return false; 2686 } 2687 2688 // Peek through mask: zext(and(shl(x,c1),c2)) 2689 APInt Mask = APInt::getAllOnes(Src.getScalarValueSizeInBits()); 2690 if (Src.getOpcode() == ISD::AND && Src.hasOneUse()) 2691 if (auto *MaskC = dyn_cast<ConstantSDNode>(Src.getOperand(1))) { 2692 Mask = MaskC->getAPIntValue(); 2693 Src = Src.getOperand(0); 2694 } 2695 2696 if (Src.getOpcode() == ISD::SHL && Src.hasOneUse()) { 2697 // Give up if the shift is not a valid scale factor [1,2,3]. 2698 SDValue ShlSrc = Src.getOperand(0); 2699 SDValue ShlAmt = Src.getOperand(1); 2700 auto *ShAmtC = dyn_cast<ConstantSDNode>(ShlAmt); 2701 if (!ShAmtC) 2702 break; 2703 unsigned ShAmtV = ShAmtC->getZExtValue(); 2704 if (ShAmtV > 3) 2705 break; 2706 2707 // The narrow shift must only shift out zero bits (it must be 'nuw'). 2708 // That makes it safe to widen to the destination type. 2709 APInt HighZeros = 2710 APInt::getHighBitsSet(ShlSrc.getValueSizeInBits(), ShAmtV); 2711 if (!Src->getFlags().hasNoUnsignedWrap() && 2712 !CurDAG->MaskedValueIsZero(ShlSrc, HighZeros & Mask)) 2713 break; 2714 2715 // zext (shl nuw i8 %x, C1) to i32 2716 // --> shl (zext i8 %x to i32), (zext C1) 2717 // zext (and (shl nuw i8 %x, C1), C2) to i32 2718 // --> shl (zext i8 (and %x, C2 >> C1) to i32), (zext C1) 2719 MVT SrcVT = ShlSrc.getSimpleValueType(); 2720 MVT VT = N.getSimpleValueType(); 2721 SDLoc DL(N); 2722 2723 SDValue Res = ShlSrc; 2724 if (!Mask.isAllOnes()) { 2725 Res = CurDAG->getConstant(Mask.lshr(ShAmtV), DL, SrcVT); 2726 insertDAGNode(*CurDAG, N, Res); 2727 Res = CurDAG->getNode(ISD::AND, DL, SrcVT, ShlSrc, Res); 2728 insertDAGNode(*CurDAG, N, Res); 2729 } 2730 SDValue Zext = CurDAG->getNode(ISD::ZERO_EXTEND, DL, VT, Res); 2731 insertDAGNode(*CurDAG, N, Zext); 2732 SDValue NewShl = CurDAG->getNode(ISD::SHL, DL, VT, Zext, ShlAmt); 2733 insertDAGNode(*CurDAG, N, NewShl); 2734 2735 // Convert the shift to scale factor. 2736 AM.Scale = 1 << ShAmtV; 2737 AM.IndexReg = Zext; 2738 2739 CurDAG->ReplaceAllUsesWith(N, NewShl); 2740 CurDAG->RemoveDeadNode(N.getNode()); 2741 return false; 2742 } 2743 2744 if (Src.getOpcode() == ISD::SRL && !Mask.isAllOnes()) { 2745 // Try to fold the mask and shift into an extract and scale. 2746 if (!foldMaskAndShiftToExtract(*CurDAG, N, Mask.getZExtValue(), Src, 2747 Src.getOperand(0), AM)) 2748 return false; 2749 2750 // Try to fold the mask and shift directly into the scale. 2751 if (!foldMaskAndShiftToScale(*CurDAG, N, Mask.getZExtValue(), Src, 2752 Src.getOperand(0), AM)) 2753 return false; 2754 2755 // Try to fold the mask and shift into BEXTR and scale. 2756 if (!foldMaskedShiftToBEXTR(*CurDAG, N, Mask.getZExtValue(), Src, 2757 Src.getOperand(0), AM, *Subtarget)) 2758 return false; 2759 } 2760 2761 break; 2762 } 2763 } 2764 2765 return matchAddressBase(N, AM); 2766 } 2767 2768 /// Helper for MatchAddress. Add the specified node to the 2769 /// specified addressing mode without any further recursion. 2770 bool X86DAGToDAGISel::matchAddressBase(SDValue N, X86ISelAddressMode &AM) { 2771 // Is the base register already occupied? 2772 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base_Reg.getNode()) { 2773 // If so, check to see if the scale index register is set. 2774 if (!AM.IndexReg.getNode()) { 2775 AM.IndexReg = N; 2776 AM.Scale = 1; 2777 return false; 2778 } 2779 2780 // Otherwise, we cannot select it. 2781 return true; 2782 } 2783 2784 // Default, generate it as a register. 2785 AM.BaseType = X86ISelAddressMode::RegBase; 2786 AM.Base_Reg = N; 2787 return false; 2788 } 2789 2790 bool X86DAGToDAGISel::matchVectorAddressRecursively(SDValue N, 2791 X86ISelAddressMode &AM, 2792 unsigned Depth) { 2793 SDLoc dl(N); 2794 LLVM_DEBUG({ 2795 dbgs() << "MatchVectorAddress: "; 2796 AM.dump(CurDAG); 2797 }); 2798 // Limit recursion. 2799 if (Depth >= SelectionDAG::MaxRecursionDepth) 2800 return matchAddressBase(N, AM); 2801 2802 // TODO: Support other operations. 2803 switch (N.getOpcode()) { 2804 case ISD::Constant: { 2805 uint64_t Val = cast<ConstantSDNode>(N)->getSExtValue(); 2806 if (!foldOffsetIntoAddress(Val, AM)) 2807 return false; 2808 break; 2809 } 2810 case X86ISD::Wrapper: 2811 if (!matchWrapper(N, AM)) 2812 return false; 2813 break; 2814 case ISD::ADD: { 2815 // Add an artificial use to this node so that we can keep track of 2816 // it if it gets CSE'd with a different node. 2817 HandleSDNode Handle(N); 2818 2819 X86ISelAddressMode Backup = AM; 2820 if (!matchVectorAddressRecursively(N.getOperand(0), AM, Depth + 1) && 2821 !matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM, 2822 Depth + 1)) 2823 return false; 2824 AM = Backup; 2825 2826 // Try again after commuting the operands. 2827 if (!matchVectorAddressRecursively(Handle.getValue().getOperand(1), AM, 2828 Depth + 1) && 2829 !matchVectorAddressRecursively(Handle.getValue().getOperand(0), AM, 2830 Depth + 1)) 2831 return false; 2832 AM = Backup; 2833 2834 N = Handle.getValue(); 2835 break; 2836 } 2837 } 2838 2839 return matchAddressBase(N, AM); 2840 } 2841 2842 /// Helper for selectVectorAddr. Handles things that can be folded into a 2843 /// gather/scatter address. The index register and scale should have already 2844 /// been handled. 2845 bool X86DAGToDAGISel::matchVectorAddress(SDValue N, X86ISelAddressMode &AM) { 2846 return matchVectorAddressRecursively(N, AM, 0); 2847 } 2848 2849 bool X86DAGToDAGISel::selectVectorAddr(MemSDNode *Parent, SDValue BasePtr, 2850 SDValue IndexOp, SDValue ScaleOp, 2851 SDValue &Base, SDValue &Scale, 2852 SDValue &Index, SDValue &Disp, 2853 SDValue &Segment) { 2854 X86ISelAddressMode AM; 2855 AM.Scale = ScaleOp->getAsZExtVal(); 2856 2857 // Attempt to match index patterns, as long as we're not relying on implicit 2858 // sign-extension, which is performed BEFORE scale. 2859 if (IndexOp.getScalarValueSizeInBits() == BasePtr.getScalarValueSizeInBits()) 2860 AM.IndexReg = matchIndexRecursively(IndexOp, AM, 0); 2861 else 2862 AM.IndexReg = IndexOp; 2863 2864 unsigned AddrSpace = Parent->getPointerInfo().getAddrSpace(); 2865 if (AddrSpace == X86AS::GS) 2866 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16); 2867 if (AddrSpace == X86AS::FS) 2868 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16); 2869 if (AddrSpace == X86AS::SS) 2870 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16); 2871 2872 SDLoc DL(BasePtr); 2873 MVT VT = BasePtr.getSimpleValueType(); 2874 2875 // Try to match into the base and displacement fields. 2876 if (matchVectorAddress(BasePtr, AM)) 2877 return false; 2878 2879 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment); 2880 return true; 2881 } 2882 2883 /// Returns true if it is able to pattern match an addressing mode. 2884 /// It returns the operands which make up the maximal addressing mode it can 2885 /// match by reference. 2886 /// 2887 /// Parent is the parent node of the addr operand that is being matched. It 2888 /// is always a load, store, atomic node, or null. It is only null when 2889 /// checking memory operands for inline asm nodes. 2890 bool X86DAGToDAGISel::selectAddr(SDNode *Parent, SDValue N, SDValue &Base, 2891 SDValue &Scale, SDValue &Index, 2892 SDValue &Disp, SDValue &Segment) { 2893 X86ISelAddressMode AM; 2894 2895 if (Parent && 2896 // This list of opcodes are all the nodes that have an "addr:$ptr" operand 2897 // that are not a MemSDNode, and thus don't have proper addrspace info. 2898 Parent->getOpcode() != ISD::INTRINSIC_W_CHAIN && // unaligned loads, fixme 2899 Parent->getOpcode() != ISD::INTRINSIC_VOID && // nontemporal stores 2900 Parent->getOpcode() != X86ISD::TLSCALL && // Fixme 2901 Parent->getOpcode() != X86ISD::ENQCMD && // Fixme 2902 Parent->getOpcode() != X86ISD::ENQCMDS && // Fixme 2903 Parent->getOpcode() != X86ISD::EH_SJLJ_SETJMP && // setjmp 2904 Parent->getOpcode() != X86ISD::EH_SJLJ_LONGJMP) { // longjmp 2905 unsigned AddrSpace = 2906 cast<MemSDNode>(Parent)->getPointerInfo().getAddrSpace(); 2907 if (AddrSpace == X86AS::GS) 2908 AM.Segment = CurDAG->getRegister(X86::GS, MVT::i16); 2909 if (AddrSpace == X86AS::FS) 2910 AM.Segment = CurDAG->getRegister(X86::FS, MVT::i16); 2911 if (AddrSpace == X86AS::SS) 2912 AM.Segment = CurDAG->getRegister(X86::SS, MVT::i16); 2913 } 2914 2915 // Save the DL and VT before calling matchAddress, it can invalidate N. 2916 SDLoc DL(N); 2917 MVT VT = N.getSimpleValueType(); 2918 2919 if (matchAddress(N, AM)) 2920 return false; 2921 2922 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment); 2923 return true; 2924 } 2925 2926 bool X86DAGToDAGISel::selectMOV64Imm32(SDValue N, SDValue &Imm) { 2927 // Cannot use 32 bit constants to reference objects in kernel code model. 2928 // Cannot use 32 bit constants to reference objects in large PIC mode since 2929 // GOTOFF is 64 bits. 2930 if (TM.getCodeModel() == CodeModel::Kernel || 2931 (TM.getCodeModel() == CodeModel::Large && TM.isPositionIndependent())) 2932 return false; 2933 2934 // In static codegen with small code model, we can get the address of a label 2935 // into a register with 'movl' 2936 if (N->getOpcode() != X86ISD::Wrapper) 2937 return false; 2938 2939 N = N.getOperand(0); 2940 2941 // At least GNU as does not accept 'movl' for TPOFF relocations. 2942 // FIXME: We could use 'movl' when we know we are targeting MC. 2943 if (N->getOpcode() == ISD::TargetGlobalTLSAddress) 2944 return false; 2945 2946 Imm = N; 2947 // Small/medium code model can reference non-TargetGlobalAddress objects with 2948 // 32 bit constants. 2949 if (N->getOpcode() != ISD::TargetGlobalAddress) { 2950 return TM.getCodeModel() == CodeModel::Small || 2951 TM.getCodeModel() == CodeModel::Medium; 2952 } 2953 2954 const GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal(); 2955 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange()) 2956 return CR->getUnsignedMax().ult(1ull << 32); 2957 2958 return !TM.isLargeGlobalValue(GV); 2959 } 2960 2961 bool X86DAGToDAGISel::selectLEA64_32Addr(SDValue N, SDValue &Base, 2962 SDValue &Scale, SDValue &Index, 2963 SDValue &Disp, SDValue &Segment) { 2964 // Save the debug loc before calling selectLEAAddr, in case it invalidates N. 2965 SDLoc DL(N); 2966 2967 if (!selectLEAAddr(N, Base, Scale, Index, Disp, Segment)) 2968 return false; 2969 2970 auto *RN = dyn_cast<RegisterSDNode>(Base); 2971 if (RN && RN->getReg() == 0) 2972 Base = CurDAG->getRegister(0, MVT::i64); 2973 else if (Base.getValueType() == MVT::i32 && !isa<FrameIndexSDNode>(Base)) { 2974 // Base could already be %rip, particularly in the x32 ABI. 2975 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL, 2976 MVT::i64), 0); 2977 Base = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef, 2978 Base); 2979 } 2980 2981 RN = dyn_cast<RegisterSDNode>(Index); 2982 if (RN && RN->getReg() == 0) 2983 Index = CurDAG->getRegister(0, MVT::i64); 2984 else { 2985 assert(Index.getValueType() == MVT::i32 && 2986 "Expect to be extending 32-bit registers for use in LEA"); 2987 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, DL, 2988 MVT::i64), 0); 2989 Index = CurDAG->getTargetInsertSubreg(X86::sub_32bit, DL, MVT::i64, ImplDef, 2990 Index); 2991 } 2992 2993 return true; 2994 } 2995 2996 /// Calls SelectAddr and determines if the maximal addressing 2997 /// mode it matches can be cost effectively emitted as an LEA instruction. 2998 bool X86DAGToDAGISel::selectLEAAddr(SDValue N, 2999 SDValue &Base, SDValue &Scale, 3000 SDValue &Index, SDValue &Disp, 3001 SDValue &Segment) { 3002 X86ISelAddressMode AM; 3003 3004 // Save the DL and VT before calling matchAddress, it can invalidate N. 3005 SDLoc DL(N); 3006 MVT VT = N.getSimpleValueType(); 3007 3008 // Set AM.Segment to prevent MatchAddress from using one. LEA doesn't support 3009 // segments. 3010 SDValue Copy = AM.Segment; 3011 SDValue T = CurDAG->getRegister(0, MVT::i32); 3012 AM.Segment = T; 3013 if (matchAddress(N, AM)) 3014 return false; 3015 assert (T == AM.Segment); 3016 AM.Segment = Copy; 3017 3018 unsigned Complexity = 0; 3019 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base_Reg.getNode()) 3020 Complexity = 1; 3021 else if (AM.BaseType == X86ISelAddressMode::FrameIndexBase) 3022 Complexity = 4; 3023 3024 if (AM.IndexReg.getNode()) 3025 Complexity++; 3026 3027 // Don't match just leal(,%reg,2). It's cheaper to do addl %reg, %reg, or with 3028 // a simple shift. 3029 if (AM.Scale > 1) 3030 Complexity++; 3031 3032 // FIXME: We are artificially lowering the criteria to turn ADD %reg, $GA 3033 // to a LEA. This is determined with some experimentation but is by no means 3034 // optimal (especially for code size consideration). LEA is nice because of 3035 // its three-address nature. Tweak the cost function again when we can run 3036 // convertToThreeAddress() at register allocation time. 3037 if (AM.hasSymbolicDisplacement()) { 3038 // For X86-64, always use LEA to materialize RIP-relative addresses. 3039 if (Subtarget->is64Bit()) 3040 Complexity = 4; 3041 else 3042 Complexity += 2; 3043 } 3044 3045 // Heuristic: try harder to form an LEA from ADD if the operands set flags. 3046 // Unlike ADD, LEA does not affect flags, so we will be less likely to require 3047 // duplicating flag-producing instructions later in the pipeline. 3048 if (N.getOpcode() == ISD::ADD) { 3049 auto isMathWithFlags = [](SDValue V) { 3050 switch (V.getOpcode()) { 3051 case X86ISD::ADD: 3052 case X86ISD::SUB: 3053 case X86ISD::ADC: 3054 case X86ISD::SBB: 3055 case X86ISD::SMUL: 3056 case X86ISD::UMUL: 3057 /* TODO: These opcodes can be added safely, but we may want to justify 3058 their inclusion for different reasons (better for reg-alloc). 3059 case X86ISD::OR: 3060 case X86ISD::XOR: 3061 case X86ISD::AND: 3062 */ 3063 // Value 1 is the flag output of the node - verify it's not dead. 3064 return !SDValue(V.getNode(), 1).use_empty(); 3065 default: 3066 return false; 3067 } 3068 }; 3069 // TODO: We might want to factor in whether there's a load folding 3070 // opportunity for the math op that disappears with LEA. 3071 if (isMathWithFlags(N.getOperand(0)) || isMathWithFlags(N.getOperand(1))) 3072 Complexity++; 3073 } 3074 3075 if (AM.Disp) 3076 Complexity++; 3077 3078 // If it isn't worth using an LEA, reject it. 3079 if (Complexity <= 2) 3080 return false; 3081 3082 getAddressOperands(AM, DL, VT, Base, Scale, Index, Disp, Segment); 3083 return true; 3084 } 3085 3086 /// This is only run on TargetGlobalTLSAddress nodes. 3087 bool X86DAGToDAGISel::selectTLSADDRAddr(SDValue N, SDValue &Base, 3088 SDValue &Scale, SDValue &Index, 3089 SDValue &Disp, SDValue &Segment) { 3090 assert(N.getOpcode() == ISD::TargetGlobalTLSAddress); 3091 auto *GA = cast<GlobalAddressSDNode>(N); 3092 3093 X86ISelAddressMode AM; 3094 AM.GV = GA->getGlobal(); 3095 AM.Disp += GA->getOffset(); 3096 AM.SymbolFlags = GA->getTargetFlags(); 3097 3098 if (Subtarget->is32Bit()) { 3099 AM.Scale = 1; 3100 AM.IndexReg = CurDAG->getRegister(X86::EBX, MVT::i32); 3101 } 3102 3103 MVT VT = N.getSimpleValueType(); 3104 getAddressOperands(AM, SDLoc(N), VT, Base, Scale, Index, Disp, Segment); 3105 return true; 3106 } 3107 3108 bool X86DAGToDAGISel::selectRelocImm(SDValue N, SDValue &Op) { 3109 // Keep track of the original value type and whether this value was 3110 // truncated. If we see a truncation from pointer type to VT that truncates 3111 // bits that are known to be zero, we can use a narrow reference. 3112 EVT VT = N.getValueType(); 3113 bool WasTruncated = false; 3114 if (N.getOpcode() == ISD::TRUNCATE) { 3115 WasTruncated = true; 3116 N = N.getOperand(0); 3117 } 3118 3119 if (N.getOpcode() != X86ISD::Wrapper) 3120 return false; 3121 3122 // We can only use non-GlobalValues as immediates if they were not truncated, 3123 // as we do not have any range information. If we have a GlobalValue and the 3124 // address was not truncated, we can select it as an operand directly. 3125 unsigned Opc = N.getOperand(0)->getOpcode(); 3126 if (Opc != ISD::TargetGlobalAddress || !WasTruncated) { 3127 Op = N.getOperand(0); 3128 // We can only select the operand directly if we didn't have to look past a 3129 // truncate. 3130 return !WasTruncated; 3131 } 3132 3133 // Check that the global's range fits into VT. 3134 auto *GA = cast<GlobalAddressSDNode>(N.getOperand(0)); 3135 std::optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange(); 3136 if (!CR || CR->getUnsignedMax().uge(1ull << VT.getSizeInBits())) 3137 return false; 3138 3139 // Okay, we can use a narrow reference. 3140 Op = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(N), VT, 3141 GA->getOffset(), GA->getTargetFlags()); 3142 return true; 3143 } 3144 3145 bool X86DAGToDAGISel::tryFoldLoad(SDNode *Root, SDNode *P, SDValue N, 3146 SDValue &Base, SDValue &Scale, 3147 SDValue &Index, SDValue &Disp, 3148 SDValue &Segment) { 3149 assert(Root && P && "Unknown root/parent nodes"); 3150 if (!ISD::isNON_EXTLoad(N.getNode()) || 3151 !IsProfitableToFold(N, P, Root) || 3152 !IsLegalToFold(N, P, Root, OptLevel)) 3153 return false; 3154 3155 return selectAddr(N.getNode(), 3156 N.getOperand(1), Base, Scale, Index, Disp, Segment); 3157 } 3158 3159 bool X86DAGToDAGISel::tryFoldBroadcast(SDNode *Root, SDNode *P, SDValue N, 3160 SDValue &Base, SDValue &Scale, 3161 SDValue &Index, SDValue &Disp, 3162 SDValue &Segment) { 3163 assert(Root && P && "Unknown root/parent nodes"); 3164 if (N->getOpcode() != X86ISD::VBROADCAST_LOAD || 3165 !IsProfitableToFold(N, P, Root) || 3166 !IsLegalToFold(N, P, Root, OptLevel)) 3167 return false; 3168 3169 return selectAddr(N.getNode(), 3170 N.getOperand(1), Base, Scale, Index, Disp, Segment); 3171 } 3172 3173 /// Return an SDNode that returns the value of the global base register. 3174 /// Output instructions required to initialize the global base register, 3175 /// if necessary. 3176 SDNode *X86DAGToDAGISel::getGlobalBaseReg() { 3177 unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF); 3178 auto &DL = MF->getDataLayout(); 3179 return CurDAG->getRegister(GlobalBaseReg, TLI->getPointerTy(DL)).getNode(); 3180 } 3181 3182 bool X86DAGToDAGISel::isSExtAbsoluteSymbolRef(unsigned Width, SDNode *N) const { 3183 if (N->getOpcode() == ISD::TRUNCATE) 3184 N = N->getOperand(0).getNode(); 3185 if (N->getOpcode() != X86ISD::Wrapper) 3186 return false; 3187 3188 auto *GA = dyn_cast<GlobalAddressSDNode>(N->getOperand(0)); 3189 if (!GA) 3190 return false; 3191 3192 std::optional<ConstantRange> CR = GA->getGlobal()->getAbsoluteSymbolRange(); 3193 if (!CR) 3194 return Width == 32 && TM.getCodeModel() == CodeModel::Small; 3195 3196 return CR->getSignedMin().sge(-1ull << Width) && 3197 CR->getSignedMax().slt(1ull << Width); 3198 } 3199 3200 X86::CondCode X86DAGToDAGISel::getCondFromNode(SDNode *N) const { 3201 assert(N->isMachineOpcode() && "Unexpected node"); 3202 unsigned Opc = N->getMachineOpcode(); 3203 const MCInstrDesc &MCID = getInstrInfo()->get(Opc); 3204 int CondNo = X86::getCondSrcNoFromDesc(MCID); 3205 if (CondNo < 0) 3206 return X86::COND_INVALID; 3207 3208 return static_cast<X86::CondCode>(N->getConstantOperandVal(CondNo)); 3209 } 3210 3211 /// Test whether the given X86ISD::CMP node has any users that use a flag 3212 /// other than ZF. 3213 bool X86DAGToDAGISel::onlyUsesZeroFlag(SDValue Flags) const { 3214 // Examine each user of the node. 3215 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end(); 3216 UI != UE; ++UI) { 3217 // Only check things that use the flags. 3218 if (UI.getUse().getResNo() != Flags.getResNo()) 3219 continue; 3220 // Only examine CopyToReg uses that copy to EFLAGS. 3221 if (UI->getOpcode() != ISD::CopyToReg || 3222 cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS) 3223 return false; 3224 // Examine each user of the CopyToReg use. 3225 for (SDNode::use_iterator FlagUI = UI->use_begin(), 3226 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) { 3227 // Only examine the Flag result. 3228 if (FlagUI.getUse().getResNo() != 1) continue; 3229 // Anything unusual: assume conservatively. 3230 if (!FlagUI->isMachineOpcode()) return false; 3231 // Examine the condition code of the user. 3232 X86::CondCode CC = getCondFromNode(*FlagUI); 3233 3234 switch (CC) { 3235 // Comparisons which only use the zero flag. 3236 case X86::COND_E: case X86::COND_NE: 3237 continue; 3238 // Anything else: assume conservatively. 3239 default: 3240 return false; 3241 } 3242 } 3243 } 3244 return true; 3245 } 3246 3247 /// Test whether the given X86ISD::CMP node has any uses which require the SF 3248 /// flag to be accurate. 3249 bool X86DAGToDAGISel::hasNoSignFlagUses(SDValue Flags) const { 3250 // Examine each user of the node. 3251 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end(); 3252 UI != UE; ++UI) { 3253 // Only check things that use the flags. 3254 if (UI.getUse().getResNo() != Flags.getResNo()) 3255 continue; 3256 // Only examine CopyToReg uses that copy to EFLAGS. 3257 if (UI->getOpcode() != ISD::CopyToReg || 3258 cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS) 3259 return false; 3260 // Examine each user of the CopyToReg use. 3261 for (SDNode::use_iterator FlagUI = UI->use_begin(), 3262 FlagUE = UI->use_end(); FlagUI != FlagUE; ++FlagUI) { 3263 // Only examine the Flag result. 3264 if (FlagUI.getUse().getResNo() != 1) continue; 3265 // Anything unusual: assume conservatively. 3266 if (!FlagUI->isMachineOpcode()) return false; 3267 // Examine the condition code of the user. 3268 X86::CondCode CC = getCondFromNode(*FlagUI); 3269 3270 switch (CC) { 3271 // Comparisons which don't examine the SF flag. 3272 case X86::COND_A: case X86::COND_AE: 3273 case X86::COND_B: case X86::COND_BE: 3274 case X86::COND_E: case X86::COND_NE: 3275 case X86::COND_O: case X86::COND_NO: 3276 case X86::COND_P: case X86::COND_NP: 3277 continue; 3278 // Anything else: assume conservatively. 3279 default: 3280 return false; 3281 } 3282 } 3283 } 3284 return true; 3285 } 3286 3287 static bool mayUseCarryFlag(X86::CondCode CC) { 3288 switch (CC) { 3289 // Comparisons which don't examine the CF flag. 3290 case X86::COND_O: case X86::COND_NO: 3291 case X86::COND_E: case X86::COND_NE: 3292 case X86::COND_S: case X86::COND_NS: 3293 case X86::COND_P: case X86::COND_NP: 3294 case X86::COND_L: case X86::COND_GE: 3295 case X86::COND_G: case X86::COND_LE: 3296 return false; 3297 // Anything else: assume conservatively. 3298 default: 3299 return true; 3300 } 3301 } 3302 3303 /// Test whether the given node which sets flags has any uses which require the 3304 /// CF flag to be accurate. 3305 bool X86DAGToDAGISel::hasNoCarryFlagUses(SDValue Flags) const { 3306 // Examine each user of the node. 3307 for (SDNode::use_iterator UI = Flags->use_begin(), UE = Flags->use_end(); 3308 UI != UE; ++UI) { 3309 // Only check things that use the flags. 3310 if (UI.getUse().getResNo() != Flags.getResNo()) 3311 continue; 3312 3313 unsigned UIOpc = UI->getOpcode(); 3314 3315 if (UIOpc == ISD::CopyToReg) { 3316 // Only examine CopyToReg uses that copy to EFLAGS. 3317 if (cast<RegisterSDNode>(UI->getOperand(1))->getReg() != X86::EFLAGS) 3318 return false; 3319 // Examine each user of the CopyToReg use. 3320 for (SDNode::use_iterator FlagUI = UI->use_begin(), FlagUE = UI->use_end(); 3321 FlagUI != FlagUE; ++FlagUI) { 3322 // Only examine the Flag result. 3323 if (FlagUI.getUse().getResNo() != 1) 3324 continue; 3325 // Anything unusual: assume conservatively. 3326 if (!FlagUI->isMachineOpcode()) 3327 return false; 3328 // Examine the condition code of the user. 3329 X86::CondCode CC = getCondFromNode(*FlagUI); 3330 3331 if (mayUseCarryFlag(CC)) 3332 return false; 3333 } 3334 3335 // This CopyToReg is ok. Move on to the next user. 3336 continue; 3337 } 3338 3339 // This might be an unselected node. So look for the pre-isel opcodes that 3340 // use flags. 3341 unsigned CCOpNo; 3342 switch (UIOpc) { 3343 default: 3344 // Something unusual. Be conservative. 3345 return false; 3346 case X86ISD::SETCC: CCOpNo = 0; break; 3347 case X86ISD::SETCC_CARRY: CCOpNo = 0; break; 3348 case X86ISD::CMOV: CCOpNo = 2; break; 3349 case X86ISD::BRCOND: CCOpNo = 2; break; 3350 } 3351 3352 X86::CondCode CC = (X86::CondCode)UI->getConstantOperandVal(CCOpNo); 3353 if (mayUseCarryFlag(CC)) 3354 return false; 3355 } 3356 return true; 3357 } 3358 3359 /// Check whether or not the chain ending in StoreNode is suitable for doing 3360 /// the {load; op; store} to modify transformation. 3361 static bool isFusableLoadOpStorePattern(StoreSDNode *StoreNode, 3362 SDValue StoredVal, SelectionDAG *CurDAG, 3363 unsigned LoadOpNo, 3364 LoadSDNode *&LoadNode, 3365 SDValue &InputChain) { 3366 // Is the stored value result 0 of the operation? 3367 if (StoredVal.getResNo() != 0) return false; 3368 3369 // Are there other uses of the operation other than the store? 3370 if (!StoredVal.getNode()->hasNUsesOfValue(1, 0)) return false; 3371 3372 // Is the store non-extending and non-indexed? 3373 if (!ISD::isNormalStore(StoreNode) || StoreNode->isNonTemporal()) 3374 return false; 3375 3376 SDValue Load = StoredVal->getOperand(LoadOpNo); 3377 // Is the stored value a non-extending and non-indexed load? 3378 if (!ISD::isNormalLoad(Load.getNode())) return false; 3379 3380 // Return LoadNode by reference. 3381 LoadNode = cast<LoadSDNode>(Load); 3382 3383 // Is store the only read of the loaded value? 3384 if (!Load.hasOneUse()) 3385 return false; 3386 3387 // Is the address of the store the same as the load? 3388 if (LoadNode->getBasePtr() != StoreNode->getBasePtr() || 3389 LoadNode->getOffset() != StoreNode->getOffset()) 3390 return false; 3391 3392 bool FoundLoad = false; 3393 SmallVector<SDValue, 4> ChainOps; 3394 SmallVector<const SDNode *, 4> LoopWorklist; 3395 SmallPtrSet<const SDNode *, 16> Visited; 3396 const unsigned int Max = 1024; 3397 3398 // Visualization of Load-Op-Store fusion: 3399 // ------------------------- 3400 // Legend: 3401 // *-lines = Chain operand dependencies. 3402 // |-lines = Normal operand dependencies. 3403 // Dependencies flow down and right. n-suffix references multiple nodes. 3404 // 3405 // C Xn C 3406 // * * * 3407 // * * * 3408 // Xn A-LD Yn TF Yn 3409 // * * \ | * | 3410 // * * \ | * | 3411 // * * \ | => A--LD_OP_ST 3412 // * * \| \ 3413 // TF OP \ 3414 // * | \ Zn 3415 // * | \ 3416 // A-ST Zn 3417 // 3418 3419 // This merge induced dependences from: #1: Xn -> LD, OP, Zn 3420 // #2: Yn -> LD 3421 // #3: ST -> Zn 3422 3423 // Ensure the transform is safe by checking for the dual 3424 // dependencies to make sure we do not induce a loop. 3425 3426 // As LD is a predecessor to both OP and ST we can do this by checking: 3427 // a). if LD is a predecessor to a member of Xn or Yn. 3428 // b). if a Zn is a predecessor to ST. 3429 3430 // However, (b) can only occur through being a chain predecessor to 3431 // ST, which is the same as Zn being a member or predecessor of Xn, 3432 // which is a subset of LD being a predecessor of Xn. So it's 3433 // subsumed by check (a). 3434 3435 SDValue Chain = StoreNode->getChain(); 3436 3437 // Gather X elements in ChainOps. 3438 if (Chain == Load.getValue(1)) { 3439 FoundLoad = true; 3440 ChainOps.push_back(Load.getOperand(0)); 3441 } else if (Chain.getOpcode() == ISD::TokenFactor) { 3442 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i) { 3443 SDValue Op = Chain.getOperand(i); 3444 if (Op == Load.getValue(1)) { 3445 FoundLoad = true; 3446 // Drop Load, but keep its chain. No cycle check necessary. 3447 ChainOps.push_back(Load.getOperand(0)); 3448 continue; 3449 } 3450 LoopWorklist.push_back(Op.getNode()); 3451 ChainOps.push_back(Op); 3452 } 3453 } 3454 3455 if (!FoundLoad) 3456 return false; 3457 3458 // Worklist is currently Xn. Add Yn to worklist. 3459 for (SDValue Op : StoredVal->ops()) 3460 if (Op.getNode() != LoadNode) 3461 LoopWorklist.push_back(Op.getNode()); 3462 3463 // Check (a) if Load is a predecessor to Xn + Yn 3464 if (SDNode::hasPredecessorHelper(Load.getNode(), Visited, LoopWorklist, Max, 3465 true)) 3466 return false; 3467 3468 InputChain = 3469 CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ChainOps); 3470 return true; 3471 } 3472 3473 // Change a chain of {load; op; store} of the same value into a simple op 3474 // through memory of that value, if the uses of the modified value and its 3475 // address are suitable. 3476 // 3477 // The tablegen pattern memory operand pattern is currently not able to match 3478 // the case where the EFLAGS on the original operation are used. 3479 // 3480 // To move this to tablegen, we'll need to improve tablegen to allow flags to 3481 // be transferred from a node in the pattern to the result node, probably with 3482 // a new keyword. For example, we have this 3483 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst", 3484 // [(store (add (loadi64 addr:$dst), -1), addr:$dst), 3485 // (implicit EFLAGS)]>; 3486 // but maybe need something like this 3487 // def DEC64m : RI<0xFF, MRM1m, (outs), (ins i64mem:$dst), "dec{q}\t$dst", 3488 // [(store (add (loadi64 addr:$dst), -1), addr:$dst), 3489 // (transferrable EFLAGS)]>; 3490 // 3491 // Until then, we manually fold these and instruction select the operation 3492 // here. 3493 bool X86DAGToDAGISel::foldLoadStoreIntoMemOperand(SDNode *Node) { 3494 auto *StoreNode = cast<StoreSDNode>(Node); 3495 SDValue StoredVal = StoreNode->getOperand(1); 3496 unsigned Opc = StoredVal->getOpcode(); 3497 3498 // Before we try to select anything, make sure this is memory operand size 3499 // and opcode we can handle. Note that this must match the code below that 3500 // actually lowers the opcodes. 3501 EVT MemVT = StoreNode->getMemoryVT(); 3502 if (MemVT != MVT::i64 && MemVT != MVT::i32 && MemVT != MVT::i16 && 3503 MemVT != MVT::i8) 3504 return false; 3505 3506 bool IsCommutable = false; 3507 bool IsNegate = false; 3508 switch (Opc) { 3509 default: 3510 return false; 3511 case X86ISD::SUB: 3512 IsNegate = isNullConstant(StoredVal.getOperand(0)); 3513 break; 3514 case X86ISD::SBB: 3515 break; 3516 case X86ISD::ADD: 3517 case X86ISD::ADC: 3518 case X86ISD::AND: 3519 case X86ISD::OR: 3520 case X86ISD::XOR: 3521 IsCommutable = true; 3522 break; 3523 } 3524 3525 unsigned LoadOpNo = IsNegate ? 1 : 0; 3526 LoadSDNode *LoadNode = nullptr; 3527 SDValue InputChain; 3528 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo, 3529 LoadNode, InputChain)) { 3530 if (!IsCommutable) 3531 return false; 3532 3533 // This operation is commutable, try the other operand. 3534 LoadOpNo = 1; 3535 if (!isFusableLoadOpStorePattern(StoreNode, StoredVal, CurDAG, LoadOpNo, 3536 LoadNode, InputChain)) 3537 return false; 3538 } 3539 3540 SDValue Base, Scale, Index, Disp, Segment; 3541 if (!selectAddr(LoadNode, LoadNode->getBasePtr(), Base, Scale, Index, Disp, 3542 Segment)) 3543 return false; 3544 3545 auto SelectOpcode = [&](unsigned Opc64, unsigned Opc32, unsigned Opc16, 3546 unsigned Opc8) { 3547 switch (MemVT.getSimpleVT().SimpleTy) { 3548 case MVT::i64: 3549 return Opc64; 3550 case MVT::i32: 3551 return Opc32; 3552 case MVT::i16: 3553 return Opc16; 3554 case MVT::i8: 3555 return Opc8; 3556 default: 3557 llvm_unreachable("Invalid size!"); 3558 } 3559 }; 3560 3561 MachineSDNode *Result; 3562 switch (Opc) { 3563 case X86ISD::SUB: 3564 // Handle negate. 3565 if (IsNegate) { 3566 unsigned NewOpc = SelectOpcode(X86::NEG64m, X86::NEG32m, X86::NEG16m, 3567 X86::NEG8m); 3568 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain}; 3569 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, 3570 MVT::Other, Ops); 3571 break; 3572 } 3573 [[fallthrough]]; 3574 case X86ISD::ADD: 3575 // Try to match inc/dec. 3576 if (!Subtarget->slowIncDec() || CurDAG->shouldOptForSize()) { 3577 bool IsOne = isOneConstant(StoredVal.getOperand(1)); 3578 bool IsNegOne = isAllOnesConstant(StoredVal.getOperand(1)); 3579 // ADD/SUB with 1/-1 and carry flag isn't used can use inc/dec. 3580 if ((IsOne || IsNegOne) && hasNoCarryFlagUses(StoredVal.getValue(1))) { 3581 unsigned NewOpc = 3582 ((Opc == X86ISD::ADD) == IsOne) 3583 ? SelectOpcode(X86::INC64m, X86::INC32m, X86::INC16m, X86::INC8m) 3584 : SelectOpcode(X86::DEC64m, X86::DEC32m, X86::DEC16m, X86::DEC8m); 3585 const SDValue Ops[] = {Base, Scale, Index, Disp, Segment, InputChain}; 3586 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, 3587 MVT::Other, Ops); 3588 break; 3589 } 3590 } 3591 [[fallthrough]]; 3592 case X86ISD::ADC: 3593 case X86ISD::SBB: 3594 case X86ISD::AND: 3595 case X86ISD::OR: 3596 case X86ISD::XOR: { 3597 auto SelectRegOpcode = [SelectOpcode](unsigned Opc) { 3598 switch (Opc) { 3599 case X86ISD::ADD: 3600 return SelectOpcode(X86::ADD64mr, X86::ADD32mr, X86::ADD16mr, 3601 X86::ADD8mr); 3602 case X86ISD::ADC: 3603 return SelectOpcode(X86::ADC64mr, X86::ADC32mr, X86::ADC16mr, 3604 X86::ADC8mr); 3605 case X86ISD::SUB: 3606 return SelectOpcode(X86::SUB64mr, X86::SUB32mr, X86::SUB16mr, 3607 X86::SUB8mr); 3608 case X86ISD::SBB: 3609 return SelectOpcode(X86::SBB64mr, X86::SBB32mr, X86::SBB16mr, 3610 X86::SBB8mr); 3611 case X86ISD::AND: 3612 return SelectOpcode(X86::AND64mr, X86::AND32mr, X86::AND16mr, 3613 X86::AND8mr); 3614 case X86ISD::OR: 3615 return SelectOpcode(X86::OR64mr, X86::OR32mr, X86::OR16mr, X86::OR8mr); 3616 case X86ISD::XOR: 3617 return SelectOpcode(X86::XOR64mr, X86::XOR32mr, X86::XOR16mr, 3618 X86::XOR8mr); 3619 default: 3620 llvm_unreachable("Invalid opcode!"); 3621 } 3622 }; 3623 auto SelectImmOpcode = [SelectOpcode](unsigned Opc) { 3624 switch (Opc) { 3625 case X86ISD::ADD: 3626 return SelectOpcode(X86::ADD64mi32, X86::ADD32mi, X86::ADD16mi, 3627 X86::ADD8mi); 3628 case X86ISD::ADC: 3629 return SelectOpcode(X86::ADC64mi32, X86::ADC32mi, X86::ADC16mi, 3630 X86::ADC8mi); 3631 case X86ISD::SUB: 3632 return SelectOpcode(X86::SUB64mi32, X86::SUB32mi, X86::SUB16mi, 3633 X86::SUB8mi); 3634 case X86ISD::SBB: 3635 return SelectOpcode(X86::SBB64mi32, X86::SBB32mi, X86::SBB16mi, 3636 X86::SBB8mi); 3637 case X86ISD::AND: 3638 return SelectOpcode(X86::AND64mi32, X86::AND32mi, X86::AND16mi, 3639 X86::AND8mi); 3640 case X86ISD::OR: 3641 return SelectOpcode(X86::OR64mi32, X86::OR32mi, X86::OR16mi, 3642 X86::OR8mi); 3643 case X86ISD::XOR: 3644 return SelectOpcode(X86::XOR64mi32, X86::XOR32mi, X86::XOR16mi, 3645 X86::XOR8mi); 3646 default: 3647 llvm_unreachable("Invalid opcode!"); 3648 } 3649 }; 3650 3651 unsigned NewOpc = SelectRegOpcode(Opc); 3652 SDValue Operand = StoredVal->getOperand(1-LoadOpNo); 3653 3654 // See if the operand is a constant that we can fold into an immediate 3655 // operand. 3656 if (auto *OperandC = dyn_cast<ConstantSDNode>(Operand)) { 3657 int64_t OperandV = OperandC->getSExtValue(); 3658 3659 // Check if we can shrink the operand enough to fit in an immediate (or 3660 // fit into a smaller immediate) by negating it and switching the 3661 // operation. 3662 if ((Opc == X86ISD::ADD || Opc == X86ISD::SUB) && 3663 ((MemVT != MVT::i8 && !isInt<8>(OperandV) && isInt<8>(-OperandV)) || 3664 (MemVT == MVT::i64 && !isInt<32>(OperandV) && 3665 isInt<32>(-OperandV))) && 3666 hasNoCarryFlagUses(StoredVal.getValue(1))) { 3667 OperandV = -OperandV; 3668 Opc = Opc == X86ISD::ADD ? X86ISD::SUB : X86ISD::ADD; 3669 } 3670 3671 if (MemVT != MVT::i64 || isInt<32>(OperandV)) { 3672 Operand = CurDAG->getTargetConstant(OperandV, SDLoc(Node), MemVT); 3673 NewOpc = SelectImmOpcode(Opc); 3674 } 3675 } 3676 3677 if (Opc == X86ISD::ADC || Opc == X86ISD::SBB) { 3678 SDValue CopyTo = 3679 CurDAG->getCopyToReg(InputChain, SDLoc(Node), X86::EFLAGS, 3680 StoredVal.getOperand(2), SDValue()); 3681 3682 const SDValue Ops[] = {Base, Scale, Index, Disp, 3683 Segment, Operand, CopyTo, CopyTo.getValue(1)}; 3684 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, 3685 Ops); 3686 } else { 3687 const SDValue Ops[] = {Base, Scale, Index, Disp, 3688 Segment, Operand, InputChain}; 3689 Result = CurDAG->getMachineNode(NewOpc, SDLoc(Node), MVT::i32, MVT::Other, 3690 Ops); 3691 } 3692 break; 3693 } 3694 default: 3695 llvm_unreachable("Invalid opcode!"); 3696 } 3697 3698 MachineMemOperand *MemOps[] = {StoreNode->getMemOperand(), 3699 LoadNode->getMemOperand()}; 3700 CurDAG->setNodeMemRefs(Result, MemOps); 3701 3702 // Update Load Chain uses as well. 3703 ReplaceUses(SDValue(LoadNode, 1), SDValue(Result, 1)); 3704 ReplaceUses(SDValue(StoreNode, 0), SDValue(Result, 1)); 3705 ReplaceUses(SDValue(StoredVal.getNode(), 1), SDValue(Result, 0)); 3706 CurDAG->RemoveDeadNode(Node); 3707 return true; 3708 } 3709 3710 // See if this is an X & Mask that we can match to BEXTR/BZHI. 3711 // Where Mask is one of the following patterns: 3712 // a) x & (1 << nbits) - 1 3713 // b) x & ~(-1 << nbits) 3714 // c) x & (-1 >> (32 - y)) 3715 // d) x << (32 - y) >> (32 - y) 3716 // e) (1 << nbits) - 1 3717 bool X86DAGToDAGISel::matchBitExtract(SDNode *Node) { 3718 assert( 3719 (Node->getOpcode() == ISD::ADD || Node->getOpcode() == ISD::AND || 3720 Node->getOpcode() == ISD::SRL) && 3721 "Should be either an and-mask, or right-shift after clearing high bits."); 3722 3723 // BEXTR is BMI instruction, BZHI is BMI2 instruction. We need at least one. 3724 if (!Subtarget->hasBMI() && !Subtarget->hasBMI2()) 3725 return false; 3726 3727 MVT NVT = Node->getSimpleValueType(0); 3728 3729 // Only supported for 32 and 64 bits. 3730 if (NVT != MVT::i32 && NVT != MVT::i64) 3731 return false; 3732 3733 SDValue NBits; 3734 bool NegateNBits; 3735 3736 // If we have BMI2's BZHI, we are ok with muti-use patterns. 3737 // Else, if we only have BMI1's BEXTR, we require one-use. 3738 const bool AllowExtraUsesByDefault = Subtarget->hasBMI2(); 3739 auto checkUses = [AllowExtraUsesByDefault]( 3740 SDValue Op, unsigned NUses, 3741 std::optional<bool> AllowExtraUses) { 3742 return AllowExtraUses.value_or(AllowExtraUsesByDefault) || 3743 Op.getNode()->hasNUsesOfValue(NUses, Op.getResNo()); 3744 }; 3745 auto checkOneUse = [checkUses](SDValue Op, 3746 std::optional<bool> AllowExtraUses = 3747 std::nullopt) { 3748 return checkUses(Op, 1, AllowExtraUses); 3749 }; 3750 auto checkTwoUse = [checkUses](SDValue Op, 3751 std::optional<bool> AllowExtraUses = 3752 std::nullopt) { 3753 return checkUses(Op, 2, AllowExtraUses); 3754 }; 3755 3756 auto peekThroughOneUseTruncation = [checkOneUse](SDValue V) { 3757 if (V->getOpcode() == ISD::TRUNCATE && checkOneUse(V)) { 3758 assert(V.getSimpleValueType() == MVT::i32 && 3759 V.getOperand(0).getSimpleValueType() == MVT::i64 && 3760 "Expected i64 -> i32 truncation"); 3761 V = V.getOperand(0); 3762 } 3763 return V; 3764 }; 3765 3766 // a) x & ((1 << nbits) + (-1)) 3767 auto matchPatternA = [checkOneUse, peekThroughOneUseTruncation, &NBits, 3768 &NegateNBits](SDValue Mask) -> bool { 3769 // Match `add`. Must only have one use! 3770 if (Mask->getOpcode() != ISD::ADD || !checkOneUse(Mask)) 3771 return false; 3772 // We should be adding all-ones constant (i.e. subtracting one.) 3773 if (!isAllOnesConstant(Mask->getOperand(1))) 3774 return false; 3775 // Match `1 << nbits`. Might be truncated. Must only have one use! 3776 SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0)); 3777 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0)) 3778 return false; 3779 if (!isOneConstant(M0->getOperand(0))) 3780 return false; 3781 NBits = M0->getOperand(1); 3782 NegateNBits = false; 3783 return true; 3784 }; 3785 3786 auto isAllOnes = [this, peekThroughOneUseTruncation, NVT](SDValue V) { 3787 V = peekThroughOneUseTruncation(V); 3788 return CurDAG->MaskedValueIsAllOnes( 3789 V, APInt::getLowBitsSet(V.getSimpleValueType().getSizeInBits(), 3790 NVT.getSizeInBits())); 3791 }; 3792 3793 // b) x & ~(-1 << nbits) 3794 auto matchPatternB = [checkOneUse, isAllOnes, peekThroughOneUseTruncation, 3795 &NBits, &NegateNBits](SDValue Mask) -> bool { 3796 // Match `~()`. Must only have one use! 3797 if (Mask.getOpcode() != ISD::XOR || !checkOneUse(Mask)) 3798 return false; 3799 // The -1 only has to be all-ones for the final Node's NVT. 3800 if (!isAllOnes(Mask->getOperand(1))) 3801 return false; 3802 // Match `-1 << nbits`. Might be truncated. Must only have one use! 3803 SDValue M0 = peekThroughOneUseTruncation(Mask->getOperand(0)); 3804 if (M0->getOpcode() != ISD::SHL || !checkOneUse(M0)) 3805 return false; 3806 // The -1 only has to be all-ones for the final Node's NVT. 3807 if (!isAllOnes(M0->getOperand(0))) 3808 return false; 3809 NBits = M0->getOperand(1); 3810 NegateNBits = false; 3811 return true; 3812 }; 3813 3814 // Try to match potentially-truncated shift amount as `(bitwidth - y)`, 3815 // or leave the shift amount as-is, but then we'll have to negate it. 3816 auto canonicalizeShiftAmt = [&NBits, &NegateNBits](SDValue ShiftAmt, 3817 unsigned Bitwidth) { 3818 NBits = ShiftAmt; 3819 NegateNBits = true; 3820 // Skip over a truncate of the shift amount, if any. 3821 if (NBits.getOpcode() == ISD::TRUNCATE) 3822 NBits = NBits.getOperand(0); 3823 // Try to match the shift amount as (bitwidth - y). It should go away, too. 3824 // If it doesn't match, that's fine, we'll just negate it ourselves. 3825 if (NBits.getOpcode() != ISD::SUB) 3826 return; 3827 auto *V0 = dyn_cast<ConstantSDNode>(NBits.getOperand(0)); 3828 if (!V0 || V0->getZExtValue() != Bitwidth) 3829 return; 3830 NBits = NBits.getOperand(1); 3831 NegateNBits = false; 3832 }; 3833 3834 // c) x & (-1 >> z) but then we'll have to subtract z from bitwidth 3835 // or 3836 // c) x & (-1 >> (32 - y)) 3837 auto matchPatternC = [checkOneUse, peekThroughOneUseTruncation, &NegateNBits, 3838 canonicalizeShiftAmt](SDValue Mask) -> bool { 3839 // The mask itself may be truncated. 3840 Mask = peekThroughOneUseTruncation(Mask); 3841 unsigned Bitwidth = Mask.getSimpleValueType().getSizeInBits(); 3842 // Match `l>>`. Must only have one use! 3843 if (Mask.getOpcode() != ISD::SRL || !checkOneUse(Mask)) 3844 return false; 3845 // We should be shifting truly all-ones constant. 3846 if (!isAllOnesConstant(Mask.getOperand(0))) 3847 return false; 3848 SDValue M1 = Mask.getOperand(1); 3849 // The shift amount should not be used externally. 3850 if (!checkOneUse(M1)) 3851 return false; 3852 canonicalizeShiftAmt(M1, Bitwidth); 3853 // Pattern c. is non-canonical, and is expanded into pattern d. iff there 3854 // is no extra use of the mask. Clearly, there was one since we are here. 3855 // But at the same time, if we need to negate the shift amount, 3856 // then we don't want the mask to stick around, else it's unprofitable. 3857 return !NegateNBits; 3858 }; 3859 3860 SDValue X; 3861 3862 // d) x << z >> z but then we'll have to subtract z from bitwidth 3863 // or 3864 // d) x << (32 - y) >> (32 - y) 3865 auto matchPatternD = [checkOneUse, checkTwoUse, canonicalizeShiftAmt, 3866 AllowExtraUsesByDefault, &NegateNBits, 3867 &X](SDNode *Node) -> bool { 3868 if (Node->getOpcode() != ISD::SRL) 3869 return false; 3870 SDValue N0 = Node->getOperand(0); 3871 if (N0->getOpcode() != ISD::SHL) 3872 return false; 3873 unsigned Bitwidth = N0.getSimpleValueType().getSizeInBits(); 3874 SDValue N1 = Node->getOperand(1); 3875 SDValue N01 = N0->getOperand(1); 3876 // Both of the shifts must be by the exact same value. 3877 if (N1 != N01) 3878 return false; 3879 canonicalizeShiftAmt(N1, Bitwidth); 3880 // There should not be any external uses of the inner shift / shift amount. 3881 // Note that while we are generally okay with external uses given BMI2, 3882 // iff we need to negate the shift amount, we are not okay with extra uses. 3883 const bool AllowExtraUses = AllowExtraUsesByDefault && !NegateNBits; 3884 if (!checkOneUse(N0, AllowExtraUses) || !checkTwoUse(N1, AllowExtraUses)) 3885 return false; 3886 X = N0->getOperand(0); 3887 return true; 3888 }; 3889 3890 auto matchLowBitMask = [matchPatternA, matchPatternB, 3891 matchPatternC](SDValue Mask) -> bool { 3892 return matchPatternA(Mask) || matchPatternB(Mask) || matchPatternC(Mask); 3893 }; 3894 3895 if (Node->getOpcode() == ISD::AND) { 3896 X = Node->getOperand(0); 3897 SDValue Mask = Node->getOperand(1); 3898 3899 if (matchLowBitMask(Mask)) { 3900 // Great. 3901 } else { 3902 std::swap(X, Mask); 3903 if (!matchLowBitMask(Mask)) 3904 return false; 3905 } 3906 } else if (matchLowBitMask(SDValue(Node, 0))) { 3907 X = CurDAG->getAllOnesConstant(SDLoc(Node), NVT); 3908 } else if (!matchPatternD(Node)) 3909 return false; 3910 3911 // If we need to negate the shift amount, require BMI2 BZHI support. 3912 // It's just too unprofitable for BMI1 BEXTR. 3913 if (NegateNBits && !Subtarget->hasBMI2()) 3914 return false; 3915 3916 SDLoc DL(Node); 3917 3918 // Truncate the shift amount. 3919 NBits = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NBits); 3920 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits); 3921 3922 // Insert 8-bit NBits into lowest 8 bits of 32-bit register. 3923 // All the other bits are undefined, we do not care about them. 3924 SDValue ImplDef = SDValue( 3925 CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, MVT::i32), 0); 3926 insertDAGNode(*CurDAG, SDValue(Node, 0), ImplDef); 3927 3928 SDValue SRIdxVal = CurDAG->getTargetConstant(X86::sub_8bit, DL, MVT::i32); 3929 insertDAGNode(*CurDAG, SDValue(Node, 0), SRIdxVal); 3930 NBits = SDValue(CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, DL, 3931 MVT::i32, ImplDef, NBits, SRIdxVal), 3932 0); 3933 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits); 3934 3935 // We might have matched the amount of high bits to be cleared, 3936 // but we want the amount of low bits to be kept, so negate it then. 3937 if (NegateNBits) { 3938 SDValue BitWidthC = CurDAG->getConstant(NVT.getSizeInBits(), DL, MVT::i32); 3939 insertDAGNode(*CurDAG, SDValue(Node, 0), BitWidthC); 3940 3941 NBits = CurDAG->getNode(ISD::SUB, DL, MVT::i32, BitWidthC, NBits); 3942 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits); 3943 } 3944 3945 if (Subtarget->hasBMI2()) { 3946 // Great, just emit the BZHI.. 3947 if (NVT != MVT::i32) { 3948 // But have to place the bit count into the wide-enough register first. 3949 NBits = CurDAG->getNode(ISD::ANY_EXTEND, DL, NVT, NBits); 3950 insertDAGNode(*CurDAG, SDValue(Node, 0), NBits); 3951 } 3952 3953 SDValue Extract = CurDAG->getNode(X86ISD::BZHI, DL, NVT, X, NBits); 3954 ReplaceNode(Node, Extract.getNode()); 3955 SelectCode(Extract.getNode()); 3956 return true; 3957 } 3958 3959 // Else, if we do *NOT* have BMI2, let's find out if the if the 'X' is 3960 // *logically* shifted (potentially with one-use trunc inbetween), 3961 // and the truncation was the only use of the shift, 3962 // and if so look past one-use truncation. 3963 { 3964 SDValue RealX = peekThroughOneUseTruncation(X); 3965 // FIXME: only if the shift is one-use? 3966 if (RealX != X && RealX.getOpcode() == ISD::SRL) 3967 X = RealX; 3968 } 3969 3970 MVT XVT = X.getSimpleValueType(); 3971 3972 // Else, emitting BEXTR requires one more step. 3973 // The 'control' of BEXTR has the pattern of: 3974 // [15...8 bit][ 7...0 bit] location 3975 // [ bit count][ shift] name 3976 // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11 3977 3978 // Shift NBits left by 8 bits, thus producing 'control'. 3979 // This makes the low 8 bits to be zero. 3980 SDValue C8 = CurDAG->getConstant(8, DL, MVT::i8); 3981 insertDAGNode(*CurDAG, SDValue(Node, 0), C8); 3982 SDValue Control = CurDAG->getNode(ISD::SHL, DL, MVT::i32, NBits, C8); 3983 insertDAGNode(*CurDAG, SDValue(Node, 0), Control); 3984 3985 // If the 'X' is *logically* shifted, we can fold that shift into 'control'. 3986 // FIXME: only if the shift is one-use? 3987 if (X.getOpcode() == ISD::SRL) { 3988 SDValue ShiftAmt = X.getOperand(1); 3989 X = X.getOperand(0); 3990 3991 assert(ShiftAmt.getValueType() == MVT::i8 && 3992 "Expected shift amount to be i8"); 3993 3994 // Now, *zero*-extend the shift amount. The bits 8...15 *must* be zero! 3995 // We could zext to i16 in some form, but we intentionally don't do that. 3996 SDValue OrigShiftAmt = ShiftAmt; 3997 ShiftAmt = CurDAG->getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShiftAmt); 3998 insertDAGNode(*CurDAG, OrigShiftAmt, ShiftAmt); 3999 4000 // And now 'or' these low 8 bits of shift amount into the 'control'. 4001 Control = CurDAG->getNode(ISD::OR, DL, MVT::i32, Control, ShiftAmt); 4002 insertDAGNode(*CurDAG, SDValue(Node, 0), Control); 4003 } 4004 4005 // But have to place the 'control' into the wide-enough register first. 4006 if (XVT != MVT::i32) { 4007 Control = CurDAG->getNode(ISD::ANY_EXTEND, DL, XVT, Control); 4008 insertDAGNode(*CurDAG, SDValue(Node, 0), Control); 4009 } 4010 4011 // And finally, form the BEXTR itself. 4012 SDValue Extract = CurDAG->getNode(X86ISD::BEXTR, DL, XVT, X, Control); 4013 4014 // The 'X' was originally truncated. Do that now. 4015 if (XVT != NVT) { 4016 insertDAGNode(*CurDAG, SDValue(Node, 0), Extract); 4017 Extract = CurDAG->getNode(ISD::TRUNCATE, DL, NVT, Extract); 4018 } 4019 4020 ReplaceNode(Node, Extract.getNode()); 4021 SelectCode(Extract.getNode()); 4022 4023 return true; 4024 } 4025 4026 // See if this is an (X >> C1) & C2 that we can match to BEXTR/BEXTRI. 4027 MachineSDNode *X86DAGToDAGISel::matchBEXTRFromAndImm(SDNode *Node) { 4028 MVT NVT = Node->getSimpleValueType(0); 4029 SDLoc dl(Node); 4030 4031 SDValue N0 = Node->getOperand(0); 4032 SDValue N1 = Node->getOperand(1); 4033 4034 // If we have TBM we can use an immediate for the control. If we have BMI 4035 // we should only do this if the BEXTR instruction is implemented well. 4036 // Otherwise moving the control into a register makes this more costly. 4037 // TODO: Maybe load folding, greater than 32-bit masks, or a guarantee of LICM 4038 // hoisting the move immediate would make it worthwhile with a less optimal 4039 // BEXTR? 4040 bool PreferBEXTR = 4041 Subtarget->hasTBM() || (Subtarget->hasBMI() && Subtarget->hasFastBEXTR()); 4042 if (!PreferBEXTR && !Subtarget->hasBMI2()) 4043 return nullptr; 4044 4045 // Must have a shift right. 4046 if (N0->getOpcode() != ISD::SRL && N0->getOpcode() != ISD::SRA) 4047 return nullptr; 4048 4049 // Shift can't have additional users. 4050 if (!N0->hasOneUse()) 4051 return nullptr; 4052 4053 // Only supported for 32 and 64 bits. 4054 if (NVT != MVT::i32 && NVT != MVT::i64) 4055 return nullptr; 4056 4057 // Shift amount and RHS of and must be constant. 4058 auto *MaskCst = dyn_cast<ConstantSDNode>(N1); 4059 auto *ShiftCst = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 4060 if (!MaskCst || !ShiftCst) 4061 return nullptr; 4062 4063 // And RHS must be a mask. 4064 uint64_t Mask = MaskCst->getZExtValue(); 4065 if (!isMask_64(Mask)) 4066 return nullptr; 4067 4068 uint64_t Shift = ShiftCst->getZExtValue(); 4069 uint64_t MaskSize = llvm::popcount(Mask); 4070 4071 // Don't interfere with something that can be handled by extracting AH. 4072 // TODO: If we are able to fold a load, BEXTR might still be better than AH. 4073 if (Shift == 8 && MaskSize == 8) 4074 return nullptr; 4075 4076 // Make sure we are only using bits that were in the original value, not 4077 // shifted in. 4078 if (Shift + MaskSize > NVT.getSizeInBits()) 4079 return nullptr; 4080 4081 // BZHI, if available, is always fast, unlike BEXTR. But even if we decide 4082 // that we can't use BEXTR, it is only worthwhile using BZHI if the mask 4083 // does not fit into 32 bits. Load folding is not a sufficient reason. 4084 if (!PreferBEXTR && MaskSize <= 32) 4085 return nullptr; 4086 4087 SDValue Control; 4088 unsigned ROpc, MOpc; 4089 4090 if (!PreferBEXTR) { 4091 assert(Subtarget->hasBMI2() && "We must have BMI2's BZHI then."); 4092 // If we can't make use of BEXTR then we can't fuse shift+mask stages. 4093 // Let's perform the mask first, and apply shift later. Note that we need to 4094 // widen the mask to account for the fact that we'll apply shift afterwards! 4095 Control = CurDAG->getTargetConstant(Shift + MaskSize, dl, NVT); 4096 ROpc = NVT == MVT::i64 ? X86::BZHI64rr : X86::BZHI32rr; 4097 MOpc = NVT == MVT::i64 ? X86::BZHI64rm : X86::BZHI32rm; 4098 unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri; 4099 Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0); 4100 } else { 4101 // The 'control' of BEXTR has the pattern of: 4102 // [15...8 bit][ 7...0 bit] location 4103 // [ bit count][ shift] name 4104 // I.e. 0b000000011'00000001 means (x >> 0b1) & 0b11 4105 Control = CurDAG->getTargetConstant(Shift | (MaskSize << 8), dl, NVT); 4106 if (Subtarget->hasTBM()) { 4107 ROpc = NVT == MVT::i64 ? X86::BEXTRI64ri : X86::BEXTRI32ri; 4108 MOpc = NVT == MVT::i64 ? X86::BEXTRI64mi : X86::BEXTRI32mi; 4109 } else { 4110 assert(Subtarget->hasBMI() && "We must have BMI1's BEXTR then."); 4111 // BMI requires the immediate to placed in a register. 4112 ROpc = NVT == MVT::i64 ? X86::BEXTR64rr : X86::BEXTR32rr; 4113 MOpc = NVT == MVT::i64 ? X86::BEXTR64rm : X86::BEXTR32rm; 4114 unsigned NewOpc = NVT == MVT::i64 ? X86::MOV32ri64 : X86::MOV32ri; 4115 Control = SDValue(CurDAG->getMachineNode(NewOpc, dl, NVT, Control), 0); 4116 } 4117 } 4118 4119 MachineSDNode *NewNode; 4120 SDValue Input = N0->getOperand(0); 4121 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 4122 if (tryFoldLoad(Node, N0.getNode(), Input, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { 4123 SDValue Ops[] = { 4124 Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Control, Input.getOperand(0)}; 4125 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other); 4126 NewNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); 4127 // Update the chain. 4128 ReplaceUses(Input.getValue(1), SDValue(NewNode, 2)); 4129 // Record the mem-refs 4130 CurDAG->setNodeMemRefs(NewNode, {cast<LoadSDNode>(Input)->getMemOperand()}); 4131 } else { 4132 NewNode = CurDAG->getMachineNode(ROpc, dl, NVT, MVT::i32, Input, Control); 4133 } 4134 4135 if (!PreferBEXTR) { 4136 // We still need to apply the shift. 4137 SDValue ShAmt = CurDAG->getTargetConstant(Shift, dl, NVT); 4138 unsigned NewOpc = NVT == MVT::i64 ? X86::SHR64ri : X86::SHR32ri; 4139 NewNode = 4140 CurDAG->getMachineNode(NewOpc, dl, NVT, SDValue(NewNode, 0), ShAmt); 4141 } 4142 4143 return NewNode; 4144 } 4145 4146 // Emit a PCMISTR(I/M) instruction. 4147 MachineSDNode *X86DAGToDAGISel::emitPCMPISTR(unsigned ROpc, unsigned MOpc, 4148 bool MayFoldLoad, const SDLoc &dl, 4149 MVT VT, SDNode *Node) { 4150 SDValue N0 = Node->getOperand(0); 4151 SDValue N1 = Node->getOperand(1); 4152 SDValue Imm = Node->getOperand(2); 4153 auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue(); 4154 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType()); 4155 4156 // Try to fold a load. No need to check alignment. 4157 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 4158 if (MayFoldLoad && tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { 4159 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm, 4160 N1.getOperand(0) }; 4161 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other); 4162 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); 4163 // Update the chain. 4164 ReplaceUses(N1.getValue(1), SDValue(CNode, 2)); 4165 // Record the mem-refs 4166 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()}); 4167 return CNode; 4168 } 4169 4170 SDValue Ops[] = { N0, N1, Imm }; 4171 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32); 4172 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops); 4173 return CNode; 4174 } 4175 4176 // Emit a PCMESTR(I/M) instruction. Also return the Glue result in case we need 4177 // to emit a second instruction after this one. This is needed since we have two 4178 // copyToReg nodes glued before this and we need to continue that glue through. 4179 MachineSDNode *X86DAGToDAGISel::emitPCMPESTR(unsigned ROpc, unsigned MOpc, 4180 bool MayFoldLoad, const SDLoc &dl, 4181 MVT VT, SDNode *Node, 4182 SDValue &InGlue) { 4183 SDValue N0 = Node->getOperand(0); 4184 SDValue N2 = Node->getOperand(2); 4185 SDValue Imm = Node->getOperand(4); 4186 auto *Val = cast<ConstantSDNode>(Imm)->getConstantIntValue(); 4187 Imm = CurDAG->getTargetConstant(*Val, SDLoc(Node), Imm.getValueType()); 4188 4189 // Try to fold a load. No need to check alignment. 4190 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 4191 if (MayFoldLoad && tryFoldLoad(Node, N2, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { 4192 SDValue Ops[] = { N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm, 4193 N2.getOperand(0), InGlue }; 4194 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Other, MVT::Glue); 4195 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); 4196 InGlue = SDValue(CNode, 3); 4197 // Update the chain. 4198 ReplaceUses(N2.getValue(1), SDValue(CNode, 2)); 4199 // Record the mem-refs 4200 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N2)->getMemOperand()}); 4201 return CNode; 4202 } 4203 4204 SDValue Ops[] = { N0, N2, Imm, InGlue }; 4205 SDVTList VTs = CurDAG->getVTList(VT, MVT::i32, MVT::Glue); 4206 MachineSDNode *CNode = CurDAG->getMachineNode(ROpc, dl, VTs, Ops); 4207 InGlue = SDValue(CNode, 2); 4208 return CNode; 4209 } 4210 4211 bool X86DAGToDAGISel::tryShiftAmountMod(SDNode *N) { 4212 EVT VT = N->getValueType(0); 4213 4214 // Only handle scalar shifts. 4215 if (VT.isVector()) 4216 return false; 4217 4218 // Narrower shifts only mask to 5 bits in hardware. 4219 unsigned Size = VT == MVT::i64 ? 64 : 32; 4220 4221 SDValue OrigShiftAmt = N->getOperand(1); 4222 SDValue ShiftAmt = OrigShiftAmt; 4223 SDLoc DL(N); 4224 4225 // Skip over a truncate of the shift amount. 4226 if (ShiftAmt->getOpcode() == ISD::TRUNCATE) 4227 ShiftAmt = ShiftAmt->getOperand(0); 4228 4229 // This function is called after X86DAGToDAGISel::matchBitExtract(), 4230 // so we are not afraid that we might mess up BZHI/BEXTR pattern. 4231 4232 SDValue NewShiftAmt; 4233 if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB || 4234 ShiftAmt->getOpcode() == ISD::XOR) { 4235 SDValue Add0 = ShiftAmt->getOperand(0); 4236 SDValue Add1 = ShiftAmt->getOperand(1); 4237 auto *Add0C = dyn_cast<ConstantSDNode>(Add0); 4238 auto *Add1C = dyn_cast<ConstantSDNode>(Add1); 4239 // If we are shifting by X+/-/^N where N == 0 mod Size, then just shift by X 4240 // to avoid the ADD/SUB/XOR. 4241 if (Add1C && Add1C->getAPIntValue().urem(Size) == 0) { 4242 NewShiftAmt = Add0; 4243 4244 } else if (ShiftAmt->getOpcode() != ISD::ADD && ShiftAmt.hasOneUse() && 4245 ((Add0C && Add0C->getAPIntValue().urem(Size) == Size - 1) || 4246 (Add1C && Add1C->getAPIntValue().urem(Size) == Size - 1))) { 4247 // If we are doing a NOT on just the lower bits with (Size*N-1) -/^ X 4248 // we can replace it with a NOT. In the XOR case it may save some code 4249 // size, in the SUB case it also may save a move. 4250 assert(Add0C == nullptr || Add1C == nullptr); 4251 4252 // We can only do N-X, not X-N 4253 if (ShiftAmt->getOpcode() == ISD::SUB && Add0C == nullptr) 4254 return false; 4255 4256 EVT OpVT = ShiftAmt.getValueType(); 4257 4258 SDValue AllOnes = CurDAG->getAllOnesConstant(DL, OpVT); 4259 NewShiftAmt = CurDAG->getNode(ISD::XOR, DL, OpVT, 4260 Add0C == nullptr ? Add0 : Add1, AllOnes); 4261 insertDAGNode(*CurDAG, OrigShiftAmt, AllOnes); 4262 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt); 4263 // If we are shifting by N-X where N == 0 mod Size, then just shift by 4264 // -X to generate a NEG instead of a SUB of a constant. 4265 } else if (ShiftAmt->getOpcode() == ISD::SUB && Add0C && 4266 Add0C->getZExtValue() != 0) { 4267 EVT SubVT = ShiftAmt.getValueType(); 4268 SDValue X; 4269 if (Add0C->getZExtValue() % Size == 0) 4270 X = Add1; 4271 else if (ShiftAmt.hasOneUse() && Size == 64 && 4272 Add0C->getZExtValue() % 32 == 0) { 4273 // We have a 64-bit shift by (n*32-x), turn it into -(x+n*32). 4274 // This is mainly beneficial if we already compute (x+n*32). 4275 if (Add1.getOpcode() == ISD::TRUNCATE) { 4276 Add1 = Add1.getOperand(0); 4277 SubVT = Add1.getValueType(); 4278 } 4279 if (Add0.getValueType() != SubVT) { 4280 Add0 = CurDAG->getZExtOrTrunc(Add0, DL, SubVT); 4281 insertDAGNode(*CurDAG, OrigShiftAmt, Add0); 4282 } 4283 4284 X = CurDAG->getNode(ISD::ADD, DL, SubVT, Add1, Add0); 4285 insertDAGNode(*CurDAG, OrigShiftAmt, X); 4286 } else 4287 return false; 4288 // Insert a negate op. 4289 // TODO: This isn't guaranteed to replace the sub if there is a logic cone 4290 // that uses it that's not a shift. 4291 SDValue Zero = CurDAG->getConstant(0, DL, SubVT); 4292 SDValue Neg = CurDAG->getNode(ISD::SUB, DL, SubVT, Zero, X); 4293 NewShiftAmt = Neg; 4294 4295 // Insert these operands into a valid topological order so they can 4296 // get selected independently. 4297 insertDAGNode(*CurDAG, OrigShiftAmt, Zero); 4298 insertDAGNode(*CurDAG, OrigShiftAmt, Neg); 4299 } else 4300 return false; 4301 } else 4302 return false; 4303 4304 if (NewShiftAmt.getValueType() != MVT::i8) { 4305 // Need to truncate the shift amount. 4306 NewShiftAmt = CurDAG->getNode(ISD::TRUNCATE, DL, MVT::i8, NewShiftAmt); 4307 // Add to a correct topological ordering. 4308 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt); 4309 } 4310 4311 // Insert a new mask to keep the shift amount legal. This should be removed 4312 // by isel patterns. 4313 NewShiftAmt = CurDAG->getNode(ISD::AND, DL, MVT::i8, NewShiftAmt, 4314 CurDAG->getConstant(Size - 1, DL, MVT::i8)); 4315 // Place in a correct topological ordering. 4316 insertDAGNode(*CurDAG, OrigShiftAmt, NewShiftAmt); 4317 4318 SDNode *UpdatedNode = CurDAG->UpdateNodeOperands(N, N->getOperand(0), 4319 NewShiftAmt); 4320 if (UpdatedNode != N) { 4321 // If we found an existing node, we should replace ourselves with that node 4322 // and wait for it to be selected after its other users. 4323 ReplaceNode(N, UpdatedNode); 4324 return true; 4325 } 4326 4327 // If the original shift amount is now dead, delete it so that we don't run 4328 // it through isel. 4329 if (OrigShiftAmt.getNode()->use_empty()) 4330 CurDAG->RemoveDeadNode(OrigShiftAmt.getNode()); 4331 4332 // Now that we've optimized the shift amount, defer to normal isel to get 4333 // load folding and legacy vs BMI2 selection without repeating it here. 4334 SelectCode(N); 4335 return true; 4336 } 4337 4338 bool X86DAGToDAGISel::tryShrinkShlLogicImm(SDNode *N) { 4339 MVT NVT = N->getSimpleValueType(0); 4340 unsigned Opcode = N->getOpcode(); 4341 SDLoc dl(N); 4342 4343 // For operations of the form (x << C1) op C2, check if we can use a smaller 4344 // encoding for C2 by transforming it into (x op (C2>>C1)) << C1. 4345 SDValue Shift = N->getOperand(0); 4346 SDValue N1 = N->getOperand(1); 4347 4348 auto *Cst = dyn_cast<ConstantSDNode>(N1); 4349 if (!Cst) 4350 return false; 4351 4352 int64_t Val = Cst->getSExtValue(); 4353 4354 // If we have an any_extend feeding the AND, look through it to see if there 4355 // is a shift behind it. But only if the AND doesn't use the extended bits. 4356 // FIXME: Generalize this to other ANY_EXTEND than i32 to i64? 4357 bool FoundAnyExtend = false; 4358 if (Shift.getOpcode() == ISD::ANY_EXTEND && Shift.hasOneUse() && 4359 Shift.getOperand(0).getSimpleValueType() == MVT::i32 && 4360 isUInt<32>(Val)) { 4361 FoundAnyExtend = true; 4362 Shift = Shift.getOperand(0); 4363 } 4364 4365 if (Shift.getOpcode() != ISD::SHL || !Shift.hasOneUse()) 4366 return false; 4367 4368 // i8 is unshrinkable, i16 should be promoted to i32. 4369 if (NVT != MVT::i32 && NVT != MVT::i64) 4370 return false; 4371 4372 auto *ShlCst = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 4373 if (!ShlCst) 4374 return false; 4375 4376 uint64_t ShAmt = ShlCst->getZExtValue(); 4377 4378 // Make sure that we don't change the operation by removing bits. 4379 // This only matters for OR and XOR, AND is unaffected. 4380 uint64_t RemovedBitsMask = (1ULL << ShAmt) - 1; 4381 if (Opcode != ISD::AND && (Val & RemovedBitsMask) != 0) 4382 return false; 4383 4384 // Check the minimum bitwidth for the new constant. 4385 // TODO: Using 16 and 8 bit operations is also possible for or32 & xor32. 4386 auto CanShrinkImmediate = [&](int64_t &ShiftedVal) { 4387 if (Opcode == ISD::AND) { 4388 // AND32ri is the same as AND64ri32 with zext imm. 4389 // Try this before sign extended immediates below. 4390 ShiftedVal = (uint64_t)Val >> ShAmt; 4391 if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal)) 4392 return true; 4393 // Also swap order when the AND can become MOVZX. 4394 if (ShiftedVal == UINT8_MAX || ShiftedVal == UINT16_MAX) 4395 return true; 4396 } 4397 ShiftedVal = Val >> ShAmt; 4398 if ((!isInt<8>(Val) && isInt<8>(ShiftedVal)) || 4399 (!isInt<32>(Val) && isInt<32>(ShiftedVal))) 4400 return true; 4401 if (Opcode != ISD::AND) { 4402 // MOV32ri+OR64r/XOR64r is cheaper than MOV64ri64+OR64rr/XOR64rr 4403 ShiftedVal = (uint64_t)Val >> ShAmt; 4404 if (NVT == MVT::i64 && !isUInt<32>(Val) && isUInt<32>(ShiftedVal)) 4405 return true; 4406 } 4407 return false; 4408 }; 4409 4410 int64_t ShiftedVal; 4411 if (!CanShrinkImmediate(ShiftedVal)) 4412 return false; 4413 4414 // Ok, we can reorder to get a smaller immediate. 4415 4416 // But, its possible the original immediate allowed an AND to become MOVZX. 4417 // Doing this late due to avoid the MakedValueIsZero call as late as 4418 // possible. 4419 if (Opcode == ISD::AND) { 4420 // Find the smallest zext this could possibly be. 4421 unsigned ZExtWidth = Cst->getAPIntValue().getActiveBits(); 4422 ZExtWidth = llvm::bit_ceil(std::max(ZExtWidth, 8U)); 4423 4424 // Figure out which bits need to be zero to achieve that mask. 4425 APInt NeededMask = APInt::getLowBitsSet(NVT.getSizeInBits(), 4426 ZExtWidth); 4427 NeededMask &= ~Cst->getAPIntValue(); 4428 4429 if (CurDAG->MaskedValueIsZero(N->getOperand(0), NeededMask)) 4430 return false; 4431 } 4432 4433 SDValue X = Shift.getOperand(0); 4434 if (FoundAnyExtend) { 4435 SDValue NewX = CurDAG->getNode(ISD::ANY_EXTEND, dl, NVT, X); 4436 insertDAGNode(*CurDAG, SDValue(N, 0), NewX); 4437 X = NewX; 4438 } 4439 4440 SDValue NewCst = CurDAG->getConstant(ShiftedVal, dl, NVT); 4441 insertDAGNode(*CurDAG, SDValue(N, 0), NewCst); 4442 SDValue NewBinOp = CurDAG->getNode(Opcode, dl, NVT, X, NewCst); 4443 insertDAGNode(*CurDAG, SDValue(N, 0), NewBinOp); 4444 SDValue NewSHL = CurDAG->getNode(ISD::SHL, dl, NVT, NewBinOp, 4445 Shift.getOperand(1)); 4446 ReplaceNode(N, NewSHL.getNode()); 4447 SelectCode(NewSHL.getNode()); 4448 return true; 4449 } 4450 4451 bool X86DAGToDAGISel::matchVPTERNLOG(SDNode *Root, SDNode *ParentA, 4452 SDNode *ParentB, SDNode *ParentC, 4453 SDValue A, SDValue B, SDValue C, 4454 uint8_t Imm) { 4455 assert(A.isOperandOf(ParentA) && B.isOperandOf(ParentB) && 4456 C.isOperandOf(ParentC) && "Incorrect parent node"); 4457 4458 auto tryFoldLoadOrBCast = 4459 [this](SDNode *Root, SDNode *P, SDValue &L, SDValue &Base, SDValue &Scale, 4460 SDValue &Index, SDValue &Disp, SDValue &Segment) { 4461 if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment)) 4462 return true; 4463 4464 // Not a load, check for broadcast which may be behind a bitcast. 4465 if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) { 4466 P = L.getNode(); 4467 L = L.getOperand(0); 4468 } 4469 4470 if (L.getOpcode() != X86ISD::VBROADCAST_LOAD) 4471 return false; 4472 4473 // Only 32 and 64 bit broadcasts are supported. 4474 auto *MemIntr = cast<MemIntrinsicSDNode>(L); 4475 unsigned Size = MemIntr->getMemoryVT().getSizeInBits(); 4476 if (Size != 32 && Size != 64) 4477 return false; 4478 4479 return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment); 4480 }; 4481 4482 bool FoldedLoad = false; 4483 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 4484 if (tryFoldLoadOrBCast(Root, ParentC, C, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { 4485 FoldedLoad = true; 4486 } else if (tryFoldLoadOrBCast(Root, ParentA, A, Tmp0, Tmp1, Tmp2, Tmp3, 4487 Tmp4)) { 4488 FoldedLoad = true; 4489 std::swap(A, C); 4490 // Swap bits 1/4 and 3/6. 4491 uint8_t OldImm = Imm; 4492 Imm = OldImm & 0xa5; 4493 if (OldImm & 0x02) Imm |= 0x10; 4494 if (OldImm & 0x10) Imm |= 0x02; 4495 if (OldImm & 0x08) Imm |= 0x40; 4496 if (OldImm & 0x40) Imm |= 0x08; 4497 } else if (tryFoldLoadOrBCast(Root, ParentB, B, Tmp0, Tmp1, Tmp2, Tmp3, 4498 Tmp4)) { 4499 FoldedLoad = true; 4500 std::swap(B, C); 4501 // Swap bits 1/2 and 5/6. 4502 uint8_t OldImm = Imm; 4503 Imm = OldImm & 0x99; 4504 if (OldImm & 0x02) Imm |= 0x04; 4505 if (OldImm & 0x04) Imm |= 0x02; 4506 if (OldImm & 0x20) Imm |= 0x40; 4507 if (OldImm & 0x40) Imm |= 0x20; 4508 } 4509 4510 SDLoc DL(Root); 4511 4512 SDValue TImm = CurDAG->getTargetConstant(Imm, DL, MVT::i8); 4513 4514 MVT NVT = Root->getSimpleValueType(0); 4515 4516 MachineSDNode *MNode; 4517 if (FoldedLoad) { 4518 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other); 4519 4520 unsigned Opc; 4521 if (C.getOpcode() == X86ISD::VBROADCAST_LOAD) { 4522 auto *MemIntr = cast<MemIntrinsicSDNode>(C); 4523 unsigned EltSize = MemIntr->getMemoryVT().getSizeInBits(); 4524 assert((EltSize == 32 || EltSize == 64) && "Unexpected broadcast size!"); 4525 4526 bool UseD = EltSize == 32; 4527 if (NVT.is128BitVector()) 4528 Opc = UseD ? X86::VPTERNLOGDZ128rmbi : X86::VPTERNLOGQZ128rmbi; 4529 else if (NVT.is256BitVector()) 4530 Opc = UseD ? X86::VPTERNLOGDZ256rmbi : X86::VPTERNLOGQZ256rmbi; 4531 else if (NVT.is512BitVector()) 4532 Opc = UseD ? X86::VPTERNLOGDZrmbi : X86::VPTERNLOGQZrmbi; 4533 else 4534 llvm_unreachable("Unexpected vector size!"); 4535 } else { 4536 bool UseD = NVT.getVectorElementType() == MVT::i32; 4537 if (NVT.is128BitVector()) 4538 Opc = UseD ? X86::VPTERNLOGDZ128rmi : X86::VPTERNLOGQZ128rmi; 4539 else if (NVT.is256BitVector()) 4540 Opc = UseD ? X86::VPTERNLOGDZ256rmi : X86::VPTERNLOGQZ256rmi; 4541 else if (NVT.is512BitVector()) 4542 Opc = UseD ? X86::VPTERNLOGDZrmi : X86::VPTERNLOGQZrmi; 4543 else 4544 llvm_unreachable("Unexpected vector size!"); 4545 } 4546 4547 SDValue Ops[] = {A, B, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, TImm, C.getOperand(0)}; 4548 MNode = CurDAG->getMachineNode(Opc, DL, VTs, Ops); 4549 4550 // Update the chain. 4551 ReplaceUses(C.getValue(1), SDValue(MNode, 1)); 4552 // Record the mem-refs 4553 CurDAG->setNodeMemRefs(MNode, {cast<MemSDNode>(C)->getMemOperand()}); 4554 } else { 4555 bool UseD = NVT.getVectorElementType() == MVT::i32; 4556 unsigned Opc; 4557 if (NVT.is128BitVector()) 4558 Opc = UseD ? X86::VPTERNLOGDZ128rri : X86::VPTERNLOGQZ128rri; 4559 else if (NVT.is256BitVector()) 4560 Opc = UseD ? X86::VPTERNLOGDZ256rri : X86::VPTERNLOGQZ256rri; 4561 else if (NVT.is512BitVector()) 4562 Opc = UseD ? X86::VPTERNLOGDZrri : X86::VPTERNLOGQZrri; 4563 else 4564 llvm_unreachable("Unexpected vector size!"); 4565 4566 MNode = CurDAG->getMachineNode(Opc, DL, NVT, {A, B, C, TImm}); 4567 } 4568 4569 ReplaceUses(SDValue(Root, 0), SDValue(MNode, 0)); 4570 CurDAG->RemoveDeadNode(Root); 4571 return true; 4572 } 4573 4574 // Try to match two logic ops to a VPTERNLOG. 4575 // FIXME: Handle more complex patterns that use an operand more than once? 4576 bool X86DAGToDAGISel::tryVPTERNLOG(SDNode *N) { 4577 MVT NVT = N->getSimpleValueType(0); 4578 4579 // Make sure we support VPTERNLOG. 4580 if (!NVT.isVector() || !Subtarget->hasAVX512() || 4581 NVT.getVectorElementType() == MVT::i1) 4582 return false; 4583 4584 // We need VLX for 128/256-bit. 4585 if (!(Subtarget->hasVLX() || NVT.is512BitVector())) 4586 return false; 4587 4588 SDValue N0 = N->getOperand(0); 4589 SDValue N1 = N->getOperand(1); 4590 4591 auto getFoldableLogicOp = [](SDValue Op) { 4592 // Peek through single use bitcast. 4593 if (Op.getOpcode() == ISD::BITCAST && Op.hasOneUse()) 4594 Op = Op.getOperand(0); 4595 4596 if (!Op.hasOneUse()) 4597 return SDValue(); 4598 4599 unsigned Opc = Op.getOpcode(); 4600 if (Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR || 4601 Opc == X86ISD::ANDNP) 4602 return Op; 4603 4604 return SDValue(); 4605 }; 4606 4607 SDValue A, FoldableOp; 4608 if ((FoldableOp = getFoldableLogicOp(N1))) { 4609 A = N0; 4610 } else if ((FoldableOp = getFoldableLogicOp(N0))) { 4611 A = N1; 4612 } else 4613 return false; 4614 4615 SDValue B = FoldableOp.getOperand(0); 4616 SDValue C = FoldableOp.getOperand(1); 4617 SDNode *ParentA = N; 4618 SDNode *ParentB = FoldableOp.getNode(); 4619 SDNode *ParentC = FoldableOp.getNode(); 4620 4621 // We can build the appropriate control immediate by performing the logic 4622 // operation we're matching using these constants for A, B, and C. 4623 uint8_t TernlogMagicA = 0xf0; 4624 uint8_t TernlogMagicB = 0xcc; 4625 uint8_t TernlogMagicC = 0xaa; 4626 4627 // Some of the inputs may be inverted, peek through them and invert the 4628 // magic values accordingly. 4629 // TODO: There may be a bitcast before the xor that we should peek through. 4630 auto PeekThroughNot = [](SDValue &Op, SDNode *&Parent, uint8_t &Magic) { 4631 if (Op.getOpcode() == ISD::XOR && Op.hasOneUse() && 4632 ISD::isBuildVectorAllOnes(Op.getOperand(1).getNode())) { 4633 Magic = ~Magic; 4634 Parent = Op.getNode(); 4635 Op = Op.getOperand(0); 4636 } 4637 }; 4638 4639 PeekThroughNot(A, ParentA, TernlogMagicA); 4640 PeekThroughNot(B, ParentB, TernlogMagicB); 4641 PeekThroughNot(C, ParentC, TernlogMagicC); 4642 4643 uint8_t Imm; 4644 switch (FoldableOp.getOpcode()) { 4645 default: llvm_unreachable("Unexpected opcode!"); 4646 case ISD::AND: Imm = TernlogMagicB & TernlogMagicC; break; 4647 case ISD::OR: Imm = TernlogMagicB | TernlogMagicC; break; 4648 case ISD::XOR: Imm = TernlogMagicB ^ TernlogMagicC; break; 4649 case X86ISD::ANDNP: Imm = ~(TernlogMagicB) & TernlogMagicC; break; 4650 } 4651 4652 switch (N->getOpcode()) { 4653 default: llvm_unreachable("Unexpected opcode!"); 4654 case X86ISD::ANDNP: 4655 if (A == N0) 4656 Imm &= ~TernlogMagicA; 4657 else 4658 Imm = ~(Imm) & TernlogMagicA; 4659 break; 4660 case ISD::AND: Imm &= TernlogMagicA; break; 4661 case ISD::OR: Imm |= TernlogMagicA; break; 4662 case ISD::XOR: Imm ^= TernlogMagicA; break; 4663 } 4664 4665 return matchVPTERNLOG(N, ParentA, ParentB, ParentC, A, B, C, Imm); 4666 } 4667 4668 /// If the high bits of an 'and' operand are known zero, try setting the 4669 /// high bits of an 'and' constant operand to produce a smaller encoding by 4670 /// creating a small, sign-extended negative immediate rather than a large 4671 /// positive one. This reverses a transform in SimplifyDemandedBits that 4672 /// shrinks mask constants by clearing bits. There is also a possibility that 4673 /// the 'and' mask can be made -1, so the 'and' itself is unnecessary. In that 4674 /// case, just replace the 'and'. Return 'true' if the node is replaced. 4675 bool X86DAGToDAGISel::shrinkAndImmediate(SDNode *And) { 4676 // i8 is unshrinkable, i16 should be promoted to i32, and vector ops don't 4677 // have immediate operands. 4678 MVT VT = And->getSimpleValueType(0); 4679 if (VT != MVT::i32 && VT != MVT::i64) 4680 return false; 4681 4682 auto *And1C = dyn_cast<ConstantSDNode>(And->getOperand(1)); 4683 if (!And1C) 4684 return false; 4685 4686 // Bail out if the mask constant is already negative. It's can't shrink more. 4687 // If the upper 32 bits of a 64 bit mask are all zeros, we have special isel 4688 // patterns to use a 32-bit and instead of a 64-bit and by relying on the 4689 // implicit zeroing of 32 bit ops. So we should check if the lower 32 bits 4690 // are negative too. 4691 APInt MaskVal = And1C->getAPIntValue(); 4692 unsigned MaskLZ = MaskVal.countl_zero(); 4693 if (!MaskLZ || (VT == MVT::i64 && MaskLZ == 32)) 4694 return false; 4695 4696 // Don't extend into the upper 32 bits of a 64 bit mask. 4697 if (VT == MVT::i64 && MaskLZ >= 32) { 4698 MaskLZ -= 32; 4699 MaskVal = MaskVal.trunc(32); 4700 } 4701 4702 SDValue And0 = And->getOperand(0); 4703 APInt HighZeros = APInt::getHighBitsSet(MaskVal.getBitWidth(), MaskLZ); 4704 APInt NegMaskVal = MaskVal | HighZeros; 4705 4706 // If a negative constant would not allow a smaller encoding, there's no need 4707 // to continue. Only change the constant when we know it's a win. 4708 unsigned MinWidth = NegMaskVal.getSignificantBits(); 4709 if (MinWidth > 32 || (MinWidth > 8 && MaskVal.getSignificantBits() <= 32)) 4710 return false; 4711 4712 // Extend masks if we truncated above. 4713 if (VT == MVT::i64 && MaskVal.getBitWidth() < 64) { 4714 NegMaskVal = NegMaskVal.zext(64); 4715 HighZeros = HighZeros.zext(64); 4716 } 4717 4718 // The variable operand must be all zeros in the top bits to allow using the 4719 // new, negative constant as the mask. 4720 if (!CurDAG->MaskedValueIsZero(And0, HighZeros)) 4721 return false; 4722 4723 // Check if the mask is -1. In that case, this is an unnecessary instruction 4724 // that escaped earlier analysis. 4725 if (NegMaskVal.isAllOnes()) { 4726 ReplaceNode(And, And0.getNode()); 4727 return true; 4728 } 4729 4730 // A negative mask allows a smaller encoding. Create a new 'and' node. 4731 SDValue NewMask = CurDAG->getConstant(NegMaskVal, SDLoc(And), VT); 4732 insertDAGNode(*CurDAG, SDValue(And, 0), NewMask); 4733 SDValue NewAnd = CurDAG->getNode(ISD::AND, SDLoc(And), VT, And0, NewMask); 4734 ReplaceNode(And, NewAnd.getNode()); 4735 SelectCode(NewAnd.getNode()); 4736 return true; 4737 } 4738 4739 static unsigned getVPTESTMOpc(MVT TestVT, bool IsTestN, bool FoldedLoad, 4740 bool FoldedBCast, bool Masked) { 4741 #define VPTESTM_CASE(VT, SUFFIX) \ 4742 case MVT::VT: \ 4743 if (Masked) \ 4744 return IsTestN ? X86::VPTESTNM##SUFFIX##k: X86::VPTESTM##SUFFIX##k; \ 4745 return IsTestN ? X86::VPTESTNM##SUFFIX : X86::VPTESTM##SUFFIX; 4746 4747 4748 #define VPTESTM_BROADCAST_CASES(SUFFIX) \ 4749 default: llvm_unreachable("Unexpected VT!"); \ 4750 VPTESTM_CASE(v4i32, DZ128##SUFFIX) \ 4751 VPTESTM_CASE(v2i64, QZ128##SUFFIX) \ 4752 VPTESTM_CASE(v8i32, DZ256##SUFFIX) \ 4753 VPTESTM_CASE(v4i64, QZ256##SUFFIX) \ 4754 VPTESTM_CASE(v16i32, DZ##SUFFIX) \ 4755 VPTESTM_CASE(v8i64, QZ##SUFFIX) 4756 4757 #define VPTESTM_FULL_CASES(SUFFIX) \ 4758 VPTESTM_BROADCAST_CASES(SUFFIX) \ 4759 VPTESTM_CASE(v16i8, BZ128##SUFFIX) \ 4760 VPTESTM_CASE(v8i16, WZ128##SUFFIX) \ 4761 VPTESTM_CASE(v32i8, BZ256##SUFFIX) \ 4762 VPTESTM_CASE(v16i16, WZ256##SUFFIX) \ 4763 VPTESTM_CASE(v64i8, BZ##SUFFIX) \ 4764 VPTESTM_CASE(v32i16, WZ##SUFFIX) 4765 4766 if (FoldedBCast) { 4767 switch (TestVT.SimpleTy) { 4768 VPTESTM_BROADCAST_CASES(rmb) 4769 } 4770 } 4771 4772 if (FoldedLoad) { 4773 switch (TestVT.SimpleTy) { 4774 VPTESTM_FULL_CASES(rm) 4775 } 4776 } 4777 4778 switch (TestVT.SimpleTy) { 4779 VPTESTM_FULL_CASES(rr) 4780 } 4781 4782 #undef VPTESTM_FULL_CASES 4783 #undef VPTESTM_BROADCAST_CASES 4784 #undef VPTESTM_CASE 4785 } 4786 4787 // Try to create VPTESTM instruction. If InMask is not null, it will be used 4788 // to form a masked operation. 4789 bool X86DAGToDAGISel::tryVPTESTM(SDNode *Root, SDValue Setcc, 4790 SDValue InMask) { 4791 assert(Subtarget->hasAVX512() && "Expected AVX512!"); 4792 assert(Setcc.getSimpleValueType().getVectorElementType() == MVT::i1 && 4793 "Unexpected VT!"); 4794 4795 // Look for equal and not equal compares. 4796 ISD::CondCode CC = cast<CondCodeSDNode>(Setcc.getOperand(2))->get(); 4797 if (CC != ISD::SETEQ && CC != ISD::SETNE) 4798 return false; 4799 4800 SDValue SetccOp0 = Setcc.getOperand(0); 4801 SDValue SetccOp1 = Setcc.getOperand(1); 4802 4803 // Canonicalize the all zero vector to the RHS. 4804 if (ISD::isBuildVectorAllZeros(SetccOp0.getNode())) 4805 std::swap(SetccOp0, SetccOp1); 4806 4807 // See if we're comparing against zero. 4808 if (!ISD::isBuildVectorAllZeros(SetccOp1.getNode())) 4809 return false; 4810 4811 SDValue N0 = SetccOp0; 4812 4813 MVT CmpVT = N0.getSimpleValueType(); 4814 MVT CmpSVT = CmpVT.getVectorElementType(); 4815 4816 // Start with both operands the same. We'll try to refine this. 4817 SDValue Src0 = N0; 4818 SDValue Src1 = N0; 4819 4820 { 4821 // Look through single use bitcasts. 4822 SDValue N0Temp = N0; 4823 if (N0Temp.getOpcode() == ISD::BITCAST && N0Temp.hasOneUse()) 4824 N0Temp = N0.getOperand(0); 4825 4826 // Look for single use AND. 4827 if (N0Temp.getOpcode() == ISD::AND && N0Temp.hasOneUse()) { 4828 Src0 = N0Temp.getOperand(0); 4829 Src1 = N0Temp.getOperand(1); 4830 } 4831 } 4832 4833 // Without VLX we need to widen the operation. 4834 bool Widen = !Subtarget->hasVLX() && !CmpVT.is512BitVector(); 4835 4836 auto tryFoldLoadOrBCast = [&](SDNode *Root, SDNode *P, SDValue &L, 4837 SDValue &Base, SDValue &Scale, SDValue &Index, 4838 SDValue &Disp, SDValue &Segment) { 4839 // If we need to widen, we can't fold the load. 4840 if (!Widen) 4841 if (tryFoldLoad(Root, P, L, Base, Scale, Index, Disp, Segment)) 4842 return true; 4843 4844 // If we didn't fold a load, try to match broadcast. No widening limitation 4845 // for this. But only 32 and 64 bit types are supported. 4846 if (CmpSVT != MVT::i32 && CmpSVT != MVT::i64) 4847 return false; 4848 4849 // Look through single use bitcasts. 4850 if (L.getOpcode() == ISD::BITCAST && L.hasOneUse()) { 4851 P = L.getNode(); 4852 L = L.getOperand(0); 4853 } 4854 4855 if (L.getOpcode() != X86ISD::VBROADCAST_LOAD) 4856 return false; 4857 4858 auto *MemIntr = cast<MemIntrinsicSDNode>(L); 4859 if (MemIntr->getMemoryVT().getSizeInBits() != CmpSVT.getSizeInBits()) 4860 return false; 4861 4862 return tryFoldBroadcast(Root, P, L, Base, Scale, Index, Disp, Segment); 4863 }; 4864 4865 // We can only fold loads if the sources are unique. 4866 bool CanFoldLoads = Src0 != Src1; 4867 4868 bool FoldedLoad = false; 4869 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 4870 if (CanFoldLoads) { 4871 FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src1, Tmp0, Tmp1, Tmp2, 4872 Tmp3, Tmp4); 4873 if (!FoldedLoad) { 4874 // And is commutative. 4875 FoldedLoad = tryFoldLoadOrBCast(Root, N0.getNode(), Src0, Tmp0, Tmp1, 4876 Tmp2, Tmp3, Tmp4); 4877 if (FoldedLoad) 4878 std::swap(Src0, Src1); 4879 } 4880 } 4881 4882 bool FoldedBCast = FoldedLoad && Src1.getOpcode() == X86ISD::VBROADCAST_LOAD; 4883 4884 bool IsMasked = InMask.getNode() != nullptr; 4885 4886 SDLoc dl(Root); 4887 4888 MVT ResVT = Setcc.getSimpleValueType(); 4889 MVT MaskVT = ResVT; 4890 if (Widen) { 4891 // Widen the inputs using insert_subreg or copy_to_regclass. 4892 unsigned Scale = CmpVT.is128BitVector() ? 4 : 2; 4893 unsigned SubReg = CmpVT.is128BitVector() ? X86::sub_xmm : X86::sub_ymm; 4894 unsigned NumElts = CmpVT.getVectorNumElements() * Scale; 4895 CmpVT = MVT::getVectorVT(CmpSVT, NumElts); 4896 MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 4897 SDValue ImplDef = SDValue(CurDAG->getMachineNode(X86::IMPLICIT_DEF, dl, 4898 CmpVT), 0); 4899 Src0 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src0); 4900 4901 if (!FoldedBCast) 4902 Src1 = CurDAG->getTargetInsertSubreg(SubReg, dl, CmpVT, ImplDef, Src1); 4903 4904 if (IsMasked) { 4905 // Widen the mask. 4906 unsigned RegClass = TLI->getRegClassFor(MaskVT)->getID(); 4907 SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32); 4908 InMask = SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 4909 dl, MaskVT, InMask, RC), 0); 4910 } 4911 } 4912 4913 bool IsTestN = CC == ISD::SETEQ; 4914 unsigned Opc = getVPTESTMOpc(CmpVT, IsTestN, FoldedLoad, FoldedBCast, 4915 IsMasked); 4916 4917 MachineSDNode *CNode; 4918 if (FoldedLoad) { 4919 SDVTList VTs = CurDAG->getVTList(MaskVT, MVT::Other); 4920 4921 if (IsMasked) { 4922 SDValue Ops[] = { InMask, Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, 4923 Src1.getOperand(0) }; 4924 CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops); 4925 } else { 4926 SDValue Ops[] = { Src0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, 4927 Src1.getOperand(0) }; 4928 CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops); 4929 } 4930 4931 // Update the chain. 4932 ReplaceUses(Src1.getValue(1), SDValue(CNode, 1)); 4933 // Record the mem-refs 4934 CurDAG->setNodeMemRefs(CNode, {cast<MemSDNode>(Src1)->getMemOperand()}); 4935 } else { 4936 if (IsMasked) 4937 CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, InMask, Src0, Src1); 4938 else 4939 CNode = CurDAG->getMachineNode(Opc, dl, MaskVT, Src0, Src1); 4940 } 4941 4942 // If we widened, we need to shrink the mask VT. 4943 if (Widen) { 4944 unsigned RegClass = TLI->getRegClassFor(ResVT)->getID(); 4945 SDValue RC = CurDAG->getTargetConstant(RegClass, dl, MVT::i32); 4946 CNode = CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 4947 dl, ResVT, SDValue(CNode, 0), RC); 4948 } 4949 4950 ReplaceUses(SDValue(Root, 0), SDValue(CNode, 0)); 4951 CurDAG->RemoveDeadNode(Root); 4952 return true; 4953 } 4954 4955 // Try to match the bitselect pattern (or (and A, B), (andn A, C)). Turn it 4956 // into vpternlog. 4957 bool X86DAGToDAGISel::tryMatchBitSelect(SDNode *N) { 4958 assert(N->getOpcode() == ISD::OR && "Unexpected opcode!"); 4959 4960 MVT NVT = N->getSimpleValueType(0); 4961 4962 // Make sure we support VPTERNLOG. 4963 if (!NVT.isVector() || !Subtarget->hasAVX512()) 4964 return false; 4965 4966 // We need VLX for 128/256-bit. 4967 if (!(Subtarget->hasVLX() || NVT.is512BitVector())) 4968 return false; 4969 4970 SDValue N0 = N->getOperand(0); 4971 SDValue N1 = N->getOperand(1); 4972 4973 // Canonicalize AND to LHS. 4974 if (N1.getOpcode() == ISD::AND) 4975 std::swap(N0, N1); 4976 4977 if (N0.getOpcode() != ISD::AND || 4978 N1.getOpcode() != X86ISD::ANDNP || 4979 !N0.hasOneUse() || !N1.hasOneUse()) 4980 return false; 4981 4982 // ANDN is not commutable, use it to pick down A and C. 4983 SDValue A = N1.getOperand(0); 4984 SDValue C = N1.getOperand(1); 4985 4986 // AND is commutable, if one operand matches A, the other operand is B. 4987 // Otherwise this isn't a match. 4988 SDValue B; 4989 if (N0.getOperand(0) == A) 4990 B = N0.getOperand(1); 4991 else if (N0.getOperand(1) == A) 4992 B = N0.getOperand(0); 4993 else 4994 return false; 4995 4996 SDLoc dl(N); 4997 SDValue Imm = CurDAG->getTargetConstant(0xCA, dl, MVT::i8); 4998 SDValue Ternlog = CurDAG->getNode(X86ISD::VPTERNLOG, dl, NVT, A, B, C, Imm); 4999 ReplaceNode(N, Ternlog.getNode()); 5000 5001 return matchVPTERNLOG(Ternlog.getNode(), Ternlog.getNode(), Ternlog.getNode(), 5002 Ternlog.getNode(), A, B, C, 0xCA); 5003 } 5004 5005 void X86DAGToDAGISel::Select(SDNode *Node) { 5006 MVT NVT = Node->getSimpleValueType(0); 5007 unsigned Opcode = Node->getOpcode(); 5008 SDLoc dl(Node); 5009 5010 if (Node->isMachineOpcode()) { 5011 LLVM_DEBUG(dbgs() << "== "; Node->dump(CurDAG); dbgs() << '\n'); 5012 Node->setNodeId(-1); 5013 return; // Already selected. 5014 } 5015 5016 switch (Opcode) { 5017 default: break; 5018 case ISD::INTRINSIC_W_CHAIN: { 5019 unsigned IntNo = Node->getConstantOperandVal(1); 5020 switch (IntNo) { 5021 default: break; 5022 case Intrinsic::x86_encodekey128: 5023 case Intrinsic::x86_encodekey256: { 5024 if (!Subtarget->hasKL()) 5025 break; 5026 5027 unsigned Opcode; 5028 switch (IntNo) { 5029 default: llvm_unreachable("Impossible intrinsic"); 5030 case Intrinsic::x86_encodekey128: Opcode = X86::ENCODEKEY128; break; 5031 case Intrinsic::x86_encodekey256: Opcode = X86::ENCODEKEY256; break; 5032 } 5033 5034 SDValue Chain = Node->getOperand(0); 5035 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(3), 5036 SDValue()); 5037 if (Opcode == X86::ENCODEKEY256) 5038 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(4), 5039 Chain.getValue(1)); 5040 5041 MachineSDNode *Res = CurDAG->getMachineNode( 5042 Opcode, dl, Node->getVTList(), 5043 {Node->getOperand(2), Chain, Chain.getValue(1)}); 5044 ReplaceNode(Node, Res); 5045 return; 5046 } 5047 case Intrinsic::x86_tileloadd64_internal: 5048 case Intrinsic::x86_tileloaddt164_internal: { 5049 if (!Subtarget->hasAMXTILE()) 5050 break; 5051 unsigned Opc = IntNo == Intrinsic::x86_tileloadd64_internal 5052 ? X86::PTILELOADDV 5053 : X86::PTILELOADDT1V; 5054 // _tile_loadd_internal(row, col, buf, STRIDE) 5055 SDValue Base = Node->getOperand(4); 5056 SDValue Scale = getI8Imm(1, dl); 5057 SDValue Index = Node->getOperand(5); 5058 SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32); 5059 SDValue Segment = CurDAG->getRegister(0, MVT::i16); 5060 SDValue Chain = Node->getOperand(0); 5061 MachineSDNode *CNode; 5062 SDValue Ops[] = {Node->getOperand(2), 5063 Node->getOperand(3), 5064 Base, 5065 Scale, 5066 Index, 5067 Disp, 5068 Segment, 5069 Chain}; 5070 CNode = CurDAG->getMachineNode(Opc, dl, {MVT::x86amx, MVT::Other}, Ops); 5071 ReplaceNode(Node, CNode); 5072 return; 5073 } 5074 } 5075 break; 5076 } 5077 case ISD::INTRINSIC_VOID: { 5078 unsigned IntNo = Node->getConstantOperandVal(1); 5079 switch (IntNo) { 5080 default: break; 5081 case Intrinsic::x86_sse3_monitor: 5082 case Intrinsic::x86_monitorx: 5083 case Intrinsic::x86_clzero: { 5084 bool Use64BitPtr = Node->getOperand(2).getValueType() == MVT::i64; 5085 5086 unsigned Opc = 0; 5087 switch (IntNo) { 5088 default: llvm_unreachable("Unexpected intrinsic!"); 5089 case Intrinsic::x86_sse3_monitor: 5090 if (!Subtarget->hasSSE3()) 5091 break; 5092 Opc = Use64BitPtr ? X86::MONITOR64rrr : X86::MONITOR32rrr; 5093 break; 5094 case Intrinsic::x86_monitorx: 5095 if (!Subtarget->hasMWAITX()) 5096 break; 5097 Opc = Use64BitPtr ? X86::MONITORX64rrr : X86::MONITORX32rrr; 5098 break; 5099 case Intrinsic::x86_clzero: 5100 if (!Subtarget->hasCLZERO()) 5101 break; 5102 Opc = Use64BitPtr ? X86::CLZERO64r : X86::CLZERO32r; 5103 break; 5104 } 5105 5106 if (Opc) { 5107 unsigned PtrReg = Use64BitPtr ? X86::RAX : X86::EAX; 5108 SDValue Chain = CurDAG->getCopyToReg(Node->getOperand(0), dl, PtrReg, 5109 Node->getOperand(2), SDValue()); 5110 SDValue InGlue = Chain.getValue(1); 5111 5112 if (IntNo == Intrinsic::x86_sse3_monitor || 5113 IntNo == Intrinsic::x86_monitorx) { 5114 // Copy the other two operands to ECX and EDX. 5115 Chain = CurDAG->getCopyToReg(Chain, dl, X86::ECX, Node->getOperand(3), 5116 InGlue); 5117 InGlue = Chain.getValue(1); 5118 Chain = CurDAG->getCopyToReg(Chain, dl, X86::EDX, Node->getOperand(4), 5119 InGlue); 5120 InGlue = Chain.getValue(1); 5121 } 5122 5123 MachineSDNode *CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, 5124 { Chain, InGlue}); 5125 ReplaceNode(Node, CNode); 5126 return; 5127 } 5128 5129 break; 5130 } 5131 case Intrinsic::x86_tilestored64_internal: { 5132 unsigned Opc = X86::PTILESTOREDV; 5133 // _tile_stored_internal(row, col, buf, STRIDE, c) 5134 SDValue Base = Node->getOperand(4); 5135 SDValue Scale = getI8Imm(1, dl); 5136 SDValue Index = Node->getOperand(5); 5137 SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32); 5138 SDValue Segment = CurDAG->getRegister(0, MVT::i16); 5139 SDValue Chain = Node->getOperand(0); 5140 MachineSDNode *CNode; 5141 SDValue Ops[] = {Node->getOperand(2), 5142 Node->getOperand(3), 5143 Base, 5144 Scale, 5145 Index, 5146 Disp, 5147 Segment, 5148 Node->getOperand(6), 5149 Chain}; 5150 CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops); 5151 ReplaceNode(Node, CNode); 5152 return; 5153 } 5154 case Intrinsic::x86_tileloadd64: 5155 case Intrinsic::x86_tileloaddt164: 5156 case Intrinsic::x86_tilestored64: { 5157 if (!Subtarget->hasAMXTILE()) 5158 break; 5159 unsigned Opc; 5160 switch (IntNo) { 5161 default: llvm_unreachable("Unexpected intrinsic!"); 5162 case Intrinsic::x86_tileloadd64: Opc = X86::PTILELOADD; break; 5163 case Intrinsic::x86_tileloaddt164: Opc = X86::PTILELOADDT1; break; 5164 case Intrinsic::x86_tilestored64: Opc = X86::PTILESTORED; break; 5165 } 5166 // FIXME: Match displacement and scale. 5167 unsigned TIndex = Node->getConstantOperandVal(2); 5168 SDValue TReg = getI8Imm(TIndex, dl); 5169 SDValue Base = Node->getOperand(3); 5170 SDValue Scale = getI8Imm(1, dl); 5171 SDValue Index = Node->getOperand(4); 5172 SDValue Disp = CurDAG->getTargetConstant(0, dl, MVT::i32); 5173 SDValue Segment = CurDAG->getRegister(0, MVT::i16); 5174 SDValue Chain = Node->getOperand(0); 5175 MachineSDNode *CNode; 5176 if (Opc == X86::PTILESTORED) { 5177 SDValue Ops[] = { Base, Scale, Index, Disp, Segment, TReg, Chain }; 5178 CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops); 5179 } else { 5180 SDValue Ops[] = { TReg, Base, Scale, Index, Disp, Segment, Chain }; 5181 CNode = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops); 5182 } 5183 ReplaceNode(Node, CNode); 5184 return; 5185 } 5186 } 5187 break; 5188 } 5189 case ISD::BRIND: 5190 case X86ISD::NT_BRIND: { 5191 if (Subtarget->isTargetNaCl()) 5192 // NaCl has its own pass where jmp %r32 are converted to jmp %r64. We 5193 // leave the instruction alone. 5194 break; 5195 if (Subtarget->isTarget64BitILP32()) { 5196 // Converts a 32-bit register to a 64-bit, zero-extended version of 5197 // it. This is needed because x86-64 can do many things, but jmp %r32 5198 // ain't one of them. 5199 SDValue Target = Node->getOperand(1); 5200 assert(Target.getValueType() == MVT::i32 && "Unexpected VT!"); 5201 SDValue ZextTarget = CurDAG->getZExtOrTrunc(Target, dl, MVT::i64); 5202 SDValue Brind = CurDAG->getNode(Opcode, dl, MVT::Other, 5203 Node->getOperand(0), ZextTarget); 5204 ReplaceNode(Node, Brind.getNode()); 5205 SelectCode(ZextTarget.getNode()); 5206 SelectCode(Brind.getNode()); 5207 return; 5208 } 5209 break; 5210 } 5211 case X86ISD::GlobalBaseReg: 5212 ReplaceNode(Node, getGlobalBaseReg()); 5213 return; 5214 5215 case ISD::BITCAST: 5216 // Just drop all 128/256/512-bit bitcasts. 5217 if (NVT.is512BitVector() || NVT.is256BitVector() || NVT.is128BitVector() || 5218 NVT == MVT::f128) { 5219 ReplaceUses(SDValue(Node, 0), Node->getOperand(0)); 5220 CurDAG->RemoveDeadNode(Node); 5221 return; 5222 } 5223 break; 5224 5225 case ISD::SRL: 5226 if (matchBitExtract(Node)) 5227 return; 5228 [[fallthrough]]; 5229 case ISD::SRA: 5230 case ISD::SHL: 5231 if (tryShiftAmountMod(Node)) 5232 return; 5233 break; 5234 5235 case X86ISD::VPTERNLOG: { 5236 uint8_t Imm = Node->getConstantOperandVal(3); 5237 if (matchVPTERNLOG(Node, Node, Node, Node, Node->getOperand(0), 5238 Node->getOperand(1), Node->getOperand(2), Imm)) 5239 return; 5240 break; 5241 } 5242 5243 case X86ISD::ANDNP: 5244 if (tryVPTERNLOG(Node)) 5245 return; 5246 break; 5247 5248 case ISD::AND: 5249 if (NVT.isVector() && NVT.getVectorElementType() == MVT::i1) { 5250 // Try to form a masked VPTESTM. Operands can be in either order. 5251 SDValue N0 = Node->getOperand(0); 5252 SDValue N1 = Node->getOperand(1); 5253 if (N0.getOpcode() == ISD::SETCC && N0.hasOneUse() && 5254 tryVPTESTM(Node, N0, N1)) 5255 return; 5256 if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse() && 5257 tryVPTESTM(Node, N1, N0)) 5258 return; 5259 } 5260 5261 if (MachineSDNode *NewNode = matchBEXTRFromAndImm(Node)) { 5262 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0)); 5263 CurDAG->RemoveDeadNode(Node); 5264 return; 5265 } 5266 if (matchBitExtract(Node)) 5267 return; 5268 if (AndImmShrink && shrinkAndImmediate(Node)) 5269 return; 5270 5271 [[fallthrough]]; 5272 case ISD::OR: 5273 case ISD::XOR: 5274 if (tryShrinkShlLogicImm(Node)) 5275 return; 5276 if (Opcode == ISD::OR && tryMatchBitSelect(Node)) 5277 return; 5278 if (tryVPTERNLOG(Node)) 5279 return; 5280 5281 [[fallthrough]]; 5282 case ISD::ADD: 5283 if (Opcode == ISD::ADD && matchBitExtract(Node)) 5284 return; 5285 [[fallthrough]]; 5286 case ISD::SUB: { 5287 // Try to avoid folding immediates with multiple uses for optsize. 5288 // This code tries to select to register form directly to avoid going 5289 // through the isel table which might fold the immediate. We can't change 5290 // the patterns on the add/sub/and/or/xor with immediate paterns in the 5291 // tablegen files to check immediate use count without making the patterns 5292 // unavailable to the fast-isel table. 5293 if (!CurDAG->shouldOptForSize()) 5294 break; 5295 5296 // Only handle i8/i16/i32/i64. 5297 if (NVT != MVT::i8 && NVT != MVT::i16 && NVT != MVT::i32 && NVT != MVT::i64) 5298 break; 5299 5300 SDValue N0 = Node->getOperand(0); 5301 SDValue N1 = Node->getOperand(1); 5302 5303 auto *Cst = dyn_cast<ConstantSDNode>(N1); 5304 if (!Cst) 5305 break; 5306 5307 int64_t Val = Cst->getSExtValue(); 5308 5309 // Make sure its an immediate that is considered foldable. 5310 // FIXME: Handle unsigned 32 bit immediates for 64-bit AND. 5311 if (!isInt<8>(Val) && !isInt<32>(Val)) 5312 break; 5313 5314 // If this can match to INC/DEC, let it go. 5315 if (Opcode == ISD::ADD && (Val == 1 || Val == -1)) 5316 break; 5317 5318 // Check if we should avoid folding this immediate. 5319 if (!shouldAvoidImmediateInstFormsForSize(N1.getNode())) 5320 break; 5321 5322 // We should not fold the immediate. So we need a register form instead. 5323 unsigned ROpc, MOpc; 5324 switch (NVT.SimpleTy) { 5325 default: llvm_unreachable("Unexpected VT!"); 5326 case MVT::i8: 5327 switch (Opcode) { 5328 default: llvm_unreachable("Unexpected opcode!"); 5329 case ISD::ADD: ROpc = X86::ADD8rr; MOpc = X86::ADD8rm; break; 5330 case ISD::SUB: ROpc = X86::SUB8rr; MOpc = X86::SUB8rm; break; 5331 case ISD::AND: ROpc = X86::AND8rr; MOpc = X86::AND8rm; break; 5332 case ISD::OR: ROpc = X86::OR8rr; MOpc = X86::OR8rm; break; 5333 case ISD::XOR: ROpc = X86::XOR8rr; MOpc = X86::XOR8rm; break; 5334 } 5335 break; 5336 case MVT::i16: 5337 switch (Opcode) { 5338 default: llvm_unreachable("Unexpected opcode!"); 5339 case ISD::ADD: ROpc = X86::ADD16rr; MOpc = X86::ADD16rm; break; 5340 case ISD::SUB: ROpc = X86::SUB16rr; MOpc = X86::SUB16rm; break; 5341 case ISD::AND: ROpc = X86::AND16rr; MOpc = X86::AND16rm; break; 5342 case ISD::OR: ROpc = X86::OR16rr; MOpc = X86::OR16rm; break; 5343 case ISD::XOR: ROpc = X86::XOR16rr; MOpc = X86::XOR16rm; break; 5344 } 5345 break; 5346 case MVT::i32: 5347 switch (Opcode) { 5348 default: llvm_unreachable("Unexpected opcode!"); 5349 case ISD::ADD: ROpc = X86::ADD32rr; MOpc = X86::ADD32rm; break; 5350 case ISD::SUB: ROpc = X86::SUB32rr; MOpc = X86::SUB32rm; break; 5351 case ISD::AND: ROpc = X86::AND32rr; MOpc = X86::AND32rm; break; 5352 case ISD::OR: ROpc = X86::OR32rr; MOpc = X86::OR32rm; break; 5353 case ISD::XOR: ROpc = X86::XOR32rr; MOpc = X86::XOR32rm; break; 5354 } 5355 break; 5356 case MVT::i64: 5357 switch (Opcode) { 5358 default: llvm_unreachable("Unexpected opcode!"); 5359 case ISD::ADD: ROpc = X86::ADD64rr; MOpc = X86::ADD64rm; break; 5360 case ISD::SUB: ROpc = X86::SUB64rr; MOpc = X86::SUB64rm; break; 5361 case ISD::AND: ROpc = X86::AND64rr; MOpc = X86::AND64rm; break; 5362 case ISD::OR: ROpc = X86::OR64rr; MOpc = X86::OR64rm; break; 5363 case ISD::XOR: ROpc = X86::XOR64rr; MOpc = X86::XOR64rm; break; 5364 } 5365 break; 5366 } 5367 5368 // Ok this is a AND/OR/XOR/ADD/SUB with constant. 5369 5370 // If this is a not a subtract, we can still try to fold a load. 5371 if (Opcode != ISD::SUB) { 5372 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 5373 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { 5374 SDValue Ops[] = { N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) }; 5375 SDVTList VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other); 5376 MachineSDNode *CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); 5377 // Update the chain. 5378 ReplaceUses(N0.getValue(1), SDValue(CNode, 2)); 5379 // Record the mem-refs 5380 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N0)->getMemOperand()}); 5381 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0)); 5382 CurDAG->RemoveDeadNode(Node); 5383 return; 5384 } 5385 } 5386 5387 CurDAG->SelectNodeTo(Node, ROpc, NVT, MVT::i32, N0, N1); 5388 return; 5389 } 5390 5391 case X86ISD::SMUL: 5392 // i16/i32/i64 are handled with isel patterns. 5393 if (NVT != MVT::i8) 5394 break; 5395 [[fallthrough]]; 5396 case X86ISD::UMUL: { 5397 SDValue N0 = Node->getOperand(0); 5398 SDValue N1 = Node->getOperand(1); 5399 5400 unsigned LoReg, ROpc, MOpc; 5401 switch (NVT.SimpleTy) { 5402 default: llvm_unreachable("Unsupported VT!"); 5403 case MVT::i8: 5404 LoReg = X86::AL; 5405 ROpc = Opcode == X86ISD::SMUL ? X86::IMUL8r : X86::MUL8r; 5406 MOpc = Opcode == X86ISD::SMUL ? X86::IMUL8m : X86::MUL8m; 5407 break; 5408 case MVT::i16: 5409 LoReg = X86::AX; 5410 ROpc = X86::MUL16r; 5411 MOpc = X86::MUL16m; 5412 break; 5413 case MVT::i32: 5414 LoReg = X86::EAX; 5415 ROpc = X86::MUL32r; 5416 MOpc = X86::MUL32m; 5417 break; 5418 case MVT::i64: 5419 LoReg = X86::RAX; 5420 ROpc = X86::MUL64r; 5421 MOpc = X86::MUL64m; 5422 break; 5423 } 5424 5425 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 5426 bool FoldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); 5427 // Multiply is commutative. 5428 if (!FoldedLoad) { 5429 FoldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); 5430 if (FoldedLoad) 5431 std::swap(N0, N1); 5432 } 5433 5434 SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg, 5435 N0, SDValue()).getValue(1); 5436 5437 MachineSDNode *CNode; 5438 if (FoldedLoad) { 5439 // i16/i32/i64 use an instruction that produces a low and high result even 5440 // though only the low result is used. 5441 SDVTList VTs; 5442 if (NVT == MVT::i8) 5443 VTs = CurDAG->getVTList(NVT, MVT::i32, MVT::Other); 5444 else 5445 VTs = CurDAG->getVTList(NVT, NVT, MVT::i32, MVT::Other); 5446 5447 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0), 5448 InGlue }; 5449 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); 5450 5451 // Update the chain. 5452 ReplaceUses(N1.getValue(1), SDValue(CNode, NVT == MVT::i8 ? 2 : 3)); 5453 // Record the mem-refs 5454 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()}); 5455 } else { 5456 // i16/i32/i64 use an instruction that produces a low and high result even 5457 // though only the low result is used. 5458 SDVTList VTs; 5459 if (NVT == MVT::i8) 5460 VTs = CurDAG->getVTList(NVT, MVT::i32); 5461 else 5462 VTs = CurDAG->getVTList(NVT, NVT, MVT::i32); 5463 5464 CNode = CurDAG->getMachineNode(ROpc, dl, VTs, {N1, InGlue}); 5465 } 5466 5467 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0)); 5468 ReplaceUses(SDValue(Node, 1), SDValue(CNode, NVT == MVT::i8 ? 1 : 2)); 5469 CurDAG->RemoveDeadNode(Node); 5470 return; 5471 } 5472 5473 case ISD::SMUL_LOHI: 5474 case ISD::UMUL_LOHI: { 5475 SDValue N0 = Node->getOperand(0); 5476 SDValue N1 = Node->getOperand(1); 5477 5478 unsigned Opc, MOpc; 5479 unsigned LoReg, HiReg; 5480 bool IsSigned = Opcode == ISD::SMUL_LOHI; 5481 bool UseMULX = !IsSigned && Subtarget->hasBMI2(); 5482 bool UseMULXHi = UseMULX && SDValue(Node, 0).use_empty(); 5483 switch (NVT.SimpleTy) { 5484 default: llvm_unreachable("Unsupported VT!"); 5485 case MVT::i32: 5486 Opc = UseMULXHi ? X86::MULX32Hrr : 5487 UseMULX ? X86::MULX32rr : 5488 IsSigned ? X86::IMUL32r : X86::MUL32r; 5489 MOpc = UseMULXHi ? X86::MULX32Hrm : 5490 UseMULX ? X86::MULX32rm : 5491 IsSigned ? X86::IMUL32m : X86::MUL32m; 5492 LoReg = UseMULX ? X86::EDX : X86::EAX; 5493 HiReg = X86::EDX; 5494 break; 5495 case MVT::i64: 5496 Opc = UseMULXHi ? X86::MULX64Hrr : 5497 UseMULX ? X86::MULX64rr : 5498 IsSigned ? X86::IMUL64r : X86::MUL64r; 5499 MOpc = UseMULXHi ? X86::MULX64Hrm : 5500 UseMULX ? X86::MULX64rm : 5501 IsSigned ? X86::IMUL64m : X86::MUL64m; 5502 LoReg = UseMULX ? X86::RDX : X86::RAX; 5503 HiReg = X86::RDX; 5504 break; 5505 } 5506 5507 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 5508 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); 5509 // Multiply is commutative. 5510 if (!foldedLoad) { 5511 foldedLoad = tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); 5512 if (foldedLoad) 5513 std::swap(N0, N1); 5514 } 5515 5516 SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, LoReg, 5517 N0, SDValue()).getValue(1); 5518 SDValue ResHi, ResLo; 5519 if (foldedLoad) { 5520 SDValue Chain; 5521 MachineSDNode *CNode = nullptr; 5522 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0), 5523 InGlue }; 5524 if (UseMULXHi) { 5525 SDVTList VTs = CurDAG->getVTList(NVT, MVT::Other); 5526 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); 5527 ResHi = SDValue(CNode, 0); 5528 Chain = SDValue(CNode, 1); 5529 } else if (UseMULX) { 5530 SDVTList VTs = CurDAG->getVTList(NVT, NVT, MVT::Other); 5531 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); 5532 ResHi = SDValue(CNode, 0); 5533 ResLo = SDValue(CNode, 1); 5534 Chain = SDValue(CNode, 2); 5535 } else { 5536 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue); 5537 CNode = CurDAG->getMachineNode(MOpc, dl, VTs, Ops); 5538 Chain = SDValue(CNode, 0); 5539 InGlue = SDValue(CNode, 1); 5540 } 5541 5542 // Update the chain. 5543 ReplaceUses(N1.getValue(1), Chain); 5544 // Record the mem-refs 5545 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()}); 5546 } else { 5547 SDValue Ops[] = { N1, InGlue }; 5548 if (UseMULXHi) { 5549 SDVTList VTs = CurDAG->getVTList(NVT); 5550 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops); 5551 ResHi = SDValue(CNode, 0); 5552 } else if (UseMULX) { 5553 SDVTList VTs = CurDAG->getVTList(NVT, NVT); 5554 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops); 5555 ResHi = SDValue(CNode, 0); 5556 ResLo = SDValue(CNode, 1); 5557 } else { 5558 SDVTList VTs = CurDAG->getVTList(MVT::Glue); 5559 SDNode *CNode = CurDAG->getMachineNode(Opc, dl, VTs, Ops); 5560 InGlue = SDValue(CNode, 0); 5561 } 5562 } 5563 5564 // Copy the low half of the result, if it is needed. 5565 if (!SDValue(Node, 0).use_empty()) { 5566 if (!ResLo) { 5567 assert(LoReg && "Register for low half is not defined!"); 5568 ResLo = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, LoReg, 5569 NVT, InGlue); 5570 InGlue = ResLo.getValue(2); 5571 } 5572 ReplaceUses(SDValue(Node, 0), ResLo); 5573 LLVM_DEBUG(dbgs() << "=> "; ResLo.getNode()->dump(CurDAG); 5574 dbgs() << '\n'); 5575 } 5576 // Copy the high half of the result, if it is needed. 5577 if (!SDValue(Node, 1).use_empty()) { 5578 if (!ResHi) { 5579 assert(HiReg && "Register for high half is not defined!"); 5580 ResHi = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, HiReg, 5581 NVT, InGlue); 5582 InGlue = ResHi.getValue(2); 5583 } 5584 ReplaceUses(SDValue(Node, 1), ResHi); 5585 LLVM_DEBUG(dbgs() << "=> "; ResHi.getNode()->dump(CurDAG); 5586 dbgs() << '\n'); 5587 } 5588 5589 CurDAG->RemoveDeadNode(Node); 5590 return; 5591 } 5592 5593 case ISD::SDIVREM: 5594 case ISD::UDIVREM: { 5595 SDValue N0 = Node->getOperand(0); 5596 SDValue N1 = Node->getOperand(1); 5597 5598 unsigned ROpc, MOpc; 5599 bool isSigned = Opcode == ISD::SDIVREM; 5600 if (!isSigned) { 5601 switch (NVT.SimpleTy) { 5602 default: llvm_unreachable("Unsupported VT!"); 5603 case MVT::i8: ROpc = X86::DIV8r; MOpc = X86::DIV8m; break; 5604 case MVT::i16: ROpc = X86::DIV16r; MOpc = X86::DIV16m; break; 5605 case MVT::i32: ROpc = X86::DIV32r; MOpc = X86::DIV32m; break; 5606 case MVT::i64: ROpc = X86::DIV64r; MOpc = X86::DIV64m; break; 5607 } 5608 } else { 5609 switch (NVT.SimpleTy) { 5610 default: llvm_unreachable("Unsupported VT!"); 5611 case MVT::i8: ROpc = X86::IDIV8r; MOpc = X86::IDIV8m; break; 5612 case MVT::i16: ROpc = X86::IDIV16r; MOpc = X86::IDIV16m; break; 5613 case MVT::i32: ROpc = X86::IDIV32r; MOpc = X86::IDIV32m; break; 5614 case MVT::i64: ROpc = X86::IDIV64r; MOpc = X86::IDIV64m; break; 5615 } 5616 } 5617 5618 unsigned LoReg, HiReg, ClrReg; 5619 unsigned SExtOpcode; 5620 switch (NVT.SimpleTy) { 5621 default: llvm_unreachable("Unsupported VT!"); 5622 case MVT::i8: 5623 LoReg = X86::AL; ClrReg = HiReg = X86::AH; 5624 SExtOpcode = 0; // Not used. 5625 break; 5626 case MVT::i16: 5627 LoReg = X86::AX; HiReg = X86::DX; 5628 ClrReg = X86::DX; 5629 SExtOpcode = X86::CWD; 5630 break; 5631 case MVT::i32: 5632 LoReg = X86::EAX; ClrReg = HiReg = X86::EDX; 5633 SExtOpcode = X86::CDQ; 5634 break; 5635 case MVT::i64: 5636 LoReg = X86::RAX; ClrReg = HiReg = X86::RDX; 5637 SExtOpcode = X86::CQO; 5638 break; 5639 } 5640 5641 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 5642 bool foldedLoad = tryFoldLoad(Node, N1, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4); 5643 bool signBitIsZero = CurDAG->SignBitIsZero(N0); 5644 5645 SDValue InGlue; 5646 if (NVT == MVT::i8) { 5647 // Special case for div8, just use a move with zero extension to AX to 5648 // clear the upper 8 bits (AH). 5649 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Chain; 5650 MachineSDNode *Move; 5651 if (tryFoldLoad(Node, N0, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { 5652 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N0.getOperand(0) }; 5653 unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rm8 5654 : X86::MOVZX16rm8; 5655 Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, MVT::Other, Ops); 5656 Chain = SDValue(Move, 1); 5657 ReplaceUses(N0.getValue(1), Chain); 5658 // Record the mem-refs 5659 CurDAG->setNodeMemRefs(Move, {cast<LoadSDNode>(N0)->getMemOperand()}); 5660 } else { 5661 unsigned Opc = (isSigned && !signBitIsZero) ? X86::MOVSX16rr8 5662 : X86::MOVZX16rr8; 5663 Move = CurDAG->getMachineNode(Opc, dl, MVT::i16, N0); 5664 Chain = CurDAG->getEntryNode(); 5665 } 5666 Chain = CurDAG->getCopyToReg(Chain, dl, X86::AX, SDValue(Move, 0), 5667 SDValue()); 5668 InGlue = Chain.getValue(1); 5669 } else { 5670 InGlue = 5671 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, 5672 LoReg, N0, SDValue()).getValue(1); 5673 if (isSigned && !signBitIsZero) { 5674 // Sign extend the low part into the high part. 5675 InGlue = 5676 SDValue(CurDAG->getMachineNode(SExtOpcode, dl, MVT::Glue, InGlue),0); 5677 } else { 5678 // Zero out the high part, effectively zero extending the input. 5679 SDVTList VTs = CurDAG->getVTList(MVT::i32, MVT::i32); 5680 SDValue ClrNode = SDValue( 5681 CurDAG->getMachineNode(X86::MOV32r0, dl, VTs, std::nullopt), 0); 5682 switch (NVT.SimpleTy) { 5683 case MVT::i16: 5684 ClrNode = 5685 SDValue(CurDAG->getMachineNode( 5686 TargetOpcode::EXTRACT_SUBREG, dl, MVT::i16, ClrNode, 5687 CurDAG->getTargetConstant(X86::sub_16bit, dl, 5688 MVT::i32)), 5689 0); 5690 break; 5691 case MVT::i32: 5692 break; 5693 case MVT::i64: 5694 ClrNode = 5695 SDValue(CurDAG->getMachineNode( 5696 TargetOpcode::SUBREG_TO_REG, dl, MVT::i64, 5697 CurDAG->getTargetConstant(0, dl, MVT::i64), ClrNode, 5698 CurDAG->getTargetConstant(X86::sub_32bit, dl, 5699 MVT::i32)), 5700 0); 5701 break; 5702 default: 5703 llvm_unreachable("Unexpected division source"); 5704 } 5705 5706 InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, ClrReg, 5707 ClrNode, InGlue).getValue(1); 5708 } 5709 } 5710 5711 if (foldedLoad) { 5712 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, N1.getOperand(0), 5713 InGlue }; 5714 MachineSDNode *CNode = 5715 CurDAG->getMachineNode(MOpc, dl, MVT::Other, MVT::Glue, Ops); 5716 InGlue = SDValue(CNode, 1); 5717 // Update the chain. 5718 ReplaceUses(N1.getValue(1), SDValue(CNode, 0)); 5719 // Record the mem-refs 5720 CurDAG->setNodeMemRefs(CNode, {cast<LoadSDNode>(N1)->getMemOperand()}); 5721 } else { 5722 InGlue = 5723 SDValue(CurDAG->getMachineNode(ROpc, dl, MVT::Glue, N1, InGlue), 0); 5724 } 5725 5726 // Prevent use of AH in a REX instruction by explicitly copying it to 5727 // an ABCD_L register. 5728 // 5729 // The current assumption of the register allocator is that isel 5730 // won't generate explicit references to the GR8_ABCD_H registers. If 5731 // the allocator and/or the backend get enhanced to be more robust in 5732 // that regard, this can be, and should be, removed. 5733 if (HiReg == X86::AH && !SDValue(Node, 1).use_empty()) { 5734 SDValue AHCopy = CurDAG->getRegister(X86::AH, MVT::i8); 5735 unsigned AHExtOpcode = 5736 isSigned ? X86::MOVSX32rr8_NOREX : X86::MOVZX32rr8_NOREX; 5737 5738 SDNode *RNode = CurDAG->getMachineNode(AHExtOpcode, dl, MVT::i32, 5739 MVT::Glue, AHCopy, InGlue); 5740 SDValue Result(RNode, 0); 5741 InGlue = SDValue(RNode, 1); 5742 5743 Result = 5744 CurDAG->getTargetExtractSubreg(X86::sub_8bit, dl, MVT::i8, Result); 5745 5746 ReplaceUses(SDValue(Node, 1), Result); 5747 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); 5748 dbgs() << '\n'); 5749 } 5750 // Copy the division (low) result, if it is needed. 5751 if (!SDValue(Node, 0).use_empty()) { 5752 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, 5753 LoReg, NVT, InGlue); 5754 InGlue = Result.getValue(2); 5755 ReplaceUses(SDValue(Node, 0), Result); 5756 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); 5757 dbgs() << '\n'); 5758 } 5759 // Copy the remainder (high) result, if it is needed. 5760 if (!SDValue(Node, 1).use_empty()) { 5761 SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl, 5762 HiReg, NVT, InGlue); 5763 InGlue = Result.getValue(2); 5764 ReplaceUses(SDValue(Node, 1), Result); 5765 LLVM_DEBUG(dbgs() << "=> "; Result.getNode()->dump(CurDAG); 5766 dbgs() << '\n'); 5767 } 5768 CurDAG->RemoveDeadNode(Node); 5769 return; 5770 } 5771 5772 case X86ISD::FCMP: 5773 case X86ISD::STRICT_FCMP: 5774 case X86ISD::STRICT_FCMPS: { 5775 bool IsStrictCmp = Node->getOpcode() == X86ISD::STRICT_FCMP || 5776 Node->getOpcode() == X86ISD::STRICT_FCMPS; 5777 SDValue N0 = Node->getOperand(IsStrictCmp ? 1 : 0); 5778 SDValue N1 = Node->getOperand(IsStrictCmp ? 2 : 1); 5779 5780 // Save the original VT of the compare. 5781 MVT CmpVT = N0.getSimpleValueType(); 5782 5783 // Floating point needs special handling if we don't have FCOMI. 5784 if (Subtarget->canUseCMOV()) 5785 break; 5786 5787 bool IsSignaling = Node->getOpcode() == X86ISD::STRICT_FCMPS; 5788 5789 unsigned Opc; 5790 switch (CmpVT.SimpleTy) { 5791 default: llvm_unreachable("Unexpected type!"); 5792 case MVT::f32: 5793 Opc = IsSignaling ? X86::COM_Fpr32 : X86::UCOM_Fpr32; 5794 break; 5795 case MVT::f64: 5796 Opc = IsSignaling ? X86::COM_Fpr64 : X86::UCOM_Fpr64; 5797 break; 5798 case MVT::f80: 5799 Opc = IsSignaling ? X86::COM_Fpr80 : X86::UCOM_Fpr80; 5800 break; 5801 } 5802 5803 SDValue Chain = 5804 IsStrictCmp ? Node->getOperand(0) : CurDAG->getEntryNode(); 5805 SDValue Glue; 5806 if (IsStrictCmp) { 5807 SDVTList VTs = CurDAG->getVTList(MVT::Other, MVT::Glue); 5808 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, VTs, {N0, N1, Chain}), 0); 5809 Glue = Chain.getValue(1); 5810 } else { 5811 Glue = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, N0, N1), 0); 5812 } 5813 5814 // Move FPSW to AX. 5815 SDValue FNSTSW = 5816 SDValue(CurDAG->getMachineNode(X86::FNSTSW16r, dl, MVT::i16, Glue), 0); 5817 5818 // Extract upper 8-bits of AX. 5819 SDValue Extract = 5820 CurDAG->getTargetExtractSubreg(X86::sub_8bit_hi, dl, MVT::i8, FNSTSW); 5821 5822 // Move AH into flags. 5823 // Some 64-bit targets lack SAHF support, but they do support FCOMI. 5824 assert(Subtarget->canUseLAHFSAHF() && 5825 "Target doesn't support SAHF or FCOMI?"); 5826 SDValue AH = CurDAG->getCopyToReg(Chain, dl, X86::AH, Extract, SDValue()); 5827 Chain = AH; 5828 SDValue SAHF = SDValue( 5829 CurDAG->getMachineNode(X86::SAHF, dl, MVT::i32, AH.getValue(1)), 0); 5830 5831 if (IsStrictCmp) 5832 ReplaceUses(SDValue(Node, 1), Chain); 5833 5834 ReplaceUses(SDValue(Node, 0), SAHF); 5835 CurDAG->RemoveDeadNode(Node); 5836 return; 5837 } 5838 5839 case X86ISD::CMP: { 5840 SDValue N0 = Node->getOperand(0); 5841 SDValue N1 = Node->getOperand(1); 5842 5843 // Optimizations for TEST compares. 5844 if (!isNullConstant(N1)) 5845 break; 5846 5847 // Save the original VT of the compare. 5848 MVT CmpVT = N0.getSimpleValueType(); 5849 5850 // If we are comparing (and (shr X, C, Mask) with 0, emit a BEXTR followed 5851 // by a test instruction. The test should be removed later by 5852 // analyzeCompare if we are using only the zero flag. 5853 // TODO: Should we check the users and use the BEXTR flags directly? 5854 if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) { 5855 if (MachineSDNode *NewNode = matchBEXTRFromAndImm(N0.getNode())) { 5856 unsigned TestOpc = CmpVT == MVT::i64 ? X86::TEST64rr 5857 : X86::TEST32rr; 5858 SDValue BEXTR = SDValue(NewNode, 0); 5859 NewNode = CurDAG->getMachineNode(TestOpc, dl, MVT::i32, BEXTR, BEXTR); 5860 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0)); 5861 CurDAG->RemoveDeadNode(Node); 5862 return; 5863 } 5864 } 5865 5866 // We can peek through truncates, but we need to be careful below. 5867 if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse()) 5868 N0 = N0.getOperand(0); 5869 5870 // Look for (X86cmp (and $op, $imm), 0) and see if we can convert it to 5871 // use a smaller encoding. 5872 // Look past the truncate if CMP is the only use of it. 5873 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() && 5874 N0.getValueType() != MVT::i8) { 5875 auto *MaskC = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5876 if (!MaskC) 5877 break; 5878 5879 // We may have looked through a truncate so mask off any bits that 5880 // shouldn't be part of the compare. 5881 uint64_t Mask = MaskC->getZExtValue(); 5882 Mask &= maskTrailingOnes<uint64_t>(CmpVT.getScalarSizeInBits()); 5883 5884 // Check if we can replace AND+IMM{32,64} with a shift. This is possible 5885 // for masks like 0xFF000000 or 0x00FFFFFF and if we care only about the 5886 // zero flag. 5887 if (CmpVT == MVT::i64 && !isInt<8>(Mask) && isShiftedMask_64(Mask) && 5888 onlyUsesZeroFlag(SDValue(Node, 0))) { 5889 unsigned ShiftOpcode = ISD::DELETED_NODE; 5890 unsigned ShiftAmt; 5891 unsigned SubRegIdx; 5892 MVT SubRegVT; 5893 unsigned TestOpcode; 5894 unsigned LeadingZeros = llvm::countl_zero(Mask); 5895 unsigned TrailingZeros = llvm::countr_zero(Mask); 5896 5897 // With leading/trailing zeros, the transform is profitable if we can 5898 // eliminate a movabsq or shrink a 32-bit immediate to 8-bit without 5899 // incurring any extra register moves. 5900 bool SavesBytes = !isInt<32>(Mask) || N0.getOperand(0).hasOneUse(); 5901 if (LeadingZeros == 0 && SavesBytes) { 5902 // If the mask covers the most significant bit, then we can replace 5903 // TEST+AND with a SHR and check eflags. 5904 // This emits a redundant TEST which is subsequently eliminated. 5905 ShiftOpcode = X86::SHR64ri; 5906 ShiftAmt = TrailingZeros; 5907 SubRegIdx = 0; 5908 TestOpcode = X86::TEST64rr; 5909 } else if (TrailingZeros == 0 && SavesBytes) { 5910 // If the mask covers the least significant bit, then we can replace 5911 // TEST+AND with a SHL and check eflags. 5912 // This emits a redundant TEST which is subsequently eliminated. 5913 ShiftOpcode = X86::SHL64ri; 5914 ShiftAmt = LeadingZeros; 5915 SubRegIdx = 0; 5916 TestOpcode = X86::TEST64rr; 5917 } else if (MaskC->hasOneUse() && !isInt<32>(Mask)) { 5918 // If the shifted mask extends into the high half and is 8/16/32 bits 5919 // wide, then replace it with a SHR and a TEST8rr/TEST16rr/TEST32rr. 5920 unsigned PopCount = 64 - LeadingZeros - TrailingZeros; 5921 if (PopCount == 8) { 5922 ShiftOpcode = X86::SHR64ri; 5923 ShiftAmt = TrailingZeros; 5924 SubRegIdx = X86::sub_8bit; 5925 SubRegVT = MVT::i8; 5926 TestOpcode = X86::TEST8rr; 5927 } else if (PopCount == 16) { 5928 ShiftOpcode = X86::SHR64ri; 5929 ShiftAmt = TrailingZeros; 5930 SubRegIdx = X86::sub_16bit; 5931 SubRegVT = MVT::i16; 5932 TestOpcode = X86::TEST16rr; 5933 } else if (PopCount == 32) { 5934 ShiftOpcode = X86::SHR64ri; 5935 ShiftAmt = TrailingZeros; 5936 SubRegIdx = X86::sub_32bit; 5937 SubRegVT = MVT::i32; 5938 TestOpcode = X86::TEST32rr; 5939 } 5940 } 5941 if (ShiftOpcode != ISD::DELETED_NODE) { 5942 SDValue ShiftC = CurDAG->getTargetConstant(ShiftAmt, dl, MVT::i64); 5943 SDValue Shift = SDValue( 5944 CurDAG->getMachineNode(ShiftOpcode, dl, MVT::i64, MVT::i32, 5945 N0.getOperand(0), ShiftC), 5946 0); 5947 if (SubRegIdx != 0) { 5948 Shift = 5949 CurDAG->getTargetExtractSubreg(SubRegIdx, dl, SubRegVT, Shift); 5950 } 5951 MachineSDNode *Test = 5952 CurDAG->getMachineNode(TestOpcode, dl, MVT::i32, Shift, Shift); 5953 ReplaceNode(Node, Test); 5954 return; 5955 } 5956 } 5957 5958 MVT VT; 5959 int SubRegOp; 5960 unsigned ROpc, MOpc; 5961 5962 // For each of these checks we need to be careful if the sign flag is 5963 // being used. It is only safe to use the sign flag in two conditions, 5964 // either the sign bit in the shrunken mask is zero or the final test 5965 // size is equal to the original compare size. 5966 5967 if (isUInt<8>(Mask) && 5968 (!(Mask & 0x80) || CmpVT == MVT::i8 || 5969 hasNoSignFlagUses(SDValue(Node, 0)))) { 5970 // For example, convert "testl %eax, $8" to "testb %al, $8" 5971 VT = MVT::i8; 5972 SubRegOp = X86::sub_8bit; 5973 ROpc = X86::TEST8ri; 5974 MOpc = X86::TEST8mi; 5975 } else if (OptForMinSize && isUInt<16>(Mask) && 5976 (!(Mask & 0x8000) || CmpVT == MVT::i16 || 5977 hasNoSignFlagUses(SDValue(Node, 0)))) { 5978 // For example, "testl %eax, $32776" to "testw %ax, $32776". 5979 // NOTE: We only want to form TESTW instructions if optimizing for 5980 // min size. Otherwise we only save one byte and possibly get a length 5981 // changing prefix penalty in the decoders. 5982 VT = MVT::i16; 5983 SubRegOp = X86::sub_16bit; 5984 ROpc = X86::TEST16ri; 5985 MOpc = X86::TEST16mi; 5986 } else if (isUInt<32>(Mask) && N0.getValueType() != MVT::i16 && 5987 ((!(Mask & 0x80000000) && 5988 // Without minsize 16-bit Cmps can get here so we need to 5989 // be sure we calculate the correct sign flag if needed. 5990 (CmpVT != MVT::i16 || !(Mask & 0x8000))) || 5991 CmpVT == MVT::i32 || 5992 hasNoSignFlagUses(SDValue(Node, 0)))) { 5993 // For example, "testq %rax, $268468232" to "testl %eax, $268468232". 5994 // NOTE: We only want to run that transform if N0 is 32 or 64 bits. 5995 // Otherwize, we find ourselves in a position where we have to do 5996 // promotion. If previous passes did not promote the and, we assume 5997 // they had a good reason not to and do not promote here. 5998 VT = MVT::i32; 5999 SubRegOp = X86::sub_32bit; 6000 ROpc = X86::TEST32ri; 6001 MOpc = X86::TEST32mi; 6002 } else { 6003 // No eligible transformation was found. 6004 break; 6005 } 6006 6007 SDValue Imm = CurDAG->getTargetConstant(Mask, dl, VT); 6008 SDValue Reg = N0.getOperand(0); 6009 6010 // Emit a testl or testw. 6011 MachineSDNode *NewNode; 6012 SDValue Tmp0, Tmp1, Tmp2, Tmp3, Tmp4; 6013 if (tryFoldLoad(Node, N0.getNode(), Reg, Tmp0, Tmp1, Tmp2, Tmp3, Tmp4)) { 6014 if (auto *LoadN = dyn_cast<LoadSDNode>(N0.getOperand(0).getNode())) { 6015 if (!LoadN->isSimple()) { 6016 unsigned NumVolBits = LoadN->getValueType(0).getSizeInBits(); 6017 if ((MOpc == X86::TEST8mi && NumVolBits != 8) || 6018 (MOpc == X86::TEST16mi && NumVolBits != 16) || 6019 (MOpc == X86::TEST32mi && NumVolBits != 32)) 6020 break; 6021 } 6022 } 6023 SDValue Ops[] = { Tmp0, Tmp1, Tmp2, Tmp3, Tmp4, Imm, 6024 Reg.getOperand(0) }; 6025 NewNode = CurDAG->getMachineNode(MOpc, dl, MVT::i32, MVT::Other, Ops); 6026 // Update the chain. 6027 ReplaceUses(Reg.getValue(1), SDValue(NewNode, 1)); 6028 // Record the mem-refs 6029 CurDAG->setNodeMemRefs(NewNode, 6030 {cast<LoadSDNode>(Reg)->getMemOperand()}); 6031 } else { 6032 // Extract the subregister if necessary. 6033 if (N0.getValueType() != VT) 6034 Reg = CurDAG->getTargetExtractSubreg(SubRegOp, dl, VT, Reg); 6035 6036 NewNode = CurDAG->getMachineNode(ROpc, dl, MVT::i32, Reg, Imm); 6037 } 6038 // Replace CMP with TEST. 6039 ReplaceNode(Node, NewNode); 6040 return; 6041 } 6042 break; 6043 } 6044 case X86ISD::PCMPISTR: { 6045 if (!Subtarget->hasSSE42()) 6046 break; 6047 6048 bool NeedIndex = !SDValue(Node, 0).use_empty(); 6049 bool NeedMask = !SDValue(Node, 1).use_empty(); 6050 // We can't fold a load if we are going to make two instructions. 6051 bool MayFoldLoad = !NeedIndex || !NeedMask; 6052 6053 MachineSDNode *CNode; 6054 if (NeedMask) { 6055 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrr : X86::PCMPISTRMrr; 6056 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRMrm : X86::PCMPISTRMrm; 6057 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node); 6058 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0)); 6059 } 6060 if (NeedIndex || !NeedMask) { 6061 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrr : X86::PCMPISTRIrr; 6062 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPISTRIrm : X86::PCMPISTRIrm; 6063 CNode = emitPCMPISTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node); 6064 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0)); 6065 } 6066 6067 // Connect the flag usage to the last instruction created. 6068 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1)); 6069 CurDAG->RemoveDeadNode(Node); 6070 return; 6071 } 6072 case X86ISD::PCMPESTR: { 6073 if (!Subtarget->hasSSE42()) 6074 break; 6075 6076 // Copy the two implicit register inputs. 6077 SDValue InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EAX, 6078 Node->getOperand(1), 6079 SDValue()).getValue(1); 6080 InGlue = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EDX, 6081 Node->getOperand(3), InGlue).getValue(1); 6082 6083 bool NeedIndex = !SDValue(Node, 0).use_empty(); 6084 bool NeedMask = !SDValue(Node, 1).use_empty(); 6085 // We can't fold a load if we are going to make two instructions. 6086 bool MayFoldLoad = !NeedIndex || !NeedMask; 6087 6088 MachineSDNode *CNode; 6089 if (NeedMask) { 6090 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrr : X86::PCMPESTRMrr; 6091 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRMrm : X86::PCMPESTRMrm; 6092 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::v16i8, Node, 6093 InGlue); 6094 ReplaceUses(SDValue(Node, 1), SDValue(CNode, 0)); 6095 } 6096 if (NeedIndex || !NeedMask) { 6097 unsigned ROpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrr : X86::PCMPESTRIrr; 6098 unsigned MOpc = Subtarget->hasAVX() ? X86::VPCMPESTRIrm : X86::PCMPESTRIrm; 6099 CNode = emitPCMPESTR(ROpc, MOpc, MayFoldLoad, dl, MVT::i32, Node, InGlue); 6100 ReplaceUses(SDValue(Node, 0), SDValue(CNode, 0)); 6101 } 6102 // Connect the flag usage to the last instruction created. 6103 ReplaceUses(SDValue(Node, 2), SDValue(CNode, 1)); 6104 CurDAG->RemoveDeadNode(Node); 6105 return; 6106 } 6107 6108 case ISD::SETCC: { 6109 if (NVT.isVector() && tryVPTESTM(Node, SDValue(Node, 0), SDValue())) 6110 return; 6111 6112 break; 6113 } 6114 6115 case ISD::STORE: 6116 if (foldLoadStoreIntoMemOperand(Node)) 6117 return; 6118 break; 6119 6120 case X86ISD::SETCC_CARRY: { 6121 MVT VT = Node->getSimpleValueType(0); 6122 SDValue Result; 6123 if (Subtarget->hasSBBDepBreaking()) { 6124 // We have to do this manually because tblgen will put the eflags copy in 6125 // the wrong place if we use an extract_subreg in the pattern. 6126 // Copy flags to the EFLAGS register and glue it to next node. 6127 SDValue EFLAGS = 6128 CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, X86::EFLAGS, 6129 Node->getOperand(1), SDValue()); 6130 6131 // Create a 64-bit instruction if the result is 64-bits otherwise use the 6132 // 32-bit version. 6133 unsigned Opc = VT == MVT::i64 ? X86::SETB_C64r : X86::SETB_C32r; 6134 MVT SetVT = VT == MVT::i64 ? MVT::i64 : MVT::i32; 6135 Result = SDValue( 6136 CurDAG->getMachineNode(Opc, dl, SetVT, EFLAGS, EFLAGS.getValue(1)), 6137 0); 6138 } else { 6139 // The target does not recognize sbb with the same reg operand as a 6140 // no-source idiom, so we explicitly zero the input values. 6141 Result = getSBBZero(Node); 6142 } 6143 6144 // For less than 32-bits we need to extract from the 32-bit node. 6145 if (VT == MVT::i8 || VT == MVT::i16) { 6146 int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit; 6147 Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result); 6148 } 6149 6150 ReplaceUses(SDValue(Node, 0), Result); 6151 CurDAG->RemoveDeadNode(Node); 6152 return; 6153 } 6154 case X86ISD::SBB: { 6155 if (isNullConstant(Node->getOperand(0)) && 6156 isNullConstant(Node->getOperand(1))) { 6157 SDValue Result = getSBBZero(Node); 6158 6159 // Replace the flag use. 6160 ReplaceUses(SDValue(Node, 1), Result.getValue(1)); 6161 6162 // Replace the result use. 6163 if (!SDValue(Node, 0).use_empty()) { 6164 // For less than 32-bits we need to extract from the 32-bit node. 6165 MVT VT = Node->getSimpleValueType(0); 6166 if (VT == MVT::i8 || VT == MVT::i16) { 6167 int SubIndex = VT == MVT::i16 ? X86::sub_16bit : X86::sub_8bit; 6168 Result = CurDAG->getTargetExtractSubreg(SubIndex, dl, VT, Result); 6169 } 6170 ReplaceUses(SDValue(Node, 0), Result); 6171 } 6172 6173 CurDAG->RemoveDeadNode(Node); 6174 return; 6175 } 6176 break; 6177 } 6178 case X86ISD::MGATHER: { 6179 auto *Mgt = cast<X86MaskedGatherSDNode>(Node); 6180 SDValue IndexOp = Mgt->getIndex(); 6181 SDValue Mask = Mgt->getMask(); 6182 MVT IndexVT = IndexOp.getSimpleValueType(); 6183 MVT ValueVT = Node->getSimpleValueType(0); 6184 MVT MaskVT = Mask.getSimpleValueType(); 6185 6186 // This is just to prevent crashes if the nodes are malformed somehow. We're 6187 // otherwise only doing loose type checking in here based on type what 6188 // a type constraint would say just like table based isel. 6189 if (!ValueVT.isVector() || !MaskVT.isVector()) 6190 break; 6191 6192 unsigned NumElts = ValueVT.getVectorNumElements(); 6193 MVT ValueSVT = ValueVT.getVectorElementType(); 6194 6195 bool IsFP = ValueSVT.isFloatingPoint(); 6196 unsigned EltSize = ValueSVT.getSizeInBits(); 6197 6198 unsigned Opc = 0; 6199 bool AVX512Gather = MaskVT.getVectorElementType() == MVT::i1; 6200 if (AVX512Gather) { 6201 if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32) 6202 Opc = IsFP ? X86::VGATHERDPSZ128rm : X86::VPGATHERDDZ128rm; 6203 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32) 6204 Opc = IsFP ? X86::VGATHERDPSZ256rm : X86::VPGATHERDDZ256rm; 6205 else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32) 6206 Opc = IsFP ? X86::VGATHERDPSZrm : X86::VPGATHERDDZrm; 6207 else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64) 6208 Opc = IsFP ? X86::VGATHERDPDZ128rm : X86::VPGATHERDQZ128rm; 6209 else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64) 6210 Opc = IsFP ? X86::VGATHERDPDZ256rm : X86::VPGATHERDQZ256rm; 6211 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64) 6212 Opc = IsFP ? X86::VGATHERDPDZrm : X86::VPGATHERDQZrm; 6213 else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32) 6214 Opc = IsFP ? X86::VGATHERQPSZ128rm : X86::VPGATHERQDZ128rm; 6215 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32) 6216 Opc = IsFP ? X86::VGATHERQPSZ256rm : X86::VPGATHERQDZ256rm; 6217 else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32) 6218 Opc = IsFP ? X86::VGATHERQPSZrm : X86::VPGATHERQDZrm; 6219 else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64) 6220 Opc = IsFP ? X86::VGATHERQPDZ128rm : X86::VPGATHERQQZ128rm; 6221 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64) 6222 Opc = IsFP ? X86::VGATHERQPDZ256rm : X86::VPGATHERQQZ256rm; 6223 else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64) 6224 Opc = IsFP ? X86::VGATHERQPDZrm : X86::VPGATHERQQZrm; 6225 } else { 6226 assert(EVT(MaskVT) == EVT(ValueVT).changeVectorElementTypeToInteger() && 6227 "Unexpected mask VT!"); 6228 if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32) 6229 Opc = IsFP ? X86::VGATHERDPSrm : X86::VPGATHERDDrm; 6230 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32) 6231 Opc = IsFP ? X86::VGATHERDPSYrm : X86::VPGATHERDDYrm; 6232 else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64) 6233 Opc = IsFP ? X86::VGATHERDPDrm : X86::VPGATHERDQrm; 6234 else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64) 6235 Opc = IsFP ? X86::VGATHERDPDYrm : X86::VPGATHERDQYrm; 6236 else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32) 6237 Opc = IsFP ? X86::VGATHERQPSrm : X86::VPGATHERQDrm; 6238 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32) 6239 Opc = IsFP ? X86::VGATHERQPSYrm : X86::VPGATHERQDYrm; 6240 else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64) 6241 Opc = IsFP ? X86::VGATHERQPDrm : X86::VPGATHERQQrm; 6242 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64) 6243 Opc = IsFP ? X86::VGATHERQPDYrm : X86::VPGATHERQQYrm; 6244 } 6245 6246 if (!Opc) 6247 break; 6248 6249 SDValue Base, Scale, Index, Disp, Segment; 6250 if (!selectVectorAddr(Mgt, Mgt->getBasePtr(), IndexOp, Mgt->getScale(), 6251 Base, Scale, Index, Disp, Segment)) 6252 break; 6253 6254 SDValue PassThru = Mgt->getPassThru(); 6255 SDValue Chain = Mgt->getChain(); 6256 // Gather instructions have a mask output not in the ISD node. 6257 SDVTList VTs = CurDAG->getVTList(ValueVT, MaskVT, MVT::Other); 6258 6259 MachineSDNode *NewNode; 6260 if (AVX512Gather) { 6261 SDValue Ops[] = {PassThru, Mask, Base, Scale, 6262 Index, Disp, Segment, Chain}; 6263 NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops); 6264 } else { 6265 SDValue Ops[] = {PassThru, Base, Scale, Index, 6266 Disp, Segment, Mask, Chain}; 6267 NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops); 6268 } 6269 CurDAG->setNodeMemRefs(NewNode, {Mgt->getMemOperand()}); 6270 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 0)); 6271 ReplaceUses(SDValue(Node, 1), SDValue(NewNode, 2)); 6272 CurDAG->RemoveDeadNode(Node); 6273 return; 6274 } 6275 case X86ISD::MSCATTER: { 6276 auto *Sc = cast<X86MaskedScatterSDNode>(Node); 6277 SDValue Value = Sc->getValue(); 6278 SDValue IndexOp = Sc->getIndex(); 6279 MVT IndexVT = IndexOp.getSimpleValueType(); 6280 MVT ValueVT = Value.getSimpleValueType(); 6281 6282 // This is just to prevent crashes if the nodes are malformed somehow. We're 6283 // otherwise only doing loose type checking in here based on type what 6284 // a type constraint would say just like table based isel. 6285 if (!ValueVT.isVector()) 6286 break; 6287 6288 unsigned NumElts = ValueVT.getVectorNumElements(); 6289 MVT ValueSVT = ValueVT.getVectorElementType(); 6290 6291 bool IsFP = ValueSVT.isFloatingPoint(); 6292 unsigned EltSize = ValueSVT.getSizeInBits(); 6293 6294 unsigned Opc; 6295 if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 32) 6296 Opc = IsFP ? X86::VSCATTERDPSZ128mr : X86::VPSCATTERDDZ128mr; 6297 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 32) 6298 Opc = IsFP ? X86::VSCATTERDPSZ256mr : X86::VPSCATTERDDZ256mr; 6299 else if (IndexVT == MVT::v16i32 && NumElts == 16 && EltSize == 32) 6300 Opc = IsFP ? X86::VSCATTERDPSZmr : X86::VPSCATTERDDZmr; 6301 else if (IndexVT == MVT::v4i32 && NumElts == 2 && EltSize == 64) 6302 Opc = IsFP ? X86::VSCATTERDPDZ128mr : X86::VPSCATTERDQZ128mr; 6303 else if (IndexVT == MVT::v4i32 && NumElts == 4 && EltSize == 64) 6304 Opc = IsFP ? X86::VSCATTERDPDZ256mr : X86::VPSCATTERDQZ256mr; 6305 else if (IndexVT == MVT::v8i32 && NumElts == 8 && EltSize == 64) 6306 Opc = IsFP ? X86::VSCATTERDPDZmr : X86::VPSCATTERDQZmr; 6307 else if (IndexVT == MVT::v2i64 && NumElts == 4 && EltSize == 32) 6308 Opc = IsFP ? X86::VSCATTERQPSZ128mr : X86::VPSCATTERQDZ128mr; 6309 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 32) 6310 Opc = IsFP ? X86::VSCATTERQPSZ256mr : X86::VPSCATTERQDZ256mr; 6311 else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 32) 6312 Opc = IsFP ? X86::VSCATTERQPSZmr : X86::VPSCATTERQDZmr; 6313 else if (IndexVT == MVT::v2i64 && NumElts == 2 && EltSize == 64) 6314 Opc = IsFP ? X86::VSCATTERQPDZ128mr : X86::VPSCATTERQQZ128mr; 6315 else if (IndexVT == MVT::v4i64 && NumElts == 4 && EltSize == 64) 6316 Opc = IsFP ? X86::VSCATTERQPDZ256mr : X86::VPSCATTERQQZ256mr; 6317 else if (IndexVT == MVT::v8i64 && NumElts == 8 && EltSize == 64) 6318 Opc = IsFP ? X86::VSCATTERQPDZmr : X86::VPSCATTERQQZmr; 6319 else 6320 break; 6321 6322 SDValue Base, Scale, Index, Disp, Segment; 6323 if (!selectVectorAddr(Sc, Sc->getBasePtr(), IndexOp, Sc->getScale(), 6324 Base, Scale, Index, Disp, Segment)) 6325 break; 6326 6327 SDValue Mask = Sc->getMask(); 6328 SDValue Chain = Sc->getChain(); 6329 // Scatter instructions have a mask output not in the ISD node. 6330 SDVTList VTs = CurDAG->getVTList(Mask.getValueType(), MVT::Other); 6331 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, Mask, Value, Chain}; 6332 6333 MachineSDNode *NewNode = CurDAG->getMachineNode(Opc, SDLoc(dl), VTs, Ops); 6334 CurDAG->setNodeMemRefs(NewNode, {Sc->getMemOperand()}); 6335 ReplaceUses(SDValue(Node, 0), SDValue(NewNode, 1)); 6336 CurDAG->RemoveDeadNode(Node); 6337 return; 6338 } 6339 case ISD::PREALLOCATED_SETUP: { 6340 auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>(); 6341 auto CallId = MFI->getPreallocatedIdForCallSite( 6342 cast<SrcValueSDNode>(Node->getOperand(1))->getValue()); 6343 SDValue Chain = Node->getOperand(0); 6344 SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32); 6345 MachineSDNode *New = CurDAG->getMachineNode( 6346 TargetOpcode::PREALLOCATED_SETUP, dl, MVT::Other, CallIdValue, Chain); 6347 ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Chain 6348 CurDAG->RemoveDeadNode(Node); 6349 return; 6350 } 6351 case ISD::PREALLOCATED_ARG: { 6352 auto *MFI = CurDAG->getMachineFunction().getInfo<X86MachineFunctionInfo>(); 6353 auto CallId = MFI->getPreallocatedIdForCallSite( 6354 cast<SrcValueSDNode>(Node->getOperand(1))->getValue()); 6355 SDValue Chain = Node->getOperand(0); 6356 SDValue CallIdValue = CurDAG->getTargetConstant(CallId, dl, MVT::i32); 6357 SDValue ArgIndex = Node->getOperand(2); 6358 SDValue Ops[3]; 6359 Ops[0] = CallIdValue; 6360 Ops[1] = ArgIndex; 6361 Ops[2] = Chain; 6362 MachineSDNode *New = CurDAG->getMachineNode( 6363 TargetOpcode::PREALLOCATED_ARG, dl, 6364 CurDAG->getVTList(TLI->getPointerTy(CurDAG->getDataLayout()), 6365 MVT::Other), 6366 Ops); 6367 ReplaceUses(SDValue(Node, 0), SDValue(New, 0)); // Arg pointer 6368 ReplaceUses(SDValue(Node, 1), SDValue(New, 1)); // Chain 6369 CurDAG->RemoveDeadNode(Node); 6370 return; 6371 } 6372 case X86ISD::AESENCWIDE128KL: 6373 case X86ISD::AESDECWIDE128KL: 6374 case X86ISD::AESENCWIDE256KL: 6375 case X86ISD::AESDECWIDE256KL: { 6376 if (!Subtarget->hasWIDEKL()) 6377 break; 6378 6379 unsigned Opcode; 6380 switch (Node->getOpcode()) { 6381 default: 6382 llvm_unreachable("Unexpected opcode!"); 6383 case X86ISD::AESENCWIDE128KL: 6384 Opcode = X86::AESENCWIDE128KL; 6385 break; 6386 case X86ISD::AESDECWIDE128KL: 6387 Opcode = X86::AESDECWIDE128KL; 6388 break; 6389 case X86ISD::AESENCWIDE256KL: 6390 Opcode = X86::AESENCWIDE256KL; 6391 break; 6392 case X86ISD::AESDECWIDE256KL: 6393 Opcode = X86::AESDECWIDE256KL; 6394 break; 6395 } 6396 6397 SDValue Chain = Node->getOperand(0); 6398 SDValue Addr = Node->getOperand(1); 6399 6400 SDValue Base, Scale, Index, Disp, Segment; 6401 if (!selectAddr(Node, Addr, Base, Scale, Index, Disp, Segment)) 6402 break; 6403 6404 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM0, Node->getOperand(2), 6405 SDValue()); 6406 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM1, Node->getOperand(3), 6407 Chain.getValue(1)); 6408 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM2, Node->getOperand(4), 6409 Chain.getValue(1)); 6410 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM3, Node->getOperand(5), 6411 Chain.getValue(1)); 6412 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM4, Node->getOperand(6), 6413 Chain.getValue(1)); 6414 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM5, Node->getOperand(7), 6415 Chain.getValue(1)); 6416 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM6, Node->getOperand(8), 6417 Chain.getValue(1)); 6418 Chain = CurDAG->getCopyToReg(Chain, dl, X86::XMM7, Node->getOperand(9), 6419 Chain.getValue(1)); 6420 6421 MachineSDNode *Res = CurDAG->getMachineNode( 6422 Opcode, dl, Node->getVTList(), 6423 {Base, Scale, Index, Disp, Segment, Chain, Chain.getValue(1)}); 6424 CurDAG->setNodeMemRefs(Res, cast<MemSDNode>(Node)->getMemOperand()); 6425 ReplaceNode(Node, Res); 6426 return; 6427 } 6428 } 6429 6430 SelectCode(Node); 6431 } 6432 6433 bool X86DAGToDAGISel::SelectInlineAsmMemoryOperand( 6434 const SDValue &Op, InlineAsm::ConstraintCode ConstraintID, 6435 std::vector<SDValue> &OutOps) { 6436 SDValue Op0, Op1, Op2, Op3, Op4; 6437 switch (ConstraintID) { 6438 default: 6439 llvm_unreachable("Unexpected asm memory constraint"); 6440 case InlineAsm::ConstraintCode::o: // offsetable ?? 6441 case InlineAsm::ConstraintCode::v: // not offsetable ?? 6442 case InlineAsm::ConstraintCode::m: // memory 6443 case InlineAsm::ConstraintCode::X: 6444 case InlineAsm::ConstraintCode::p: // address 6445 if (!selectAddr(nullptr, Op, Op0, Op1, Op2, Op3, Op4)) 6446 return true; 6447 break; 6448 } 6449 6450 OutOps.push_back(Op0); 6451 OutOps.push_back(Op1); 6452 OutOps.push_back(Op2); 6453 OutOps.push_back(Op3); 6454 OutOps.push_back(Op4); 6455 return false; 6456 } 6457 6458 /// This pass converts a legalized DAG into a X86-specific DAG, 6459 /// ready for instruction scheduling. 6460 FunctionPass *llvm::createX86ISelDag(X86TargetMachine &TM, 6461 CodeGenOptLevel OptLevel) { 6462 return new X86DAGToDAGISel(TM, OptLevel); 6463 } 6464