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