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