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