LLVM API Documentation

TargetInstrInfo.cpp
Go to the documentation of this file.
00001 //===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the TargetInstrInfo class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Target/TargetInstrInfo.h"
00015 #include "llvm/CodeGen/MachineFrameInfo.h"
00016 #include "llvm/CodeGen/MachineInstrBuilder.h"
00017 #include "llvm/CodeGen/MachineMemOperand.h"
00018 #include "llvm/CodeGen/MachineRegisterInfo.h"
00019 #include "llvm/CodeGen/PseudoSourceValue.h"
00020 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
00021 #include "llvm/CodeGen/StackMaps.h"
00022 #include "llvm/IR/DataLayout.h"
00023 #include "llvm/MC/MCAsmInfo.h"
00024 #include "llvm/MC/MCInstrItineraries.h"
00025 #include "llvm/Support/CommandLine.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include "llvm/Target/TargetLowering.h"
00029 #include "llvm/Target/TargetMachine.h"
00030 #include "llvm/Target/TargetRegisterInfo.h"
00031 #include <cctype>
00032 using namespace llvm;
00033 
00034 static cl::opt<bool> DisableHazardRecognizer(
00035   "disable-sched-hazard", cl::Hidden, cl::init(false),
00036   cl::desc("Disable hazard detection during preRA scheduling"));
00037 
00038 TargetInstrInfo::~TargetInstrInfo() {
00039 }
00040 
00041 const TargetRegisterClass*
00042 TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
00043                              const TargetRegisterInfo *TRI,
00044                              const MachineFunction &MF) const {
00045   if (OpNum >= MCID.getNumOperands())
00046     return nullptr;
00047 
00048   short RegClass = MCID.OpInfo[OpNum].RegClass;
00049   if (MCID.OpInfo[OpNum].isLookupPtrRegClass())
00050     return TRI->getPointerRegClass(MF, RegClass);
00051 
00052   // Instructions like INSERT_SUBREG do not have fixed register classes.
00053   if (RegClass < 0)
00054     return nullptr;
00055 
00056   // Otherwise just look it up normally.
00057   return TRI->getRegClass(RegClass);
00058 }
00059 
00060 /// insertNoop - Insert a noop into the instruction stream at the specified
00061 /// point.
00062 void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
00063                                  MachineBasicBlock::iterator MI) const {
00064   llvm_unreachable("Target didn't implement insertNoop!");
00065 }
00066 
00067 /// Measure the specified inline asm to determine an approximation of its
00068 /// length.
00069 /// Comments (which run till the next SeparatorString or newline) do not
00070 /// count as an instruction.
00071 /// Any other non-whitespace text is considered an instruction, with
00072 /// multiple instructions separated by SeparatorString or newlines.
00073 /// Variable-length instructions are not handled here; this function
00074 /// may be overloaded in the target code to do that.
00075 unsigned TargetInstrInfo::getInlineAsmLength(const char *Str,
00076                                              const MCAsmInfo &MAI) const {
00077 
00078 
00079   // Count the number of instructions in the asm.
00080   bool atInsnStart = true;
00081   unsigned Length = 0;
00082   for (; *Str; ++Str) {
00083     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
00084                                 strlen(MAI.getSeparatorString())) == 0)
00085       atInsnStart = true;
00086     if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
00087       Length += MAI.getMaxInstLength();
00088       atInsnStart = false;
00089     }
00090     if (atInsnStart && strncmp(Str, MAI.getCommentString(),
00091                                strlen(MAI.getCommentString())) == 0)
00092       atInsnStart = false;
00093   }
00094 
00095   return Length;
00096 }
00097 
00098 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
00099 /// after it, replacing it with an unconditional branch to NewDest.
00100 void
00101 TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
00102                                          MachineBasicBlock *NewDest) const {
00103   MachineBasicBlock *MBB = Tail->getParent();
00104 
00105   // Remove all the old successors of MBB from the CFG.
00106   while (!MBB->succ_empty())
00107     MBB->removeSuccessor(MBB->succ_begin());
00108 
00109   // Remove all the dead instructions from the end of MBB.
00110   MBB->erase(Tail, MBB->end());
00111 
00112   // If MBB isn't immediately before MBB, insert a branch to it.
00113   if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
00114     InsertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(),
00115                  Tail->getDebugLoc());
00116   MBB->addSuccessor(NewDest);
00117 }
00118 
00119 // commuteInstruction - The default implementation of this method just exchanges
00120 // the two operands returned by findCommutedOpIndices.
00121 MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr *MI,
00122                                                   bool NewMI) const {
00123   const MCInstrDesc &MCID = MI->getDesc();
00124   bool HasDef = MCID.getNumDefs();
00125   if (HasDef && !MI->getOperand(0).isReg())
00126     // No idea how to commute this instruction. Target should implement its own.
00127     return nullptr;
00128   unsigned Idx1, Idx2;
00129   if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
00130     assert(MI->isCommutable() && "Precondition violation: MI must be commutable.");
00131     return nullptr;
00132   }
00133 
00134   assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
00135          "This only knows how to commute register operands so far");
00136   unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0;
00137   unsigned Reg1 = MI->getOperand(Idx1).getReg();
00138   unsigned Reg2 = MI->getOperand(Idx2).getReg();
00139   unsigned SubReg0 = HasDef ? MI->getOperand(0).getSubReg() : 0;
00140   unsigned SubReg1 = MI->getOperand(Idx1).getSubReg();
00141   unsigned SubReg2 = MI->getOperand(Idx2).getSubReg();
00142   bool Reg1IsKill = MI->getOperand(Idx1).isKill();
00143   bool Reg2IsKill = MI->getOperand(Idx2).isKill();
00144   // If destination is tied to either of the commuted source register, then
00145   // it must be updated.
00146   if (HasDef && Reg0 == Reg1 &&
00147       MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
00148     Reg2IsKill = false;
00149     Reg0 = Reg2;
00150     SubReg0 = SubReg2;
00151   } else if (HasDef && Reg0 == Reg2 &&
00152              MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
00153     Reg1IsKill = false;
00154     Reg0 = Reg1;
00155     SubReg0 = SubReg1;
00156   }
00157 
00158   if (NewMI) {
00159     // Create a new instruction.
00160     MachineFunction &MF = *MI->getParent()->getParent();
00161     MI = MF.CloneMachineInstr(MI);
00162   }
00163 
00164   if (HasDef) {
00165     MI->getOperand(0).setReg(Reg0);
00166     MI->getOperand(0).setSubReg(SubReg0);
00167   }
00168   MI->getOperand(Idx2).setReg(Reg1);
00169   MI->getOperand(Idx1).setReg(Reg2);
00170   MI->getOperand(Idx2).setSubReg(SubReg1);
00171   MI->getOperand(Idx1).setSubReg(SubReg2);
00172   MI->getOperand(Idx2).setIsKill(Reg1IsKill);
00173   MI->getOperand(Idx1).setIsKill(Reg2IsKill);
00174   return MI;
00175 }
00176 
00177 /// findCommutedOpIndices - If specified MI is commutable, return the two
00178 /// operand indices that would swap value. Return true if the instruction
00179 /// is not in a form which this routine understands.
00180 bool TargetInstrInfo::findCommutedOpIndices(MachineInstr *MI,
00181                                             unsigned &SrcOpIdx1,
00182                                             unsigned &SrcOpIdx2) const {
00183   assert(!MI->isBundle() &&
00184          "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
00185 
00186   const MCInstrDesc &MCID = MI->getDesc();
00187   if (!MCID.isCommutable())
00188     return false;
00189   // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
00190   // is not true, then the target must implement this.
00191   SrcOpIdx1 = MCID.getNumDefs();
00192   SrcOpIdx2 = SrcOpIdx1 + 1;
00193   if (!MI->getOperand(SrcOpIdx1).isReg() ||
00194       !MI->getOperand(SrcOpIdx2).isReg())
00195     // No idea.
00196     return false;
00197   return true;
00198 }
00199 
00200 
00201 bool
00202 TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
00203   if (!MI->isTerminator()) return false;
00204 
00205   // Conditional branch is a special case.
00206   if (MI->isBranch() && !MI->isBarrier())
00207     return true;
00208   if (!MI->isPredicable())
00209     return true;
00210   return !isPredicated(MI);
00211 }
00212 
00213 
00214 bool TargetInstrInfo::PredicateInstruction(MachineInstr *MI,
00215                             const SmallVectorImpl<MachineOperand> &Pred) const {
00216   bool MadeChange = false;
00217 
00218   assert(!MI->isBundle() &&
00219          "TargetInstrInfo::PredicateInstruction() can't handle bundles");
00220 
00221   const MCInstrDesc &MCID = MI->getDesc();
00222   if (!MI->isPredicable())
00223     return false;
00224 
00225   for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
00226     if (MCID.OpInfo[i].isPredicate()) {
00227       MachineOperand &MO = MI->getOperand(i);
00228       if (MO.isReg()) {
00229         MO.setReg(Pred[j].getReg());
00230         MadeChange = true;
00231       } else if (MO.isImm()) {
00232         MO.setImm(Pred[j].getImm());
00233         MadeChange = true;
00234       } else if (MO.isMBB()) {
00235         MO.setMBB(Pred[j].getMBB());
00236         MadeChange = true;
00237       }
00238       ++j;
00239     }
00240   }
00241   return MadeChange;
00242 }
00243 
00244 bool TargetInstrInfo::hasLoadFromStackSlot(const MachineInstr *MI,
00245                                            const MachineMemOperand *&MMO,
00246                                            int &FrameIndex) const {
00247   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
00248          oe = MI->memoperands_end();
00249        o != oe;
00250        ++o) {
00251     if ((*o)->isLoad()) {
00252       if (const FixedStackPseudoSourceValue *Value =
00253           dyn_cast_or_null<FixedStackPseudoSourceValue>(
00254               (*o)->getPseudoValue())) {
00255         FrameIndex = Value->getFrameIndex();
00256         MMO = *o;
00257         return true;
00258       }
00259     }
00260   }
00261   return false;
00262 }
00263 
00264 bool TargetInstrInfo::hasStoreToStackSlot(const MachineInstr *MI,
00265                                           const MachineMemOperand *&MMO,
00266                                           int &FrameIndex) const {
00267   for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
00268          oe = MI->memoperands_end();
00269        o != oe;
00270        ++o) {
00271     if ((*o)->isStore()) {
00272       if (const FixedStackPseudoSourceValue *Value =
00273           dyn_cast_or_null<FixedStackPseudoSourceValue>(
00274               (*o)->getPseudoValue())) {
00275         FrameIndex = Value->getFrameIndex();
00276         MMO = *o;
00277         return true;
00278       }
00279     }
00280   }
00281   return false;
00282 }
00283 
00284 bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
00285                                         unsigned SubIdx, unsigned &Size,
00286                                         unsigned &Offset,
00287                                         const TargetMachine *TM) const {
00288   if (!SubIdx) {
00289     Size = RC->getSize();
00290     Offset = 0;
00291     return true;
00292   }
00293   unsigned BitSize =
00294       TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIdxSize(SubIdx);
00295   // Convert bit size to byte size to be consistent with
00296   // MCRegisterClass::getSize().
00297   if (BitSize % 8)
00298     return false;
00299 
00300   int BitOffset =
00301       TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIdxOffset(SubIdx);
00302   if (BitOffset < 0 || BitOffset % 8)
00303     return false;
00304 
00305   Size = BitSize /= 8;
00306   Offset = (unsigned)BitOffset / 8;
00307 
00308   assert(RC->getSize() >= (Offset + Size) && "bad subregister range");
00309 
00310   if (!TM->getSubtargetImpl()->getDataLayout()->isLittleEndian()) {
00311     Offset = RC->getSize() - (Offset + Size);
00312   }
00313   return true;
00314 }
00315 
00316 void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
00317                                     MachineBasicBlock::iterator I,
00318                                     unsigned DestReg,
00319                                     unsigned SubIdx,
00320                                     const MachineInstr *Orig,
00321                                     const TargetRegisterInfo &TRI) const {
00322   MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
00323   MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
00324   MBB.insert(I, MI);
00325 }
00326 
00327 bool
00328 TargetInstrInfo::produceSameValue(const MachineInstr *MI0,
00329                                   const MachineInstr *MI1,
00330                                   const MachineRegisterInfo *MRI) const {
00331   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
00332 }
00333 
00334 MachineInstr *TargetInstrInfo::duplicate(MachineInstr *Orig,
00335                                          MachineFunction &MF) const {
00336   assert(!Orig->isNotDuplicable() &&
00337          "Instruction cannot be duplicated");
00338   return MF.CloneMachineInstr(Orig);
00339 }
00340 
00341 // If the COPY instruction in MI can be folded to a stack operation, return
00342 // the register class to use.
00343 static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI,
00344                                               unsigned FoldIdx) {
00345   assert(MI->isCopy() && "MI must be a COPY instruction");
00346   if (MI->getNumOperands() != 2)
00347     return nullptr;
00348   assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
00349 
00350   const MachineOperand &FoldOp = MI->getOperand(FoldIdx);
00351   const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx);
00352 
00353   if (FoldOp.getSubReg() || LiveOp.getSubReg())
00354     return nullptr;
00355 
00356   unsigned FoldReg = FoldOp.getReg();
00357   unsigned LiveReg = LiveOp.getReg();
00358 
00359   assert(TargetRegisterInfo::isVirtualRegister(FoldReg) &&
00360          "Cannot fold physregs");
00361 
00362   const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
00363   const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
00364 
00365   if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg()))
00366     return RC->contains(LiveOp.getReg()) ? RC : nullptr;
00367 
00368   if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
00369     return RC;
00370 
00371   // FIXME: Allow folding when register classes are memory compatible.
00372   return nullptr;
00373 }
00374 
00375 void TargetInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
00376   llvm_unreachable("Not a MachO target");
00377 }
00378 
00379 bool TargetInstrInfo::
00380 canFoldMemoryOperand(const MachineInstr *MI,
00381                      const SmallVectorImpl<unsigned> &Ops) const {
00382   return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]);
00383 }
00384 
00385 static MachineInstr* foldPatchpoint(MachineFunction &MF,
00386                                     MachineInstr *MI,
00387                                     const SmallVectorImpl<unsigned> &Ops,
00388                                     int FrameIndex,
00389                                     const TargetInstrInfo &TII) {
00390   unsigned StartIdx = 0;
00391   switch (MI->getOpcode()) {
00392   case TargetOpcode::STACKMAP:
00393     StartIdx = 2; // Skip ID, nShadowBytes.
00394     break;
00395   case TargetOpcode::PATCHPOINT: {
00396     // For PatchPoint, the call args are not foldable.
00397     PatchPointOpers opers(MI);
00398     StartIdx = opers.getVarIdx();
00399     break;
00400   }
00401   default:
00402     llvm_unreachable("unexpected stackmap opcode");
00403   }
00404 
00405   // Return false if any operands requested for folding are not foldable (not
00406   // part of the stackmap's live values).
00407   for (SmallVectorImpl<unsigned>::const_iterator I = Ops.begin(), E = Ops.end();
00408        I != E; ++I) {
00409     if (*I < StartIdx)
00410       return nullptr;
00411   }
00412 
00413   MachineInstr *NewMI =
00414     MF.CreateMachineInstr(TII.get(MI->getOpcode()), MI->getDebugLoc(), true);
00415   MachineInstrBuilder MIB(MF, NewMI);
00416 
00417   // No need to fold return, the meta data, and function arguments
00418   for (unsigned i = 0; i < StartIdx; ++i)
00419     MIB.addOperand(MI->getOperand(i));
00420 
00421   for (unsigned i = StartIdx; i < MI->getNumOperands(); ++i) {
00422     MachineOperand &MO = MI->getOperand(i);
00423     if (std::find(Ops.begin(), Ops.end(), i) != Ops.end()) {
00424       unsigned SpillSize;
00425       unsigned SpillOffset;
00426       // Compute the spill slot size and offset.
00427       const TargetRegisterClass *RC =
00428         MF.getRegInfo().getRegClass(MO.getReg());
00429       bool Valid = TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize,
00430                                          SpillOffset, &MF.getTarget());
00431       if (!Valid)
00432         report_fatal_error("cannot spill patchpoint subregister operand");
00433       MIB.addImm(StackMaps::IndirectMemRefOp);
00434       MIB.addImm(SpillSize);
00435       MIB.addFrameIndex(FrameIndex);
00436       MIB.addImm(SpillOffset);
00437     }
00438     else
00439       MIB.addOperand(MO);
00440   }
00441   return NewMI;
00442 }
00443 
00444 /// foldMemoryOperand - Attempt to fold a load or store of the specified stack
00445 /// slot into the specified machine instruction for the specified operand(s).
00446 /// If this is possible, a new instruction is returned with the specified
00447 /// operand folded, otherwise NULL is returned. The client is responsible for
00448 /// removing the old instruction and adding the new one in the instruction
00449 /// stream.
00450 MachineInstr*
00451 TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
00452                                    const SmallVectorImpl<unsigned> &Ops,
00453                                    int FI) const {
00454   unsigned Flags = 0;
00455   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
00456     if (MI->getOperand(Ops[i]).isDef())
00457       Flags |= MachineMemOperand::MOStore;
00458     else
00459       Flags |= MachineMemOperand::MOLoad;
00460 
00461   MachineBasicBlock *MBB = MI->getParent();
00462   assert(MBB && "foldMemoryOperand needs an inserted instruction");
00463   MachineFunction &MF = *MBB->getParent();
00464 
00465   MachineInstr *NewMI = nullptr;
00466 
00467   if (MI->getOpcode() == TargetOpcode::STACKMAP ||
00468       MI->getOpcode() == TargetOpcode::PATCHPOINT) {
00469     // Fold stackmap/patchpoint.
00470     NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
00471   } else {
00472     // Ask the target to do the actual folding.
00473     NewMI =foldMemoryOperandImpl(MF, MI, Ops, FI);
00474   }
00475  
00476   if (NewMI) {
00477     NewMI->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
00478     // Add a memory operand, foldMemoryOperandImpl doesn't do that.
00479     assert((!(Flags & MachineMemOperand::MOStore) ||
00480             NewMI->mayStore()) &&
00481            "Folded a def to a non-store!");
00482     assert((!(Flags & MachineMemOperand::MOLoad) ||
00483             NewMI->mayLoad()) &&
00484            "Folded a use to a non-load!");
00485     const MachineFrameInfo &MFI = *MF.getFrameInfo();
00486     assert(MFI.getObjectOffset(FI) != -1);
00487     MachineMemOperand *MMO =
00488       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
00489                               Flags, MFI.getObjectSize(FI),
00490                               MFI.getObjectAlignment(FI));
00491     NewMI->addMemOperand(MF, MMO);
00492 
00493     // FIXME: change foldMemoryOperandImpl semantics to also insert NewMI.
00494     return MBB->insert(MI, NewMI);
00495   }
00496 
00497   // Straight COPY may fold as load/store.
00498   if (!MI->isCopy() || Ops.size() != 1)
00499     return nullptr;
00500 
00501   const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
00502   if (!RC)
00503     return nullptr;
00504 
00505   const MachineOperand &MO = MI->getOperand(1-Ops[0]);
00506   MachineBasicBlock::iterator Pos = MI;
00507   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
00508 
00509   if (Flags == MachineMemOperand::MOStore)
00510     storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
00511   else
00512     loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
00513   return --Pos;
00514 }
00515 
00516 /// foldMemoryOperand - Same as the previous version except it allows folding
00517 /// of any load and store from / to any address, not just from a specific
00518 /// stack slot.
00519 MachineInstr*
00520 TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
00521                                    const SmallVectorImpl<unsigned> &Ops,
00522                                    MachineInstr* LoadMI) const {
00523   assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
00524 #ifndef NDEBUG
00525   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
00526     assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
00527 #endif
00528   MachineBasicBlock &MBB = *MI->getParent();
00529   MachineFunction &MF = *MBB.getParent();
00530 
00531   // Ask the target to do the actual folding.
00532   MachineInstr *NewMI = nullptr;
00533   int FrameIndex = 0;
00534 
00535   if ((MI->getOpcode() == TargetOpcode::STACKMAP ||
00536        MI->getOpcode() == TargetOpcode::PATCHPOINT) &&
00537       isLoadFromStackSlot(LoadMI, FrameIndex)) {
00538     // Fold stackmap/patchpoint.
00539     NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
00540   } else {
00541     // Ask the target to do the actual folding.
00542     NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
00543   }
00544 
00545   if (!NewMI) return nullptr;
00546 
00547   NewMI = MBB.insert(MI, NewMI);
00548 
00549   // Copy the memoperands from the load to the folded instruction.
00550   if (MI->memoperands_empty()) {
00551     NewMI->setMemRefs(LoadMI->memoperands_begin(),
00552                       LoadMI->memoperands_end());
00553   }
00554   else {
00555     // Handle the rare case of folding multiple loads.
00556     NewMI->setMemRefs(MI->memoperands_begin(),
00557                       MI->memoperands_end());
00558     for (MachineInstr::mmo_iterator I = LoadMI->memoperands_begin(),
00559            E = LoadMI->memoperands_end(); I != E; ++I) {
00560       NewMI->addMemOperand(MF, *I);
00561     }
00562   }
00563   return NewMI;
00564 }
00565 
00566 bool TargetInstrInfo::
00567 isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
00568                                          AliasAnalysis *AA) const {
00569   const MachineFunction &MF = *MI->getParent()->getParent();
00570   const MachineRegisterInfo &MRI = MF.getRegInfo();
00571 
00572   // Remat clients assume operand 0 is the defined register.
00573   if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
00574     return false;
00575   unsigned DefReg = MI->getOperand(0).getReg();
00576 
00577   // A sub-register definition can only be rematerialized if the instruction
00578   // doesn't read the other parts of the register.  Otherwise it is really a
00579   // read-modify-write operation on the full virtual register which cannot be
00580   // moved safely.
00581   if (TargetRegisterInfo::isVirtualRegister(DefReg) &&
00582       MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg))
00583     return false;
00584 
00585   // A load from a fixed stack slot can be rematerialized. This may be
00586   // redundant with subsequent checks, but it's target-independent,
00587   // simple, and a common case.
00588   int FrameIdx = 0;
00589   if (isLoadFromStackSlot(MI, FrameIdx) &&
00590       MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
00591     return true;
00592 
00593   // Avoid instructions obviously unsafe for remat.
00594   if (MI->isNotDuplicable() || MI->mayStore() ||
00595       MI->hasUnmodeledSideEffects())
00596     return false;
00597 
00598   // Don't remat inline asm. We have no idea how expensive it is
00599   // even if it's side effect free.
00600   if (MI->isInlineAsm())
00601     return false;
00602 
00603   // Avoid instructions which load from potentially varying memory.
00604   if (MI->mayLoad() && !MI->isInvariantLoad(AA))
00605     return false;
00606 
00607   // If any of the registers accessed are non-constant, conservatively assume
00608   // the instruction is not rematerializable.
00609   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00610     const MachineOperand &MO = MI->getOperand(i);
00611     if (!MO.isReg()) continue;
00612     unsigned Reg = MO.getReg();
00613     if (Reg == 0)
00614       continue;
00615 
00616     // Check for a well-behaved physical register.
00617     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
00618       if (MO.isUse()) {
00619         // If the physreg has no defs anywhere, it's just an ambient register
00620         // and we can freely move its uses. Alternatively, if it's allocatable,
00621         // it could get allocated to something with a def during allocation.
00622         if (!MRI.isConstantPhysReg(Reg, MF))
00623           return false;
00624       } else {
00625         // A physreg def. We can't remat it.
00626         return false;
00627       }
00628       continue;
00629     }
00630 
00631     // Only allow one virtual-register def.  There may be multiple defs of the
00632     // same virtual register, though.
00633     if (MO.isDef() && Reg != DefReg)
00634       return false;
00635 
00636     // Don't allow any virtual-register uses. Rematting an instruction with
00637     // virtual register uses would length the live ranges of the uses, which
00638     // is not necessarily a good idea, certainly not "trivial".
00639     if (MO.isUse())
00640       return false;
00641   }
00642 
00643   // Everything checked out.
00644   return true;
00645 }
00646 
00647 /// isSchedulingBoundary - Test if the given instruction should be
00648 /// considered a scheduling boundary. This primarily includes labels
00649 /// and terminators.
00650 bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
00651                                            const MachineBasicBlock *MBB,
00652                                            const MachineFunction &MF) const {
00653   // Terminators and labels can't be scheduled around.
00654   if (MI->isTerminator() || MI->isPosition())
00655     return true;
00656 
00657   // Don't attempt to schedule around any instruction that defines
00658   // a stack-oriented pointer, as it's unlikely to be profitable. This
00659   // saves compile time, because it doesn't require every single
00660   // stack slot reference to depend on the instruction that does the
00661   // modification.
00662   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
00663   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
00664   if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI))
00665     return true;
00666 
00667   return false;
00668 }
00669 
00670 // Provide a global flag for disabling the PreRA hazard recognizer that targets
00671 // may choose to honor.
00672 bool TargetInstrInfo::usePreRAHazardRecognizer() const {
00673   return !DisableHazardRecognizer;
00674 }
00675 
00676 // Default implementation of CreateTargetRAHazardRecognizer.
00677 ScheduleHazardRecognizer *TargetInstrInfo::
00678 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
00679                              const ScheduleDAG *DAG) const {
00680   // Dummy hazard recognizer allows all instructions to issue.
00681   return new ScheduleHazardRecognizer();
00682 }
00683 
00684 // Default implementation of CreateTargetMIHazardRecognizer.
00685 ScheduleHazardRecognizer *TargetInstrInfo::
00686 CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
00687                                const ScheduleDAG *DAG) const {
00688   return (ScheduleHazardRecognizer *)
00689     new ScoreboardHazardRecognizer(II, DAG, "misched");
00690 }
00691 
00692 // Default implementation of CreateTargetPostRAHazardRecognizer.
00693 ScheduleHazardRecognizer *TargetInstrInfo::
00694 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
00695                                    const ScheduleDAG *DAG) const {
00696   return (ScheduleHazardRecognizer *)
00697     new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
00698 }
00699 
00700 //===----------------------------------------------------------------------===//
00701 //  SelectionDAG latency interface.
00702 //===----------------------------------------------------------------------===//
00703 
00704 int
00705 TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
00706                                    SDNode *DefNode, unsigned DefIdx,
00707                                    SDNode *UseNode, unsigned UseIdx) const {
00708   if (!ItinData || ItinData->isEmpty())
00709     return -1;
00710 
00711   if (!DefNode->isMachineOpcode())
00712     return -1;
00713 
00714   unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
00715   if (!UseNode->isMachineOpcode())
00716     return ItinData->getOperandCycle(DefClass, DefIdx);
00717   unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
00718   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
00719 }
00720 
00721 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
00722                                      SDNode *N) const {
00723   if (!ItinData || ItinData->isEmpty())
00724     return 1;
00725 
00726   if (!N->isMachineOpcode())
00727     return 1;
00728 
00729   return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
00730 }
00731 
00732 //===----------------------------------------------------------------------===//
00733 //  MachineInstr latency interface.
00734 //===----------------------------------------------------------------------===//
00735 
00736 unsigned
00737 TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
00738                                 const MachineInstr *MI) const {
00739   if (!ItinData || ItinData->isEmpty())
00740     return 1;
00741 
00742   unsigned Class = MI->getDesc().getSchedClass();
00743   int UOps = ItinData->Itineraries[Class].NumMicroOps;
00744   if (UOps >= 0)
00745     return UOps;
00746 
00747   // The # of u-ops is dynamically determined. The specific target should
00748   // override this function to return the right number.
00749   return 1;
00750 }
00751 
00752 /// Return the default expected latency for a def based on it's opcode.
00753 unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
00754                                             const MachineInstr *DefMI) const {
00755   if (DefMI->isTransient())
00756     return 0;
00757   if (DefMI->mayLoad())
00758     return SchedModel.LoadLatency;
00759   if (isHighLatencyDef(DefMI->getOpcode()))
00760     return SchedModel.HighLatency;
00761   return 1;
00762 }
00763 
00764 unsigned TargetInstrInfo::getPredicationCost(const MachineInstr *) const {
00765   return 0;
00766 }
00767 
00768 unsigned TargetInstrInfo::
00769 getInstrLatency(const InstrItineraryData *ItinData,
00770                 const MachineInstr *MI,
00771                 unsigned *PredCost) const {
00772   // Default to one cycle for no itinerary. However, an "empty" itinerary may
00773   // still have a MinLatency property, which getStageLatency checks.
00774   if (!ItinData)
00775     return MI->mayLoad() ? 2 : 1;
00776 
00777   return ItinData->getStageLatency(MI->getDesc().getSchedClass());
00778 }
00779 
00780 bool TargetInstrInfo::hasLowDefLatency(const InstrItineraryData *ItinData,
00781                                        const MachineInstr *DefMI,
00782                                        unsigned DefIdx) const {
00783   if (!ItinData || ItinData->isEmpty())
00784     return false;
00785 
00786   unsigned DefClass = DefMI->getDesc().getSchedClass();
00787   int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
00788   return (DefCycle != -1 && DefCycle <= 1);
00789 }
00790 
00791 /// Both DefMI and UseMI must be valid.  By default, call directly to the
00792 /// itinerary. This may be overriden by the target.
00793 int TargetInstrInfo::
00794 getOperandLatency(const InstrItineraryData *ItinData,
00795                   const MachineInstr *DefMI, unsigned DefIdx,
00796                   const MachineInstr *UseMI, unsigned UseIdx) const {
00797   unsigned DefClass = DefMI->getDesc().getSchedClass();
00798   unsigned UseClass = UseMI->getDesc().getSchedClass();
00799   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
00800 }
00801 
00802 /// If we can determine the operand latency from the def only, without itinerary
00803 /// lookup, do so. Otherwise return -1.
00804 int TargetInstrInfo::computeDefOperandLatency(
00805   const InstrItineraryData *ItinData,
00806   const MachineInstr *DefMI) const {
00807 
00808   // Let the target hook getInstrLatency handle missing itineraries.
00809   if (!ItinData)
00810     return getInstrLatency(ItinData, DefMI);
00811 
00812   if(ItinData->isEmpty())
00813     return defaultDefLatency(ItinData->SchedModel, DefMI);
00814 
00815   // ...operand lookup required
00816   return -1;
00817 }
00818 
00819 /// computeOperandLatency - Compute and return the latency of the given data
00820 /// dependent def and use when the operand indices are already known. UseMI may
00821 /// be NULL for an unknown use.
00822 ///
00823 /// FindMin may be set to get the minimum vs. expected latency. Minimum
00824 /// latency is used for scheduling groups, while expected latency is for
00825 /// instruction cost and critical path.
00826 ///
00827 /// Depending on the subtarget's itinerary properties, this may or may not need
00828 /// to call getOperandLatency(). For most subtargets, we don't need DefIdx or
00829 /// UseIdx to compute min latency.
00830 unsigned TargetInstrInfo::
00831 computeOperandLatency(const InstrItineraryData *ItinData,
00832                       const MachineInstr *DefMI, unsigned DefIdx,
00833                       const MachineInstr *UseMI, unsigned UseIdx) const {
00834 
00835   int DefLatency = computeDefOperandLatency(ItinData, DefMI);
00836   if (DefLatency >= 0)
00837     return DefLatency;
00838 
00839   assert(ItinData && !ItinData->isEmpty() && "computeDefOperandLatency fail");
00840 
00841   int OperLatency = 0;
00842   if (UseMI)
00843     OperLatency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
00844   else {
00845     unsigned DefClass = DefMI->getDesc().getSchedClass();
00846     OperLatency = ItinData->getOperandCycle(DefClass, DefIdx);
00847   }
00848   if (OperLatency >= 0)
00849     return OperLatency;
00850 
00851   // No operand latency was found.
00852   unsigned InstrLatency = getInstrLatency(ItinData, DefMI);
00853 
00854   // Expected latency is the max of the stage latency and itinerary props.
00855   InstrLatency = std::max(InstrLatency,
00856                           defaultDefLatency(ItinData->SchedModel, DefMI));
00857   return InstrLatency;
00858 }
00859 
00860 bool TargetInstrInfo::getRegSequenceInputs(
00861     const MachineInstr &MI, unsigned DefIdx,
00862     SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
00863   assert((MI.isRegSequence() ||
00864           MI.isRegSequenceLike()) && "Instruction do not have the proper type");
00865 
00866   if (!MI.isRegSequence())
00867     return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
00868 
00869   // We are looking at:
00870   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
00871   assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
00872   for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
00873        OpIdx += 2) {
00874     const MachineOperand &MOReg = MI.getOperand(OpIdx);
00875     const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
00876     assert(MOSubIdx.isImm() &&
00877            "One of the subindex of the reg_sequence is not an immediate");
00878     // Record Reg:SubReg, SubIdx.
00879     InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
00880                                             (unsigned)MOSubIdx.getImm()));
00881   }
00882   return true;
00883 }
00884 
00885 bool TargetInstrInfo::getExtractSubregInputs(
00886     const MachineInstr &MI, unsigned DefIdx,
00887     RegSubRegPairAndIdx &InputReg) const {
00888   assert((MI.isExtractSubreg() ||
00889       MI.isExtractSubregLike()) && "Instruction do not have the proper type");
00890 
00891   if (!MI.isExtractSubreg())
00892     return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
00893 
00894   // We are looking at:
00895   // Def = EXTRACT_SUBREG v0.sub1, sub0.
00896   assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
00897   const MachineOperand &MOReg = MI.getOperand(1);
00898   const MachineOperand &MOSubIdx = MI.getOperand(2);
00899   assert(MOSubIdx.isImm() &&
00900          "The subindex of the extract_subreg is not an immediate");
00901 
00902   InputReg.Reg = MOReg.getReg();
00903   InputReg.SubReg = MOReg.getSubReg();
00904   InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
00905   return true;
00906 }
00907 
00908 bool TargetInstrInfo::getInsertSubregInputs(
00909     const MachineInstr &MI, unsigned DefIdx,
00910     RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
00911   assert((MI.isInsertSubreg() ||
00912       MI.isInsertSubregLike()) && "Instruction do not have the proper type");
00913 
00914   if (!MI.isInsertSubreg())
00915     return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
00916 
00917   // We are looking at:
00918   // Def = INSERT_SEQUENCE v0, v1, sub0.
00919   assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
00920   const MachineOperand &MOBaseReg = MI.getOperand(1);
00921   const MachineOperand &MOInsertedReg = MI.getOperand(2);
00922   const MachineOperand &MOSubIdx = MI.getOperand(3);
00923   assert(MOSubIdx.isImm() &&
00924          "One of the subindex of the reg_sequence is not an immediate");
00925   BaseReg.Reg = MOBaseReg.getReg();
00926   BaseReg.SubReg = MOBaseReg.getSubReg();
00927 
00928   InsertedReg.Reg = MOInsertedReg.getReg();
00929   InsertedReg.SubReg = MOInsertedReg.getSubReg();
00930   InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
00931   return true;
00932 }