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