1 //===-- TargetInstrInfo.cpp - Target Instruction Information --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the TargetInstrInfo class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Target/TargetInstrInfo.h" 15 #include "llvm/CodeGen/MachineFrameInfo.h" 16 #include "llvm/CodeGen/MachineInstrBuilder.h" 17 #include "llvm/CodeGen/MachineMemOperand.h" 18 #include "llvm/CodeGen/MachineRegisterInfo.h" 19 #include "llvm/CodeGen/PseudoSourceValue.h" 20 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h" 21 #include "llvm/CodeGen/StackMaps.h" 22 #include "llvm/CodeGen/TargetSchedule.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/MC/MCAsmInfo.h" 25 #include "llvm/MC/MCInstrItineraries.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/raw_ostream.h" 29 #include "llvm/Target/TargetFrameLowering.h" 30 #include "llvm/Target/TargetLowering.h" 31 #include "llvm/Target/TargetMachine.h" 32 #include "llvm/Target/TargetRegisterInfo.h" 33 #include <cctype> 34 35 using namespace llvm; 36 37 static cl::opt<bool> DisableHazardRecognizer( 38 "disable-sched-hazard", cl::Hidden, cl::init(false), 39 cl::desc("Disable hazard detection during preRA scheduling")); 40 41 TargetInstrInfo::~TargetInstrInfo() { 42 } 43 44 const TargetRegisterClass* 45 TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum, 46 const TargetRegisterInfo *TRI, 47 const MachineFunction &MF) const { 48 if (OpNum >= MCID.getNumOperands()) 49 return nullptr; 50 51 short RegClass = MCID.OpInfo[OpNum].RegClass; 52 if (MCID.OpInfo[OpNum].isLookupPtrRegClass()) 53 return TRI->getPointerRegClass(MF, RegClass); 54 55 // Instructions like INSERT_SUBREG do not have fixed register classes. 56 if (RegClass < 0) 57 return nullptr; 58 59 // Otherwise just look it up normally. 60 return TRI->getRegClass(RegClass); 61 } 62 63 /// insertNoop - Insert a noop into the instruction stream at the specified 64 /// point. 65 void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB, 66 MachineBasicBlock::iterator MI) const { 67 llvm_unreachable("Target didn't implement insertNoop!"); 68 } 69 70 static bool isAsmComment(const char *Str, const MCAsmInfo &MAI) { 71 return strncmp(Str, MAI.getCommentString().data(), 72 MAI.getCommentString().size()) == 0; 73 } 74 75 /// Measure the specified inline asm to determine an approximation of its 76 /// length. 77 /// Comments (which run till the next SeparatorString or newline) do not 78 /// count as an instruction. 79 /// Any other non-whitespace text is considered an instruction, with 80 /// multiple instructions separated by SeparatorString or newlines. 81 /// Variable-length instructions are not handled here; this function 82 /// may be overloaded in the target code to do that. 83 /// We implement a special case of the .space directive which takes only a 84 /// single integer argument in base 10 that is the size in bytes. This is a 85 /// restricted form of the GAS directive in that we only interpret 86 /// simple--i.e. not a logical or arithmetic expression--size values without 87 /// the optional fill value. This is primarily used for creating arbitrary 88 /// sized inline asm blocks for testing purposes. 89 unsigned TargetInstrInfo::getInlineAsmLength(const char *Str, 90 const MCAsmInfo &MAI) const { 91 // Count the number of instructions in the asm. 92 bool AtInsnStart = true; 93 unsigned Length = 0; 94 for (; *Str; ++Str) { 95 if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(), 96 strlen(MAI.getSeparatorString())) == 0) { 97 AtInsnStart = true; 98 } else if (isAsmComment(Str, MAI)) { 99 // Stop counting as an instruction after a comment until the next 100 // separator. 101 AtInsnStart = false; 102 } 103 104 if (AtInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) { 105 unsigned AddLength = MAI.getMaxInstLength(); 106 if (strncmp(Str, ".space", 6) == 0) { 107 char *EStr; 108 int SpaceSize; 109 SpaceSize = strtol(Str + 6, &EStr, 10); 110 SpaceSize = SpaceSize < 0 ? 0 : SpaceSize; 111 while (*EStr != '\n' && std::isspace(static_cast<unsigned char>(*EStr))) 112 ++EStr; 113 if (*EStr == '\0' || *EStr == '\n' || 114 isAsmComment(EStr, MAI)) // Successfully parsed .space argument 115 AddLength = SpaceSize; 116 } 117 Length += AddLength; 118 AtInsnStart = false; 119 } 120 } 121 122 return Length; 123 } 124 125 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything 126 /// after it, replacing it with an unconditional branch to NewDest. 127 void 128 TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail, 129 MachineBasicBlock *NewDest) const { 130 MachineBasicBlock *MBB = Tail->getParent(); 131 132 // Remove all the old successors of MBB from the CFG. 133 while (!MBB->succ_empty()) 134 MBB->removeSuccessor(MBB->succ_begin()); 135 136 // Save off the debug loc before erasing the instruction. 137 DebugLoc DL = Tail->getDebugLoc(); 138 139 // Remove all the dead instructions from the end of MBB. 140 MBB->erase(Tail, MBB->end()); 141 142 // If MBB isn't immediately before MBB, insert a branch to it. 143 if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest)) 144 insertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(), DL); 145 MBB->addSuccessor(NewDest); 146 } 147 148 MachineInstr *TargetInstrInfo::commuteInstructionImpl(MachineInstr &MI, 149 bool NewMI, unsigned Idx1, 150 unsigned Idx2) const { 151 const MCInstrDesc &MCID = MI.getDesc(); 152 bool HasDef = MCID.getNumDefs(); 153 if (HasDef && !MI.getOperand(0).isReg()) 154 // No idea how to commute this instruction. Target should implement its own. 155 return nullptr; 156 157 unsigned CommutableOpIdx1 = Idx1; (void)CommutableOpIdx1; 158 unsigned CommutableOpIdx2 = Idx2; (void)CommutableOpIdx2; 159 assert(findCommutedOpIndices(MI, CommutableOpIdx1, CommutableOpIdx2) && 160 CommutableOpIdx1 == Idx1 && CommutableOpIdx2 == Idx2 && 161 "TargetInstrInfo::CommuteInstructionImpl(): not commutable operands."); 162 assert(MI.getOperand(Idx1).isReg() && MI.getOperand(Idx2).isReg() && 163 "This only knows how to commute register operands so far"); 164 165 unsigned Reg0 = HasDef ? MI.getOperand(0).getReg() : 0; 166 unsigned Reg1 = MI.getOperand(Idx1).getReg(); 167 unsigned Reg2 = MI.getOperand(Idx2).getReg(); 168 unsigned SubReg0 = HasDef ? MI.getOperand(0).getSubReg() : 0; 169 unsigned SubReg1 = MI.getOperand(Idx1).getSubReg(); 170 unsigned SubReg2 = MI.getOperand(Idx2).getSubReg(); 171 bool Reg1IsKill = MI.getOperand(Idx1).isKill(); 172 bool Reg2IsKill = MI.getOperand(Idx2).isKill(); 173 bool Reg1IsUndef = MI.getOperand(Idx1).isUndef(); 174 bool Reg2IsUndef = MI.getOperand(Idx2).isUndef(); 175 bool Reg1IsInternal = MI.getOperand(Idx1).isInternalRead(); 176 bool Reg2IsInternal = MI.getOperand(Idx2).isInternalRead(); 177 // If destination is tied to either of the commuted source register, then 178 // it must be updated. 179 if (HasDef && Reg0 == Reg1 && 180 MI.getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) { 181 Reg2IsKill = false; 182 Reg0 = Reg2; 183 SubReg0 = SubReg2; 184 } else if (HasDef && Reg0 == Reg2 && 185 MI.getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) { 186 Reg1IsKill = false; 187 Reg0 = Reg1; 188 SubReg0 = SubReg1; 189 } 190 191 MachineInstr *CommutedMI = nullptr; 192 if (NewMI) { 193 // Create a new instruction. 194 MachineFunction &MF = *MI.getParent()->getParent(); 195 CommutedMI = MF.CloneMachineInstr(&MI); 196 } else { 197 CommutedMI = &MI; 198 } 199 200 if (HasDef) { 201 CommutedMI->getOperand(0).setReg(Reg0); 202 CommutedMI->getOperand(0).setSubReg(SubReg0); 203 } 204 CommutedMI->getOperand(Idx2).setReg(Reg1); 205 CommutedMI->getOperand(Idx1).setReg(Reg2); 206 CommutedMI->getOperand(Idx2).setSubReg(SubReg1); 207 CommutedMI->getOperand(Idx1).setSubReg(SubReg2); 208 CommutedMI->getOperand(Idx2).setIsKill(Reg1IsKill); 209 CommutedMI->getOperand(Idx1).setIsKill(Reg2IsKill); 210 CommutedMI->getOperand(Idx2).setIsUndef(Reg1IsUndef); 211 CommutedMI->getOperand(Idx1).setIsUndef(Reg2IsUndef); 212 CommutedMI->getOperand(Idx2).setIsInternalRead(Reg1IsInternal); 213 CommutedMI->getOperand(Idx1).setIsInternalRead(Reg2IsInternal); 214 return CommutedMI; 215 } 216 217 MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr &MI, bool NewMI, 218 unsigned OpIdx1, 219 unsigned OpIdx2) const { 220 // If OpIdx1 or OpIdx2 is not specified, then this method is free to choose 221 // any commutable operand, which is done in findCommutedOpIndices() method 222 // called below. 223 if ((OpIdx1 == CommuteAnyOperandIndex || OpIdx2 == CommuteAnyOperandIndex) && 224 !findCommutedOpIndices(MI, OpIdx1, OpIdx2)) { 225 assert(MI.isCommutable() && 226 "Precondition violation: MI must be commutable."); 227 return nullptr; 228 } 229 return commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); 230 } 231 232 bool TargetInstrInfo::fixCommutedOpIndices(unsigned &ResultIdx1, 233 unsigned &ResultIdx2, 234 unsigned CommutableOpIdx1, 235 unsigned CommutableOpIdx2) { 236 if (ResultIdx1 == CommuteAnyOperandIndex && 237 ResultIdx2 == CommuteAnyOperandIndex) { 238 ResultIdx1 = CommutableOpIdx1; 239 ResultIdx2 = CommutableOpIdx2; 240 } else if (ResultIdx1 == CommuteAnyOperandIndex) { 241 if (ResultIdx2 == CommutableOpIdx1) 242 ResultIdx1 = CommutableOpIdx2; 243 else if (ResultIdx2 == CommutableOpIdx2) 244 ResultIdx1 = CommutableOpIdx1; 245 else 246 return false; 247 } else if (ResultIdx2 == CommuteAnyOperandIndex) { 248 if (ResultIdx1 == CommutableOpIdx1) 249 ResultIdx2 = CommutableOpIdx2; 250 else if (ResultIdx1 == CommutableOpIdx2) 251 ResultIdx2 = CommutableOpIdx1; 252 else 253 return false; 254 } else 255 // Check that the result operand indices match the given commutable 256 // operand indices. 257 return (ResultIdx1 == CommutableOpIdx1 && ResultIdx2 == CommutableOpIdx2) || 258 (ResultIdx1 == CommutableOpIdx2 && ResultIdx2 == CommutableOpIdx1); 259 260 return true; 261 } 262 263 bool TargetInstrInfo::findCommutedOpIndices(MachineInstr &MI, 264 unsigned &SrcOpIdx1, 265 unsigned &SrcOpIdx2) const { 266 assert(!MI.isBundle() && 267 "TargetInstrInfo::findCommutedOpIndices() can't handle bundles"); 268 269 const MCInstrDesc &MCID = MI.getDesc(); 270 if (!MCID.isCommutable()) 271 return false; 272 273 // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this 274 // is not true, then the target must implement this. 275 unsigned CommutableOpIdx1 = MCID.getNumDefs(); 276 unsigned CommutableOpIdx2 = CommutableOpIdx1 + 1; 277 if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 278 CommutableOpIdx1, CommutableOpIdx2)) 279 return false; 280 281 if (!MI.getOperand(SrcOpIdx1).isReg() || !MI.getOperand(SrcOpIdx2).isReg()) 282 // No idea. 283 return false; 284 return true; 285 } 286 287 bool TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const { 288 if (!MI.isTerminator()) return false; 289 290 // Conditional branch is a special case. 291 if (MI.isBranch() && !MI.isBarrier()) 292 return true; 293 if (!MI.isPredicable()) 294 return true; 295 return !isPredicated(MI); 296 } 297 298 bool TargetInstrInfo::PredicateInstruction( 299 MachineInstr &MI, ArrayRef<MachineOperand> Pred) const { 300 bool MadeChange = false; 301 302 assert(!MI.isBundle() && 303 "TargetInstrInfo::PredicateInstruction() can't handle bundles"); 304 305 const MCInstrDesc &MCID = MI.getDesc(); 306 if (!MI.isPredicable()) 307 return false; 308 309 for (unsigned j = 0, i = 0, e = MI.getNumOperands(); i != e; ++i) { 310 if (MCID.OpInfo[i].isPredicate()) { 311 MachineOperand &MO = MI.getOperand(i); 312 if (MO.isReg()) { 313 MO.setReg(Pred[j].getReg()); 314 MadeChange = true; 315 } else if (MO.isImm()) { 316 MO.setImm(Pred[j].getImm()); 317 MadeChange = true; 318 } else if (MO.isMBB()) { 319 MO.setMBB(Pred[j].getMBB()); 320 MadeChange = true; 321 } 322 ++j; 323 } 324 } 325 return MadeChange; 326 } 327 328 bool TargetInstrInfo::hasLoadFromStackSlot(const MachineInstr &MI, 329 const MachineMemOperand *&MMO, 330 int &FrameIndex) const { 331 for (MachineInstr::mmo_iterator o = MI.memoperands_begin(), 332 oe = MI.memoperands_end(); 333 o != oe; ++o) { 334 if ((*o)->isLoad()) { 335 if (const FixedStackPseudoSourceValue *Value = 336 dyn_cast_or_null<FixedStackPseudoSourceValue>( 337 (*o)->getPseudoValue())) { 338 FrameIndex = Value->getFrameIndex(); 339 MMO = *o; 340 return true; 341 } 342 } 343 } 344 return false; 345 } 346 347 bool TargetInstrInfo::hasStoreToStackSlot(const MachineInstr &MI, 348 const MachineMemOperand *&MMO, 349 int &FrameIndex) const { 350 for (MachineInstr::mmo_iterator o = MI.memoperands_begin(), 351 oe = MI.memoperands_end(); 352 o != oe; ++o) { 353 if ((*o)->isStore()) { 354 if (const FixedStackPseudoSourceValue *Value = 355 dyn_cast_or_null<FixedStackPseudoSourceValue>( 356 (*o)->getPseudoValue())) { 357 FrameIndex = Value->getFrameIndex(); 358 MMO = *o; 359 return true; 360 } 361 } 362 } 363 return false; 364 } 365 366 bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC, 367 unsigned SubIdx, unsigned &Size, 368 unsigned &Offset, 369 const MachineFunction &MF) const { 370 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 371 if (!SubIdx) { 372 Size = TRI->getSpillSize(*RC); 373 Offset = 0; 374 return true; 375 } 376 unsigned BitSize = TRI->getSubRegIdxSize(SubIdx); 377 // Convert bit size to byte size to be consistent with 378 // MCRegisterClass::getSize(). 379 if (BitSize % 8) 380 return false; 381 382 int BitOffset = TRI->getSubRegIdxOffset(SubIdx); 383 if (BitOffset < 0 || BitOffset % 8) 384 return false; 385 386 Size = BitSize /= 8; 387 Offset = (unsigned)BitOffset / 8; 388 389 assert(TRI->getSpillSize(*RC) >= (Offset + Size) && "bad subregister range"); 390 391 if (!MF.getDataLayout().isLittleEndian()) { 392 Offset = TRI->getSpillSize(*RC) - (Offset + Size); 393 } 394 return true; 395 } 396 397 void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB, 398 MachineBasicBlock::iterator I, 399 unsigned DestReg, unsigned SubIdx, 400 const MachineInstr &Orig, 401 const TargetRegisterInfo &TRI) const { 402 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig); 403 MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI); 404 MBB.insert(I, MI); 405 } 406 407 bool TargetInstrInfo::produceSameValue(const MachineInstr &MI0, 408 const MachineInstr &MI1, 409 const MachineRegisterInfo *MRI) const { 410 return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs); 411 } 412 413 MachineInstr &TargetInstrInfo::duplicate(MachineBasicBlock &MBB, 414 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) const { 415 assert(!Orig.isNotDuplicable() && "Instruction cannot be duplicated"); 416 MachineFunction &MF = *MBB.getParent(); 417 return MF.CloneMachineInstrBundle(MBB, InsertBefore, Orig); 418 } 419 420 // If the COPY instruction in MI can be folded to a stack operation, return 421 // the register class to use. 422 static const TargetRegisterClass *canFoldCopy(const MachineInstr &MI, 423 unsigned FoldIdx) { 424 assert(MI.isCopy() && "MI must be a COPY instruction"); 425 if (MI.getNumOperands() != 2) 426 return nullptr; 427 assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand"); 428 429 const MachineOperand &FoldOp = MI.getOperand(FoldIdx); 430 const MachineOperand &LiveOp = MI.getOperand(1 - FoldIdx); 431 432 if (FoldOp.getSubReg() || LiveOp.getSubReg()) 433 return nullptr; 434 435 unsigned FoldReg = FoldOp.getReg(); 436 unsigned LiveReg = LiveOp.getReg(); 437 438 assert(TargetRegisterInfo::isVirtualRegister(FoldReg) && 439 "Cannot fold physregs"); 440 441 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 442 const TargetRegisterClass *RC = MRI.getRegClass(FoldReg); 443 444 if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg())) 445 return RC->contains(LiveOp.getReg()) ? RC : nullptr; 446 447 if (RC->hasSubClassEq(MRI.getRegClass(LiveReg))) 448 return RC; 449 450 // FIXME: Allow folding when register classes are memory compatible. 451 return nullptr; 452 } 453 454 void TargetInstrInfo::getNoop(MCInst &NopInst) const { 455 llvm_unreachable("Not implemented"); 456 } 457 458 static MachineInstr *foldPatchpoint(MachineFunction &MF, MachineInstr &MI, 459 ArrayRef<unsigned> Ops, int FrameIndex, 460 const TargetInstrInfo &TII) { 461 unsigned StartIdx = 0; 462 switch (MI.getOpcode()) { 463 case TargetOpcode::STACKMAP: { 464 // StackMapLiveValues are foldable 465 StartIdx = StackMapOpers(&MI).getVarIdx(); 466 break; 467 } 468 case TargetOpcode::PATCHPOINT: { 469 // For PatchPoint, the call args are not foldable (even if reported in the 470 // stackmap e.g. via anyregcc). 471 StartIdx = PatchPointOpers(&MI).getVarIdx(); 472 break; 473 } 474 case TargetOpcode::STATEPOINT: { 475 // For statepoints, fold deopt and gc arguments, but not call arguments. 476 StartIdx = StatepointOpers(&MI).getVarIdx(); 477 break; 478 } 479 default: 480 llvm_unreachable("unexpected stackmap opcode"); 481 } 482 483 // Return false if any operands requested for folding are not foldable (not 484 // part of the stackmap's live values). 485 for (unsigned Op : Ops) { 486 if (Op < StartIdx) 487 return nullptr; 488 } 489 490 MachineInstr *NewMI = 491 MF.CreateMachineInstr(TII.get(MI.getOpcode()), MI.getDebugLoc(), true); 492 MachineInstrBuilder MIB(MF, NewMI); 493 494 // No need to fold return, the meta data, and function arguments 495 for (unsigned i = 0; i < StartIdx; ++i) 496 MIB.add(MI.getOperand(i)); 497 498 for (unsigned i = StartIdx; i < MI.getNumOperands(); ++i) { 499 MachineOperand &MO = MI.getOperand(i); 500 if (is_contained(Ops, i)) { 501 unsigned SpillSize; 502 unsigned SpillOffset; 503 // Compute the spill slot size and offset. 504 const TargetRegisterClass *RC = 505 MF.getRegInfo().getRegClass(MO.getReg()); 506 bool Valid = 507 TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF); 508 if (!Valid) 509 report_fatal_error("cannot spill patchpoint subregister operand"); 510 MIB.addImm(StackMaps::IndirectMemRefOp); 511 MIB.addImm(SpillSize); 512 MIB.addFrameIndex(FrameIndex); 513 MIB.addImm(SpillOffset); 514 } 515 else 516 MIB.add(MO); 517 } 518 return NewMI; 519 } 520 521 /// foldMemoryOperand - Attempt to fold a load or store of the specified stack 522 /// slot into the specified machine instruction for the specified operand(s). 523 /// If this is possible, a new instruction is returned with the specified 524 /// operand folded, otherwise NULL is returned. The client is responsible for 525 /// removing the old instruction and adding the new one in the instruction 526 /// stream. 527 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI, 528 ArrayRef<unsigned> Ops, int FI, 529 LiveIntervals *LIS) const { 530 auto Flags = MachineMemOperand::MONone; 531 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 532 if (MI.getOperand(Ops[i]).isDef()) 533 Flags |= MachineMemOperand::MOStore; 534 else 535 Flags |= MachineMemOperand::MOLoad; 536 537 MachineBasicBlock *MBB = MI.getParent(); 538 assert(MBB && "foldMemoryOperand needs an inserted instruction"); 539 MachineFunction &MF = *MBB->getParent(); 540 541 // If we're not folding a load into a subreg, the size of the load is the 542 // size of the spill slot. But if we are, we need to figure out what the 543 // actual load size is. 544 int64_t MemSize = 0; 545 const MachineFrameInfo &MFI = MF.getFrameInfo(); 546 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 547 548 if (Flags & MachineMemOperand::MOStore) { 549 MemSize = MFI.getObjectSize(FI); 550 } else { 551 for (unsigned Idx : Ops) { 552 int64_t OpSize = MFI.getObjectSize(FI); 553 554 if (auto SubReg = MI.getOperand(Idx).getSubReg()) { 555 unsigned SubRegSize = TRI->getSubRegIdxSize(SubReg); 556 if (SubRegSize > 0 && !(SubRegSize % 8)) 557 OpSize = SubRegSize / 8; 558 } 559 560 MemSize = std::max(MemSize, OpSize); 561 } 562 } 563 564 assert(MemSize && "Did not expect a zero-sized stack slot"); 565 566 MachineInstr *NewMI = nullptr; 567 568 if (MI.getOpcode() == TargetOpcode::STACKMAP || 569 MI.getOpcode() == TargetOpcode::PATCHPOINT || 570 MI.getOpcode() == TargetOpcode::STATEPOINT) { 571 // Fold stackmap/patchpoint. 572 NewMI = foldPatchpoint(MF, MI, Ops, FI, *this); 573 if (NewMI) 574 MBB->insert(MI, NewMI); 575 } else { 576 // Ask the target to do the actual folding. 577 NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, FI, LIS); 578 } 579 580 if (NewMI) { 581 NewMI->setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 582 // Add a memory operand, foldMemoryOperandImpl doesn't do that. 583 assert((!(Flags & MachineMemOperand::MOStore) || 584 NewMI->mayStore()) && 585 "Folded a def to a non-store!"); 586 assert((!(Flags & MachineMemOperand::MOLoad) || 587 NewMI->mayLoad()) && 588 "Folded a use to a non-load!"); 589 assert(MFI.getObjectOffset(FI) != -1); 590 MachineMemOperand *MMO = MF.getMachineMemOperand( 591 MachinePointerInfo::getFixedStack(MF, FI), Flags, MemSize, 592 MFI.getObjectAlignment(FI)); 593 NewMI->addMemOperand(MF, MMO); 594 595 return NewMI; 596 } 597 598 // Straight COPY may fold as load/store. 599 if (!MI.isCopy() || Ops.size() != 1) 600 return nullptr; 601 602 const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]); 603 if (!RC) 604 return nullptr; 605 606 const MachineOperand &MO = MI.getOperand(1 - Ops[0]); 607 MachineBasicBlock::iterator Pos = MI; 608 609 if (Flags == MachineMemOperand::MOStore) 610 storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI); 611 else 612 loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI); 613 return &*--Pos; 614 } 615 616 bool TargetInstrInfo::hasReassociableOperands( 617 const MachineInstr &Inst, const MachineBasicBlock *MBB) const { 618 const MachineOperand &Op1 = Inst.getOperand(1); 619 const MachineOperand &Op2 = Inst.getOperand(2); 620 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 621 622 // We need virtual register definitions for the operands that we will 623 // reassociate. 624 MachineInstr *MI1 = nullptr; 625 MachineInstr *MI2 = nullptr; 626 if (Op1.isReg() && TargetRegisterInfo::isVirtualRegister(Op1.getReg())) 627 MI1 = MRI.getUniqueVRegDef(Op1.getReg()); 628 if (Op2.isReg() && TargetRegisterInfo::isVirtualRegister(Op2.getReg())) 629 MI2 = MRI.getUniqueVRegDef(Op2.getReg()); 630 631 // And they need to be in the trace (otherwise, they won't have a depth). 632 return MI1 && MI2 && MI1->getParent() == MBB && MI2->getParent() == MBB; 633 } 634 635 bool TargetInstrInfo::hasReassociableSibling(const MachineInstr &Inst, 636 bool &Commuted) const { 637 const MachineBasicBlock *MBB = Inst.getParent(); 638 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 639 MachineInstr *MI1 = MRI.getUniqueVRegDef(Inst.getOperand(1).getReg()); 640 MachineInstr *MI2 = MRI.getUniqueVRegDef(Inst.getOperand(2).getReg()); 641 unsigned AssocOpcode = Inst.getOpcode(); 642 643 // If only one operand has the same opcode and it's the second source operand, 644 // the operands must be commuted. 645 Commuted = MI1->getOpcode() != AssocOpcode && MI2->getOpcode() == AssocOpcode; 646 if (Commuted) 647 std::swap(MI1, MI2); 648 649 // 1. The previous instruction must be the same type as Inst. 650 // 2. The previous instruction must have virtual register definitions for its 651 // operands in the same basic block as Inst. 652 // 3. The previous instruction's result must only be used by Inst. 653 return MI1->getOpcode() == AssocOpcode && 654 hasReassociableOperands(*MI1, MBB) && 655 MRI.hasOneNonDBGUse(MI1->getOperand(0).getReg()); 656 } 657 658 // 1. The operation must be associative and commutative. 659 // 2. The instruction must have virtual register definitions for its 660 // operands in the same basic block. 661 // 3. The instruction must have a reassociable sibling. 662 bool TargetInstrInfo::isReassociationCandidate(const MachineInstr &Inst, 663 bool &Commuted) const { 664 return isAssociativeAndCommutative(Inst) && 665 hasReassociableOperands(Inst, Inst.getParent()) && 666 hasReassociableSibling(Inst, Commuted); 667 } 668 669 // The concept of the reassociation pass is that these operations can benefit 670 // from this kind of transformation: 671 // 672 // A = ? op ? 673 // B = A op X (Prev) 674 // C = B op Y (Root) 675 // --> 676 // A = ? op ? 677 // B = X op Y 678 // C = A op B 679 // 680 // breaking the dependency between A and B, allowing them to be executed in 681 // parallel (or back-to-back in a pipeline) instead of depending on each other. 682 683 // FIXME: This has the potential to be expensive (compile time) while not 684 // improving the code at all. Some ways to limit the overhead: 685 // 1. Track successful transforms; bail out if hit rate gets too low. 686 // 2. Only enable at -O3 or some other non-default optimization level. 687 // 3. Pre-screen pattern candidates here: if an operand of the previous 688 // instruction is known to not increase the critical path, then don't match 689 // that pattern. 690 bool TargetInstrInfo::getMachineCombinerPatterns( 691 MachineInstr &Root, 692 SmallVectorImpl<MachineCombinerPattern> &Patterns) const { 693 bool Commute; 694 if (isReassociationCandidate(Root, Commute)) { 695 // We found a sequence of instructions that may be suitable for a 696 // reassociation of operands to increase ILP. Specify each commutation 697 // possibility for the Prev instruction in the sequence and let the 698 // machine combiner decide if changing the operands is worthwhile. 699 if (Commute) { 700 Patterns.push_back(MachineCombinerPattern::REASSOC_AX_YB); 701 Patterns.push_back(MachineCombinerPattern::REASSOC_XA_YB); 702 } else { 703 Patterns.push_back(MachineCombinerPattern::REASSOC_AX_BY); 704 Patterns.push_back(MachineCombinerPattern::REASSOC_XA_BY); 705 } 706 return true; 707 } 708 709 return false; 710 } 711 /// Return true when a code sequence can improve loop throughput. 712 bool 713 TargetInstrInfo::isThroughputPattern(MachineCombinerPattern Pattern) const { 714 return false; 715 } 716 /// Attempt the reassociation transformation to reduce critical path length. 717 /// See the above comments before getMachineCombinerPatterns(). 718 void TargetInstrInfo::reassociateOps( 719 MachineInstr &Root, MachineInstr &Prev, 720 MachineCombinerPattern Pattern, 721 SmallVectorImpl<MachineInstr *> &InsInstrs, 722 SmallVectorImpl<MachineInstr *> &DelInstrs, 723 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const { 724 MachineFunction *MF = Root.getParent()->getParent(); 725 MachineRegisterInfo &MRI = MF->getRegInfo(); 726 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 727 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 728 const TargetRegisterClass *RC = Root.getRegClassConstraint(0, TII, TRI); 729 730 // This array encodes the operand index for each parameter because the 731 // operands may be commuted. Each row corresponds to a pattern value, 732 // and each column specifies the index of A, B, X, Y. 733 unsigned OpIdx[4][4] = { 734 { 1, 1, 2, 2 }, 735 { 1, 2, 2, 1 }, 736 { 2, 1, 1, 2 }, 737 { 2, 2, 1, 1 } 738 }; 739 740 int Row; 741 switch (Pattern) { 742 case MachineCombinerPattern::REASSOC_AX_BY: Row = 0; break; 743 case MachineCombinerPattern::REASSOC_AX_YB: Row = 1; break; 744 case MachineCombinerPattern::REASSOC_XA_BY: Row = 2; break; 745 case MachineCombinerPattern::REASSOC_XA_YB: Row = 3; break; 746 default: llvm_unreachable("unexpected MachineCombinerPattern"); 747 } 748 749 MachineOperand &OpA = Prev.getOperand(OpIdx[Row][0]); 750 MachineOperand &OpB = Root.getOperand(OpIdx[Row][1]); 751 MachineOperand &OpX = Prev.getOperand(OpIdx[Row][2]); 752 MachineOperand &OpY = Root.getOperand(OpIdx[Row][3]); 753 MachineOperand &OpC = Root.getOperand(0); 754 755 unsigned RegA = OpA.getReg(); 756 unsigned RegB = OpB.getReg(); 757 unsigned RegX = OpX.getReg(); 758 unsigned RegY = OpY.getReg(); 759 unsigned RegC = OpC.getReg(); 760 761 if (TargetRegisterInfo::isVirtualRegister(RegA)) 762 MRI.constrainRegClass(RegA, RC); 763 if (TargetRegisterInfo::isVirtualRegister(RegB)) 764 MRI.constrainRegClass(RegB, RC); 765 if (TargetRegisterInfo::isVirtualRegister(RegX)) 766 MRI.constrainRegClass(RegX, RC); 767 if (TargetRegisterInfo::isVirtualRegister(RegY)) 768 MRI.constrainRegClass(RegY, RC); 769 if (TargetRegisterInfo::isVirtualRegister(RegC)) 770 MRI.constrainRegClass(RegC, RC); 771 772 // Create a new virtual register for the result of (X op Y) instead of 773 // recycling RegB because the MachineCombiner's computation of the critical 774 // path requires a new register definition rather than an existing one. 775 unsigned NewVR = MRI.createVirtualRegister(RC); 776 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0)); 777 778 unsigned Opcode = Root.getOpcode(); 779 bool KillA = OpA.isKill(); 780 bool KillX = OpX.isKill(); 781 bool KillY = OpY.isKill(); 782 783 // Create new instructions for insertion. 784 MachineInstrBuilder MIB1 = 785 BuildMI(*MF, Prev.getDebugLoc(), TII->get(Opcode), NewVR) 786 .addReg(RegX, getKillRegState(KillX)) 787 .addReg(RegY, getKillRegState(KillY)); 788 MachineInstrBuilder MIB2 = 789 BuildMI(*MF, Root.getDebugLoc(), TII->get(Opcode), RegC) 790 .addReg(RegA, getKillRegState(KillA)) 791 .addReg(NewVR, getKillRegState(true)); 792 793 setSpecialOperandAttr(Root, Prev, *MIB1, *MIB2); 794 795 // Record new instructions for insertion and old instructions for deletion. 796 InsInstrs.push_back(MIB1); 797 InsInstrs.push_back(MIB2); 798 DelInstrs.push_back(&Prev); 799 DelInstrs.push_back(&Root); 800 } 801 802 void TargetInstrInfo::genAlternativeCodeSequence( 803 MachineInstr &Root, MachineCombinerPattern Pattern, 804 SmallVectorImpl<MachineInstr *> &InsInstrs, 805 SmallVectorImpl<MachineInstr *> &DelInstrs, 806 DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const { 807 MachineRegisterInfo &MRI = Root.getParent()->getParent()->getRegInfo(); 808 809 // Select the previous instruction in the sequence based on the input pattern. 810 MachineInstr *Prev = nullptr; 811 switch (Pattern) { 812 case MachineCombinerPattern::REASSOC_AX_BY: 813 case MachineCombinerPattern::REASSOC_XA_BY: 814 Prev = MRI.getUniqueVRegDef(Root.getOperand(1).getReg()); 815 break; 816 case MachineCombinerPattern::REASSOC_AX_YB: 817 case MachineCombinerPattern::REASSOC_XA_YB: 818 Prev = MRI.getUniqueVRegDef(Root.getOperand(2).getReg()); 819 break; 820 default: 821 break; 822 } 823 824 assert(Prev && "Unknown pattern for machine combiner"); 825 826 reassociateOps(Root, *Prev, Pattern, InsInstrs, DelInstrs, InstIdxForVirtReg); 827 } 828 829 /// foldMemoryOperand - Same as the previous version except it allows folding 830 /// of any load and store from / to any address, not just from a specific 831 /// stack slot. 832 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI, 833 ArrayRef<unsigned> Ops, 834 MachineInstr &LoadMI, 835 LiveIntervals *LIS) const { 836 assert(LoadMI.canFoldAsLoad() && "LoadMI isn't foldable!"); 837 #ifndef NDEBUG 838 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 839 assert(MI.getOperand(Ops[i]).isUse() && "Folding load into def!"); 840 #endif 841 MachineBasicBlock &MBB = *MI.getParent(); 842 MachineFunction &MF = *MBB.getParent(); 843 844 // Ask the target to do the actual folding. 845 MachineInstr *NewMI = nullptr; 846 int FrameIndex = 0; 847 848 if ((MI.getOpcode() == TargetOpcode::STACKMAP || 849 MI.getOpcode() == TargetOpcode::PATCHPOINT || 850 MI.getOpcode() == TargetOpcode::STATEPOINT) && 851 isLoadFromStackSlot(LoadMI, FrameIndex)) { 852 // Fold stackmap/patchpoint. 853 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this); 854 if (NewMI) 855 NewMI = &*MBB.insert(MI, NewMI); 856 } else { 857 // Ask the target to do the actual folding. 858 NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, LoadMI, LIS); 859 } 860 861 if (!NewMI) return nullptr; 862 863 // Copy the memoperands from the load to the folded instruction. 864 if (MI.memoperands_empty()) { 865 NewMI->setMemRefs(LoadMI.memoperands_begin(), LoadMI.memoperands_end()); 866 } 867 else { 868 // Handle the rare case of folding multiple loads. 869 NewMI->setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 870 for (MachineInstr::mmo_iterator I = LoadMI.memoperands_begin(), 871 E = LoadMI.memoperands_end(); 872 I != E; ++I) { 873 NewMI->addMemOperand(MF, *I); 874 } 875 } 876 return NewMI; 877 } 878 879 bool TargetInstrInfo::isReallyTriviallyReMaterializableGeneric( 880 const MachineInstr &MI, AliasAnalysis *AA) const { 881 const MachineFunction &MF = *MI.getParent()->getParent(); 882 const MachineRegisterInfo &MRI = MF.getRegInfo(); 883 884 // Remat clients assume operand 0 is the defined register. 885 if (!MI.getNumOperands() || !MI.getOperand(0).isReg()) 886 return false; 887 unsigned DefReg = MI.getOperand(0).getReg(); 888 889 // A sub-register definition can only be rematerialized if the instruction 890 // doesn't read the other parts of the register. Otherwise it is really a 891 // read-modify-write operation on the full virtual register which cannot be 892 // moved safely. 893 if (TargetRegisterInfo::isVirtualRegister(DefReg) && 894 MI.getOperand(0).getSubReg() && MI.readsVirtualRegister(DefReg)) 895 return false; 896 897 // A load from a fixed stack slot can be rematerialized. This may be 898 // redundant with subsequent checks, but it's target-independent, 899 // simple, and a common case. 900 int FrameIdx = 0; 901 if (isLoadFromStackSlot(MI, FrameIdx) && 902 MF.getFrameInfo().isImmutableObjectIndex(FrameIdx)) 903 return true; 904 905 // Avoid instructions obviously unsafe for remat. 906 if (MI.isNotDuplicable() || MI.mayStore() || MI.hasUnmodeledSideEffects()) 907 return false; 908 909 // Don't remat inline asm. We have no idea how expensive it is 910 // even if it's side effect free. 911 if (MI.isInlineAsm()) 912 return false; 913 914 // Avoid instructions which load from potentially varying memory. 915 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)) 916 return false; 917 918 // If any of the registers accessed are non-constant, conservatively assume 919 // the instruction is not rematerializable. 920 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 921 const MachineOperand &MO = MI.getOperand(i); 922 if (!MO.isReg()) continue; 923 unsigned Reg = MO.getReg(); 924 if (Reg == 0) 925 continue; 926 927 // Check for a well-behaved physical register. 928 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 929 if (MO.isUse()) { 930 // If the physreg has no defs anywhere, it's just an ambient register 931 // and we can freely move its uses. Alternatively, if it's allocatable, 932 // it could get allocated to something with a def during allocation. 933 if (!MRI.isConstantPhysReg(Reg)) 934 return false; 935 } else { 936 // A physreg def. We can't remat it. 937 return false; 938 } 939 continue; 940 } 941 942 // Only allow one virtual-register def. There may be multiple defs of the 943 // same virtual register, though. 944 if (MO.isDef() && Reg != DefReg) 945 return false; 946 947 // Don't allow any virtual-register uses. Rematting an instruction with 948 // virtual register uses would length the live ranges of the uses, which 949 // is not necessarily a good idea, certainly not "trivial". 950 if (MO.isUse()) 951 return false; 952 } 953 954 // Everything checked out. 955 return true; 956 } 957 958 int TargetInstrInfo::getSPAdjust(const MachineInstr &MI) const { 959 const MachineFunction *MF = MI.getParent()->getParent(); 960 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); 961 bool StackGrowsDown = 962 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown; 963 964 unsigned FrameSetupOpcode = getCallFrameSetupOpcode(); 965 unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode(); 966 967 if (!isFrameInstr(MI)) 968 return 0; 969 970 int SPAdj = TFI->alignSPAdjust(getFrameSize(MI)); 971 972 if ((!StackGrowsDown && MI.getOpcode() == FrameSetupOpcode) || 973 (StackGrowsDown && MI.getOpcode() == FrameDestroyOpcode)) 974 SPAdj = -SPAdj; 975 976 return SPAdj; 977 } 978 979 /// isSchedulingBoundary - Test if the given instruction should be 980 /// considered a scheduling boundary. This primarily includes labels 981 /// and terminators. 982 bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr &MI, 983 const MachineBasicBlock *MBB, 984 const MachineFunction &MF) const { 985 // Terminators and labels can't be scheduled around. 986 if (MI.isTerminator() || MI.isPosition()) 987 return true; 988 989 // Don't attempt to schedule around any instruction that defines 990 // a stack-oriented pointer, as it's unlikely to be profitable. This 991 // saves compile time, because it doesn't require every single 992 // stack slot reference to depend on the instruction that does the 993 // modification. 994 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering(); 995 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 996 return MI.modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI); 997 } 998 999 // Provide a global flag for disabling the PreRA hazard recognizer that targets 1000 // may choose to honor. 1001 bool TargetInstrInfo::usePreRAHazardRecognizer() const { 1002 return !DisableHazardRecognizer; 1003 } 1004 1005 // Default implementation of CreateTargetRAHazardRecognizer. 1006 ScheduleHazardRecognizer *TargetInstrInfo:: 1007 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, 1008 const ScheduleDAG *DAG) const { 1009 // Dummy hazard recognizer allows all instructions to issue. 1010 return new ScheduleHazardRecognizer(); 1011 } 1012 1013 // Default implementation of CreateTargetMIHazardRecognizer. 1014 ScheduleHazardRecognizer *TargetInstrInfo:: 1015 CreateTargetMIHazardRecognizer(const InstrItineraryData *II, 1016 const ScheduleDAG *DAG) const { 1017 return (ScheduleHazardRecognizer *) 1018 new ScoreboardHazardRecognizer(II, DAG, "misched"); 1019 } 1020 1021 // Default implementation of CreateTargetPostRAHazardRecognizer. 1022 ScheduleHazardRecognizer *TargetInstrInfo:: 1023 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, 1024 const ScheduleDAG *DAG) const { 1025 return (ScheduleHazardRecognizer *) 1026 new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched"); 1027 } 1028 1029 //===----------------------------------------------------------------------===// 1030 // SelectionDAG latency interface. 1031 //===----------------------------------------------------------------------===// 1032 1033 int 1034 TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 1035 SDNode *DefNode, unsigned DefIdx, 1036 SDNode *UseNode, unsigned UseIdx) const { 1037 if (!ItinData || ItinData->isEmpty()) 1038 return -1; 1039 1040 if (!DefNode->isMachineOpcode()) 1041 return -1; 1042 1043 unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass(); 1044 if (!UseNode->isMachineOpcode()) 1045 return ItinData->getOperandCycle(DefClass, DefIdx); 1046 unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass(); 1047 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); 1048 } 1049 1050 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 1051 SDNode *N) const { 1052 if (!ItinData || ItinData->isEmpty()) 1053 return 1; 1054 1055 if (!N->isMachineOpcode()) 1056 return 1; 1057 1058 return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass()); 1059 } 1060 1061 //===----------------------------------------------------------------------===// 1062 // MachineInstr latency interface. 1063 //===----------------------------------------------------------------------===// 1064 1065 unsigned TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData, 1066 const MachineInstr &MI) const { 1067 if (!ItinData || ItinData->isEmpty()) 1068 return 1; 1069 1070 unsigned Class = MI.getDesc().getSchedClass(); 1071 int UOps = ItinData->Itineraries[Class].NumMicroOps; 1072 if (UOps >= 0) 1073 return UOps; 1074 1075 // The # of u-ops is dynamically determined. The specific target should 1076 // override this function to return the right number. 1077 return 1; 1078 } 1079 1080 /// Return the default expected latency for a def based on it's opcode. 1081 unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel, 1082 const MachineInstr &DefMI) const { 1083 if (DefMI.isTransient()) 1084 return 0; 1085 if (DefMI.mayLoad()) 1086 return SchedModel.LoadLatency; 1087 if (isHighLatencyDef(DefMI.getOpcode())) 1088 return SchedModel.HighLatency; 1089 return 1; 1090 } 1091 1092 unsigned TargetInstrInfo::getPredicationCost(const MachineInstr &) const { 1093 return 0; 1094 } 1095 1096 unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 1097 const MachineInstr &MI, 1098 unsigned *PredCost) const { 1099 // Default to one cycle for no itinerary. However, an "empty" itinerary may 1100 // still have a MinLatency property, which getStageLatency checks. 1101 if (!ItinData) 1102 return MI.mayLoad() ? 2 : 1; 1103 1104 return ItinData->getStageLatency(MI.getDesc().getSchedClass()); 1105 } 1106 1107 bool TargetInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel, 1108 const MachineInstr &DefMI, 1109 unsigned DefIdx) const { 1110 const InstrItineraryData *ItinData = SchedModel.getInstrItineraries(); 1111 if (!ItinData || ItinData->isEmpty()) 1112 return false; 1113 1114 unsigned DefClass = DefMI.getDesc().getSchedClass(); 1115 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx); 1116 return (DefCycle != -1 && DefCycle <= 1); 1117 } 1118 1119 /// Both DefMI and UseMI must be valid. By default, call directly to the 1120 /// itinerary. This may be overriden by the target. 1121 int TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 1122 const MachineInstr &DefMI, 1123 unsigned DefIdx, 1124 const MachineInstr &UseMI, 1125 unsigned UseIdx) const { 1126 unsigned DefClass = DefMI.getDesc().getSchedClass(); 1127 unsigned UseClass = UseMI.getDesc().getSchedClass(); 1128 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx); 1129 } 1130 1131 /// If we can determine the operand latency from the def only, without itinerary 1132 /// lookup, do so. Otherwise return -1. 1133 int TargetInstrInfo::computeDefOperandLatency( 1134 const InstrItineraryData *ItinData, const MachineInstr &DefMI) const { 1135 1136 // Let the target hook getInstrLatency handle missing itineraries. 1137 if (!ItinData) 1138 return getInstrLatency(ItinData, DefMI); 1139 1140 if(ItinData->isEmpty()) 1141 return defaultDefLatency(ItinData->SchedModel, DefMI); 1142 1143 // ...operand lookup required 1144 return -1; 1145 } 1146 1147 bool TargetInstrInfo::getRegSequenceInputs( 1148 const MachineInstr &MI, unsigned DefIdx, 1149 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const { 1150 assert((MI.isRegSequence() || 1151 MI.isRegSequenceLike()) && "Instruction do not have the proper type"); 1152 1153 if (!MI.isRegSequence()) 1154 return getRegSequenceLikeInputs(MI, DefIdx, InputRegs); 1155 1156 // We are looking at: 1157 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ... 1158 assert(DefIdx == 0 && "REG_SEQUENCE only has one def"); 1159 for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx; 1160 OpIdx += 2) { 1161 const MachineOperand &MOReg = MI.getOperand(OpIdx); 1162 const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1); 1163 assert(MOSubIdx.isImm() && 1164 "One of the subindex of the reg_sequence is not an immediate"); 1165 // Record Reg:SubReg, SubIdx. 1166 InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(), 1167 (unsigned)MOSubIdx.getImm())); 1168 } 1169 return true; 1170 } 1171 1172 bool TargetInstrInfo::getExtractSubregInputs( 1173 const MachineInstr &MI, unsigned DefIdx, 1174 RegSubRegPairAndIdx &InputReg) const { 1175 assert((MI.isExtractSubreg() || 1176 MI.isExtractSubregLike()) && "Instruction do not have the proper type"); 1177 1178 if (!MI.isExtractSubreg()) 1179 return getExtractSubregLikeInputs(MI, DefIdx, InputReg); 1180 1181 // We are looking at: 1182 // Def = EXTRACT_SUBREG v0.sub1, sub0. 1183 assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def"); 1184 const MachineOperand &MOReg = MI.getOperand(1); 1185 const MachineOperand &MOSubIdx = MI.getOperand(2); 1186 assert(MOSubIdx.isImm() && 1187 "The subindex of the extract_subreg is not an immediate"); 1188 1189 InputReg.Reg = MOReg.getReg(); 1190 InputReg.SubReg = MOReg.getSubReg(); 1191 InputReg.SubIdx = (unsigned)MOSubIdx.getImm(); 1192 return true; 1193 } 1194 1195 bool TargetInstrInfo::getInsertSubregInputs( 1196 const MachineInstr &MI, unsigned DefIdx, 1197 RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const { 1198 assert((MI.isInsertSubreg() || 1199 MI.isInsertSubregLike()) && "Instruction do not have the proper type"); 1200 1201 if (!MI.isInsertSubreg()) 1202 return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg); 1203 1204 // We are looking at: 1205 // Def = INSERT_SEQUENCE v0, v1, sub0. 1206 assert(DefIdx == 0 && "INSERT_SUBREG only has one def"); 1207 const MachineOperand &MOBaseReg = MI.getOperand(1); 1208 const MachineOperand &MOInsertedReg = MI.getOperand(2); 1209 const MachineOperand &MOSubIdx = MI.getOperand(3); 1210 assert(MOSubIdx.isImm() && 1211 "One of the subindex of the reg_sequence is not an immediate"); 1212 BaseReg.Reg = MOBaseReg.getReg(); 1213 BaseReg.SubReg = MOBaseReg.getSubReg(); 1214 1215 InsertedReg.Reg = MOInsertedReg.getReg(); 1216 InsertedReg.SubReg = MOInsertedReg.getSubReg(); 1217 InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm(); 1218 return true; 1219 } 1220