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