LLVM API Documentation

MachineFunction.cpp
Go to the documentation of this file.
00001 //===-- MachineFunction.cpp -----------------------------------------------===//
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 // Collect native machine code information for a function.  This allows
00011 // target-specific information about the generated code to be stored with each
00012 // function.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/CodeGen/MachineFunction.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallString.h"
00019 #include "llvm/Analysis/ConstantFolding.h"
00020 #include "llvm/CodeGen/MachineConstantPool.h"
00021 #include "llvm/CodeGen/MachineFrameInfo.h"
00022 #include "llvm/CodeGen/MachineFunctionPass.h"
00023 #include "llvm/CodeGen/MachineInstr.h"
00024 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00025 #include "llvm/CodeGen/MachineModuleInfo.h"
00026 #include "llvm/CodeGen/MachineRegisterInfo.h"
00027 #include "llvm/CodeGen/Passes.h"
00028 #include "llvm/IR/DataLayout.h"
00029 #include "llvm/IR/DebugInfo.h"
00030 #include "llvm/IR/Function.h"
00031 #include "llvm/MC/MCAsmInfo.h"
00032 #include "llvm/MC/MCContext.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/GraphWriter.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetFrameLowering.h"
00037 #include "llvm/Target/TargetLowering.h"
00038 #include "llvm/Target/TargetMachine.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 using namespace llvm;
00041 
00042 #define DEBUG_TYPE "codegen"
00043 
00044 //===----------------------------------------------------------------------===//
00045 // MachineFunction implementation
00046 //===----------------------------------------------------------------------===//
00047 
00048 // Out of line virtual method.
00049 MachineFunctionInfo::~MachineFunctionInfo() {}
00050 
00051 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
00052   MBB->getParent()->DeleteMachineBasicBlock(MBB);
00053 }
00054 
00055 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
00056                                  unsigned FunctionNum, MachineModuleInfo &mmi)
00057     : Fn(F), Target(TM), STI(TM.getSubtargetImpl()), Ctx(mmi.getContext()),
00058       MMI(mmi) {
00059   if (STI->getRegisterInfo())
00060     RegInfo = new (Allocator) MachineRegisterInfo(this);
00061   else
00062     RegInfo = nullptr;
00063 
00064   MFInfo = nullptr;
00065   FrameInfo = new (Allocator)
00066       MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
00067                        STI->getFrameLowering()->isStackRealignable(),
00068                        !F->hasFnAttribute("no-realign-stack"));
00069 
00070   if (Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00071                                        Attribute::StackAlignment))
00072     FrameInfo->ensureMaxAlignment(Fn->getAttributes().
00073                                 getStackAlignment(AttributeSet::FunctionIndex));
00074 
00075   ConstantPool = new (Allocator) MachineConstantPool(TM);
00076   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
00077 
00078   // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
00079   if (!Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00080                                         Attribute::OptimizeForSize))
00081     Alignment = std::max(Alignment,
00082                          STI->getTargetLowering()->getPrefFunctionAlignment());
00083 
00084   FunctionNumber = FunctionNum;
00085   JumpTableInfo = nullptr;
00086 }
00087 
00088 MachineFunction::~MachineFunction() {
00089   // Don't call destructors on MachineInstr and MachineOperand. All of their
00090   // memory comes from the BumpPtrAllocator which is about to be purged.
00091   //
00092   // Do call MachineBasicBlock destructors, it contains std::vectors.
00093   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
00094     I->Insts.clearAndLeakNodesUnsafely();
00095 
00096   InstructionRecycler.clear(Allocator);
00097   OperandRecycler.clear(Allocator);
00098   BasicBlockRecycler.clear(Allocator);
00099   if (RegInfo) {
00100     RegInfo->~MachineRegisterInfo();
00101     Allocator.Deallocate(RegInfo);
00102   }
00103   if (MFInfo) {
00104     MFInfo->~MachineFunctionInfo();
00105     Allocator.Deallocate(MFInfo);
00106   }
00107 
00108   FrameInfo->~MachineFrameInfo();
00109   Allocator.Deallocate(FrameInfo);
00110 
00111   ConstantPool->~MachineConstantPool();
00112   Allocator.Deallocate(ConstantPool);
00113 
00114   if (JumpTableInfo) {
00115     JumpTableInfo->~MachineJumpTableInfo();
00116     Allocator.Deallocate(JumpTableInfo);
00117   }
00118 }
00119 
00120 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
00121 /// does already exist, allocate one.
00122 MachineJumpTableInfo *MachineFunction::
00123 getOrCreateJumpTableInfo(unsigned EntryKind) {
00124   if (JumpTableInfo) return JumpTableInfo;
00125 
00126   JumpTableInfo = new (Allocator)
00127     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
00128   return JumpTableInfo;
00129 }
00130 
00131 /// Should we be emitting segmented stack stuff for the function
00132 bool MachineFunction::shouldSplitStack() {
00133   return getFunction()->hasFnAttribute("split-stack");
00134 }
00135 
00136 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
00137 /// recomputes them.  This guarantees that the MBB numbers are sequential,
00138 /// dense, and match the ordering of the blocks within the function.  If a
00139 /// specific MachineBasicBlock is specified, only that block and those after
00140 /// it are renumbered.
00141 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
00142   if (empty()) { MBBNumbering.clear(); return; }
00143   MachineFunction::iterator MBBI, E = end();
00144   if (MBB == nullptr)
00145     MBBI = begin();
00146   else
00147     MBBI = MBB;
00148 
00149   // Figure out the block number this should have.
00150   unsigned BlockNo = 0;
00151   if (MBBI != begin())
00152     BlockNo = std::prev(MBBI)->getNumber() + 1;
00153 
00154   for (; MBBI != E; ++MBBI, ++BlockNo) {
00155     if (MBBI->getNumber() != (int)BlockNo) {
00156       // Remove use of the old number.
00157       if (MBBI->getNumber() != -1) {
00158         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
00159                "MBB number mismatch!");
00160         MBBNumbering[MBBI->getNumber()] = nullptr;
00161       }
00162 
00163       // If BlockNo is already taken, set that block's number to -1.
00164       if (MBBNumbering[BlockNo])
00165         MBBNumbering[BlockNo]->setNumber(-1);
00166 
00167       MBBNumbering[BlockNo] = MBBI;
00168       MBBI->setNumber(BlockNo);
00169     }
00170   }
00171 
00172   // Okay, all the blocks are renumbered.  If we have compactified the block
00173   // numbering, shrink MBBNumbering now.
00174   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
00175   MBBNumbering.resize(BlockNo);
00176 }
00177 
00178 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
00179 /// of `new MachineInstr'.
00180 ///
00181 MachineInstr *
00182 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
00183                                     DebugLoc DL, bool NoImp) {
00184   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
00185     MachineInstr(*this, MCID, DL, NoImp);
00186 }
00187 
00188 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
00189 /// 'Orig' instruction, identical in all ways except the instruction
00190 /// has no parent, prev, or next.
00191 ///
00192 MachineInstr *
00193 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
00194   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
00195              MachineInstr(*this, *Orig);
00196 }
00197 
00198 /// DeleteMachineInstr - Delete the given MachineInstr.
00199 ///
00200 /// This function also serves as the MachineInstr destructor - the real
00201 /// ~MachineInstr() destructor must be empty.
00202 void
00203 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
00204   // Strip it for parts. The operand array and the MI object itself are
00205   // independently recyclable.
00206   if (MI->Operands)
00207     deallocateOperandArray(MI->CapOperands, MI->Operands);
00208   // Don't call ~MachineInstr() which must be trivial anyway because
00209   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
00210   // destructors.
00211   InstructionRecycler.Deallocate(Allocator, MI);
00212 }
00213 
00214 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
00215 /// instead of `new MachineBasicBlock'.
00216 ///
00217 MachineBasicBlock *
00218 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
00219   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
00220              MachineBasicBlock(*this, bb);
00221 }
00222 
00223 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
00224 ///
00225 void
00226 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
00227   assert(MBB->getParent() == this && "MBB parent mismatch!");
00228   MBB->~MachineBasicBlock();
00229   BasicBlockRecycler.Deallocate(Allocator, MBB);
00230 }
00231 
00232 MachineMemOperand *
00233 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
00234                                       uint64_t s, unsigned base_alignment,
00235                                       const AAMDNodes &AAInfo,
00236                                       const MDNode *Ranges) {
00237   return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
00238                                            AAInfo, Ranges);
00239 }
00240 
00241 MachineMemOperand *
00242 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
00243                                       int64_t Offset, uint64_t Size) {
00244   if (MMO->getValue())
00245     return new (Allocator)
00246                MachineMemOperand(MachinePointerInfo(MMO->getValue(),
00247                                                     MMO->getOffset()+Offset),
00248                                  MMO->getFlags(), Size,
00249                                  MMO->getBaseAlignment());
00250   return new (Allocator)
00251              MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
00252                                                   MMO->getOffset()+Offset),
00253                                MMO->getFlags(), Size,
00254                                MMO->getBaseAlignment());
00255 }
00256 
00257 MachineInstr::mmo_iterator
00258 MachineFunction::allocateMemRefsArray(unsigned long Num) {
00259   return Allocator.Allocate<MachineMemOperand *>(Num);
00260 }
00261 
00262 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
00263 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
00264                                     MachineInstr::mmo_iterator End) {
00265   // Count the number of load mem refs.
00266   unsigned Num = 0;
00267   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
00268     if ((*I)->isLoad())
00269       ++Num;
00270 
00271   // Allocate a new array and populate it with the load information.
00272   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
00273   unsigned Index = 0;
00274   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
00275     if ((*I)->isLoad()) {
00276       if (!(*I)->isStore())
00277         // Reuse the MMO.
00278         Result[Index] = *I;
00279       else {
00280         // Clone the MMO and unset the store flag.
00281         MachineMemOperand *JustLoad =
00282           getMachineMemOperand((*I)->getPointerInfo(),
00283                                (*I)->getFlags() & ~MachineMemOperand::MOStore,
00284                                (*I)->getSize(), (*I)->getBaseAlignment(),
00285                                (*I)->getAAInfo());
00286         Result[Index] = JustLoad;
00287       }
00288       ++Index;
00289     }
00290   }
00291   return std::make_pair(Result, Result + Num);
00292 }
00293 
00294 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
00295 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
00296                                      MachineInstr::mmo_iterator End) {
00297   // Count the number of load mem refs.
00298   unsigned Num = 0;
00299   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
00300     if ((*I)->isStore())
00301       ++Num;
00302 
00303   // Allocate a new array and populate it with the store information.
00304   MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
00305   unsigned Index = 0;
00306   for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
00307     if ((*I)->isStore()) {
00308       if (!(*I)->isLoad())
00309         // Reuse the MMO.
00310         Result[Index] = *I;
00311       else {
00312         // Clone the MMO and unset the load flag.
00313         MachineMemOperand *JustStore =
00314           getMachineMemOperand((*I)->getPointerInfo(),
00315                                (*I)->getFlags() & ~MachineMemOperand::MOLoad,
00316                                (*I)->getSize(), (*I)->getBaseAlignment(),
00317                                (*I)->getAAInfo());
00318         Result[Index] = JustStore;
00319       }
00320       ++Index;
00321     }
00322   }
00323   return std::make_pair(Result, Result + Num);
00324 }
00325 
00326 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00327 void MachineFunction::dump() const {
00328   print(dbgs());
00329 }
00330 #endif
00331 
00332 StringRef MachineFunction::getName() const {
00333   assert(getFunction() && "No function!");
00334   return getFunction()->getName();
00335 }
00336 
00337 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
00338   OS << "# Machine code for function " << getName() << ": ";
00339   if (RegInfo) {
00340     OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
00341     if (!RegInfo->tracksLiveness())
00342       OS << ", not tracking liveness";
00343   }
00344   OS << '\n';
00345 
00346   // Print Frame Information
00347   FrameInfo->print(*this, OS);
00348 
00349   // Print JumpTable Information
00350   if (JumpTableInfo)
00351     JumpTableInfo->print(OS);
00352 
00353   // Print Constant Pool
00354   ConstantPool->print(OS);
00355 
00356   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
00357 
00358   if (RegInfo && !RegInfo->livein_empty()) {
00359     OS << "Function Live Ins: ";
00360     for (MachineRegisterInfo::livein_iterator
00361          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
00362       OS << PrintReg(I->first, TRI);
00363       if (I->second)
00364         OS << " in " << PrintReg(I->second, TRI);
00365       if (std::next(I) != E)
00366         OS << ", ";
00367     }
00368     OS << '\n';
00369   }
00370 
00371   for (const auto &BB : *this) {
00372     OS << '\n';
00373     BB.print(OS, Indexes);
00374   }
00375 
00376   OS << "\n# End machine code for function " << getName() << ".\n\n";
00377 }
00378 
00379 namespace llvm {
00380   template<>
00381   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
00382 
00383   DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
00384 
00385     static std::string getGraphName(const MachineFunction *F) {
00386       return "CFG for '" + F->getName().str() + "' function";
00387     }
00388 
00389     std::string getNodeLabel(const MachineBasicBlock *Node,
00390                              const MachineFunction *Graph) {
00391       std::string OutStr;
00392       {
00393         raw_string_ostream OSS(OutStr);
00394 
00395         if (isSimple()) {
00396           OSS << "BB#" << Node->getNumber();
00397           if (const BasicBlock *BB = Node->getBasicBlock())
00398             OSS << ": " << BB->getName();
00399         } else
00400           Node->print(OSS);
00401       }
00402 
00403       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
00404 
00405       // Process string output to make it nicer...
00406       for (unsigned i = 0; i != OutStr.length(); ++i)
00407         if (OutStr[i] == '\n') {                            // Left justify
00408           OutStr[i] = '\\';
00409           OutStr.insert(OutStr.begin()+i+1, 'l');
00410         }
00411       return OutStr;
00412     }
00413   };
00414 }
00415 
00416 void MachineFunction::viewCFG() const
00417 {
00418 #ifndef NDEBUG
00419   ViewGraph(this, "mf" + getName());
00420 #else
00421   errs() << "MachineFunction::viewCFG is only available in debug builds on "
00422          << "systems with Graphviz or gv!\n";
00423 #endif // NDEBUG
00424 }
00425 
00426 void MachineFunction::viewCFGOnly() const
00427 {
00428 #ifndef NDEBUG
00429   ViewGraph(this, "mf" + getName(), true);
00430 #else
00431   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
00432          << "systems with Graphviz or gv!\n";
00433 #endif // NDEBUG
00434 }
00435 
00436 /// addLiveIn - Add the specified physical register as a live-in value and
00437 /// create a corresponding virtual register for it.
00438 unsigned MachineFunction::addLiveIn(unsigned PReg,
00439                                     const TargetRegisterClass *RC) {
00440   MachineRegisterInfo &MRI = getRegInfo();
00441   unsigned VReg = MRI.getLiveInVirtReg(PReg);
00442   if (VReg) {
00443     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
00444     (void)VRegRC;
00445     // A physical register can be added several times.
00446     // Between two calls, the register class of the related virtual register
00447     // may have been constrained to match some operation constraints.
00448     // In that case, check that the current register class includes the
00449     // physical register and is a sub class of the specified RC.
00450     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
00451                              RC->hasSubClassEq(VRegRC))) &&
00452             "Register class mismatch!");
00453     return VReg;
00454   }
00455   VReg = MRI.createVirtualRegister(RC);
00456   MRI.addLiveIn(PReg, VReg);
00457   return VReg;
00458 }
00459 
00460 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
00461 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
00462 /// normal 'L' label is returned.
00463 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
00464                                         bool isLinkerPrivate) const {
00465   const DataLayout *DL = getSubtarget().getDataLayout();
00466   assert(JumpTableInfo && "No jump tables");
00467   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
00468 
00469   const char *Prefix = isLinkerPrivate ? DL->getLinkerPrivateGlobalPrefix() :
00470                                          DL->getPrivateGlobalPrefix();
00471   SmallString<60> Name;
00472   raw_svector_ostream(Name)
00473     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
00474   return Ctx.GetOrCreateSymbol(Name.str());
00475 }
00476 
00477 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
00478 /// base.
00479 MCSymbol *MachineFunction::getPICBaseSymbol() const {
00480   const DataLayout *DL = getSubtarget().getDataLayout();
00481   return Ctx.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
00482                                Twine(getFunctionNumber())+"$pb");
00483 }
00484 
00485 //===----------------------------------------------------------------------===//
00486 //  MachineFrameInfo implementation
00487 //===----------------------------------------------------------------------===//
00488 
00489 /// ensureMaxAlignment - Make sure the function is at least Align bytes
00490 /// aligned.
00491 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
00492   if (!StackRealignable || !RealignOption)
00493     assert(Align <= StackAlignment &&
00494            "For targets without stack realignment, Align is out of limit!");
00495   if (MaxAlignment < Align) MaxAlignment = Align;
00496 }
00497 
00498 /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
00499 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
00500                                            unsigned StackAlign) {
00501   if (!ShouldClamp || Align <= StackAlign)
00502     return Align;
00503   DEBUG(dbgs() << "Warning: requested alignment " << Align
00504                << " exceeds the stack alignment " << StackAlign
00505                << " when stack realignment is off" << '\n');
00506   return StackAlign;
00507 }
00508 
00509 /// CreateStackObject - Create a new statically sized stack object, returning
00510 /// a nonnegative identifier to represent it.
00511 ///
00512 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
00513                       bool isSS, const AllocaInst *Alloca) {
00514   assert(Size != 0 && "Cannot allocate zero size stack objects!");
00515   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00516                                   Alignment, StackAlignment);
00517   Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
00518                                 !isSS));
00519   int Index = (int)Objects.size() - NumFixedObjects - 1;
00520   assert(Index >= 0 && "Bad frame index!");
00521   ensureMaxAlignment(Alignment);
00522   return Index;
00523 }
00524 
00525 /// CreateSpillStackObject - Create a new statically sized stack object that
00526 /// represents a spill slot, returning a nonnegative identifier to represent
00527 /// it.
00528 ///
00529 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
00530                                              unsigned Alignment) {
00531   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00532                                   Alignment, StackAlignment);
00533   CreateStackObject(Size, Alignment, true);
00534   int Index = (int)Objects.size() - NumFixedObjects - 1;
00535   ensureMaxAlignment(Alignment);
00536   return Index;
00537 }
00538 
00539 /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
00540 /// variable sized object has been created.  This must be created whenever a
00541 /// variable sized object is created, whether or not the index returned is
00542 /// actually used.
00543 ///
00544 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
00545                                                 const AllocaInst *Alloca) {
00546   HasVarSizedObjects = true;
00547   Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
00548                                   Alignment, StackAlignment);
00549   Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
00550   ensureMaxAlignment(Alignment);
00551   return (int)Objects.size()-NumFixedObjects-1;
00552 }
00553 
00554 /// CreateFixedObject - Create a new object at a fixed location on the stack.
00555 /// All fixed objects should be created before other objects are created for
00556 /// efficiency. By default, fixed objects are immutable. This returns an
00557 /// index with a negative value.
00558 ///
00559 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
00560                                         bool Immutable, bool isAliased) {
00561   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
00562   // The alignment of the frame index can be determined from its offset from
00563   // the incoming frame position.  If the frame object is at offset 32 and
00564   // the stack is guaranteed to be 16-byte aligned, then we know that the
00565   // object is 16-byte aligned.
00566   unsigned Align = MinAlign(SPOffset, StackAlignment);
00567   Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
00568                               StackAlignment);
00569   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
00570                                               /*isSS*/   false,
00571                                               /*Alloca*/ nullptr, isAliased));
00572   return -++NumFixedObjects;
00573 }
00574 
00575 /// CreateFixedSpillStackObject - Create a spill slot at a fixed location
00576 /// on the stack.  Returns an index with a negative value.
00577 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
00578                                                   int64_t SPOffset) {
00579   unsigned Align = MinAlign(SPOffset, StackAlignment);
00580   Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
00581                               StackAlignment);
00582   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
00583                                               /*Immutable*/ true,
00584                                               /*isSS*/ true,
00585                                               /*Alloca*/ nullptr,
00586                                               /*isAliased*/ false));
00587   return -++NumFixedObjects;
00588 }
00589 
00590 BitVector
00591 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
00592   assert(MBB && "MBB must be valid");
00593   const MachineFunction *MF = MBB->getParent();
00594   assert(MF && "MBB must be part of a MachineFunction");
00595   const TargetMachine &TM = MF->getTarget();
00596   const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
00597   BitVector BV(TRI->getNumRegs());
00598 
00599   // Before CSI is calculated, no registers are considered pristine. They can be
00600   // freely used and PEI will make sure they are saved.
00601   if (!isCalleeSavedInfoValid())
00602     return BV;
00603 
00604   for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
00605     BV.set(*CSR);
00606 
00607   // The entry MBB always has all CSRs pristine.
00608   if (MBB == &MF->front())
00609     return BV;
00610 
00611   // On other MBBs the saved CSRs are not pristine.
00612   const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
00613   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
00614          E = CSI.end(); I != E; ++I)
00615     BV.reset(I->getReg());
00616 
00617   return BV;
00618 }
00619 
00620 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
00621   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
00622   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
00623   unsigned MaxAlign = getMaxAlignment();
00624   int Offset = 0;
00625 
00626   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
00627   // It really should be refactored to share code. Until then, changes
00628   // should keep in mind that there's tight coupling between the two.
00629 
00630   for (int i = getObjectIndexBegin(); i != 0; ++i) {
00631     int FixedOff = -getObjectOffset(i);
00632     if (FixedOff > Offset) Offset = FixedOff;
00633   }
00634   for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
00635     if (isDeadObjectIndex(i))
00636       continue;
00637     Offset += getObjectSize(i);
00638     unsigned Align = getObjectAlignment(i);
00639     // Adjust to alignment boundary
00640     Offset = (Offset+Align-1)/Align*Align;
00641 
00642     MaxAlign = std::max(Align, MaxAlign);
00643   }
00644 
00645   if (adjustsStack() && TFI->hasReservedCallFrame(MF))
00646     Offset += getMaxCallFrameSize();
00647 
00648   // Round up the size to a multiple of the alignment.  If the function has
00649   // any calls or alloca's, align to the target's StackAlignment value to
00650   // ensure that the callee's frame or the alloca data is suitably aligned;
00651   // otherwise, for leaf functions, align to the TransientStackAlignment
00652   // value.
00653   unsigned StackAlign;
00654   if (adjustsStack() || hasVarSizedObjects() ||
00655       (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
00656     StackAlign = TFI->getStackAlignment();
00657   else
00658     StackAlign = TFI->getTransientStackAlignment();
00659 
00660   // If the frame pointer is eliminated, all frame offsets will be relative to
00661   // SP not FP. Align to MaxAlign so this works.
00662   StackAlign = std::max(StackAlign, MaxAlign);
00663   unsigned AlignMask = StackAlign - 1;
00664   Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
00665 
00666   return (unsigned)Offset;
00667 }
00668 
00669 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
00670   if (Objects.empty()) return;
00671 
00672   const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
00673   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
00674 
00675   OS << "Frame Objects:\n";
00676 
00677   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
00678     const StackObject &SO = Objects[i];
00679     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
00680     if (SO.Size == ~0ULL) {
00681       OS << "dead\n";
00682       continue;
00683     }
00684     if (SO.Size == 0)
00685       OS << "variable sized";
00686     else
00687       OS << "size=" << SO.Size;
00688     OS << ", align=" << SO.Alignment;
00689 
00690     if (i < NumFixedObjects)
00691       OS << ", fixed";
00692     if (i < NumFixedObjects || SO.SPOffset != -1) {
00693       int64_t Off = SO.SPOffset - ValOffset;
00694       OS << ", at location [SP";
00695       if (Off > 0)
00696         OS << "+" << Off;
00697       else if (Off < 0)
00698         OS << Off;
00699       OS << "]";
00700     }
00701     OS << "\n";
00702   }
00703 }
00704 
00705 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00706 void MachineFrameInfo::dump(const MachineFunction &MF) const {
00707   print(MF, dbgs());
00708 }
00709 #endif
00710 
00711 //===----------------------------------------------------------------------===//
00712 //  MachineJumpTableInfo implementation
00713 //===----------------------------------------------------------------------===//
00714 
00715 /// getEntrySize - Return the size of each entry in the jump table.
00716 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
00717   // The size of a jump table entry is 4 bytes unless the entry is just the
00718   // address of a block, in which case it is the pointer size.
00719   switch (getEntryKind()) {
00720   case MachineJumpTableInfo::EK_BlockAddress:
00721     return TD.getPointerSize();
00722   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
00723     return 8;
00724   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
00725   case MachineJumpTableInfo::EK_LabelDifference32:
00726   case MachineJumpTableInfo::EK_Custom32:
00727     return 4;
00728   case MachineJumpTableInfo::EK_Inline:
00729     return 0;
00730   }
00731   llvm_unreachable("Unknown jump table encoding!");
00732 }
00733 
00734 /// getEntryAlignment - Return the alignment of each entry in the jump table.
00735 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
00736   // The alignment of a jump table entry is the alignment of int32 unless the
00737   // entry is just the address of a block, in which case it is the pointer
00738   // alignment.
00739   switch (getEntryKind()) {
00740   case MachineJumpTableInfo::EK_BlockAddress:
00741     return TD.getPointerABIAlignment();
00742   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
00743     return TD.getABIIntegerTypeAlignment(64);
00744   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
00745   case MachineJumpTableInfo::EK_LabelDifference32:
00746   case MachineJumpTableInfo::EK_Custom32:
00747     return TD.getABIIntegerTypeAlignment(32);
00748   case MachineJumpTableInfo::EK_Inline:
00749     return 1;
00750   }
00751   llvm_unreachable("Unknown jump table encoding!");
00752 }
00753 
00754 /// createJumpTableIndex - Create a new jump table entry in the jump table info.
00755 ///
00756 unsigned MachineJumpTableInfo::createJumpTableIndex(
00757                                const std::vector<MachineBasicBlock*> &DestBBs) {
00758   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
00759   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
00760   return JumpTables.size()-1;
00761 }
00762 
00763 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
00764 /// the jump tables to branch to New instead.
00765 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
00766                                                   MachineBasicBlock *New) {
00767   assert(Old != New && "Not making a change?");
00768   bool MadeChange = false;
00769   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
00770     ReplaceMBBInJumpTable(i, Old, New);
00771   return MadeChange;
00772 }
00773 
00774 /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
00775 /// the jump table to branch to New instead.
00776 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
00777                                                  MachineBasicBlock *Old,
00778                                                  MachineBasicBlock *New) {
00779   assert(Old != New && "Not making a change?");
00780   bool MadeChange = false;
00781   MachineJumpTableEntry &JTE = JumpTables[Idx];
00782   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
00783     if (JTE.MBBs[j] == Old) {
00784       JTE.MBBs[j] = New;
00785       MadeChange = true;
00786     }
00787   return MadeChange;
00788 }
00789 
00790 void MachineJumpTableInfo::print(raw_ostream &OS) const {
00791   if (JumpTables.empty()) return;
00792 
00793   OS << "Jump Tables:\n";
00794 
00795   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
00796     OS << "  jt#" << i << ": ";
00797     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
00798       OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
00799   }
00800 
00801   OS << '\n';
00802 }
00803 
00804 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00805 void MachineJumpTableInfo::dump() const { print(dbgs()); }
00806 #endif
00807 
00808 
00809 //===----------------------------------------------------------------------===//
00810 //  MachineConstantPool implementation
00811 //===----------------------------------------------------------------------===//
00812 
00813 void MachineConstantPoolValue::anchor() { }
00814 
00815 const DataLayout *MachineConstantPool::getDataLayout() const {
00816   return TM.getSubtargetImpl()->getDataLayout();
00817 }
00818 
00819 Type *MachineConstantPoolEntry::getType() const {
00820   if (isMachineConstantPoolEntry())
00821     return Val.MachineCPVal->getType();
00822   return Val.ConstVal->getType();
00823 }
00824 
00825 
00826 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
00827   if (isMachineConstantPoolEntry())
00828     return Val.MachineCPVal->getRelocationInfo();
00829   return Val.ConstVal->getRelocationInfo();
00830 }
00831 
00832 SectionKind
00833 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
00834   SectionKind Kind;
00835   switch (getRelocationInfo()) {
00836   default:
00837     llvm_unreachable("Unknown section kind");
00838   case 2:
00839     Kind = SectionKind::getReadOnlyWithRel();
00840     break;
00841   case 1:
00842     Kind = SectionKind::getReadOnlyWithRelLocal();
00843     break;
00844   case 0:
00845     switch (DL->getTypeAllocSize(getType())) {
00846     case 4:
00847       Kind = SectionKind::getMergeableConst4();
00848       break;
00849     case 8:
00850       Kind = SectionKind::getMergeableConst8();
00851       break;
00852     case 16:
00853       Kind = SectionKind::getMergeableConst16();
00854       break;
00855     default:
00856       Kind = SectionKind::getMergeableConst();
00857       break;
00858     }
00859   }
00860   return Kind;
00861 }
00862 
00863 MachineConstantPool::~MachineConstantPool() {
00864   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00865     if (Constants[i].isMachineConstantPoolEntry())
00866       delete Constants[i].Val.MachineCPVal;
00867   for (DenseSet<MachineConstantPoolValue*>::iterator I =
00868        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
00869        I != E; ++I)
00870     delete *I;
00871 }
00872 
00873 /// CanShareConstantPoolEntry - Test whether the given two constants
00874 /// can be allocated the same constant pool entry.
00875 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
00876                                       const DataLayout *TD) {
00877   // Handle the trivial case quickly.
00878   if (A == B) return true;
00879 
00880   // If they have the same type but weren't the same constant, quickly
00881   // reject them.
00882   if (A->getType() == B->getType()) return false;
00883 
00884   // We can't handle structs or arrays.
00885   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
00886       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
00887     return false;
00888 
00889   // For now, only support constants with the same size.
00890   uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
00891   if (StoreSize != TD->getTypeStoreSize(B->getType()) || StoreSize > 128)
00892     return false;
00893 
00894   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
00895 
00896   // Try constant folding a bitcast of both instructions to an integer.  If we
00897   // get two identical ConstantInt's, then we are good to share them.  We use
00898   // the constant folding APIs to do this so that we get the benefit of
00899   // DataLayout.
00900   if (isa<PointerType>(A->getType()))
00901     A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
00902                                  const_cast<Constant*>(A), TD);
00903   else if (A->getType() != IntTy)
00904     A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
00905                                  const_cast<Constant*>(A), TD);
00906   if (isa<PointerType>(B->getType()))
00907     B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
00908                                  const_cast<Constant*>(B), TD);
00909   else if (B->getType() != IntTy)
00910     B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
00911                                  const_cast<Constant*>(B), TD);
00912 
00913   return A == B;
00914 }
00915 
00916 /// getConstantPoolIndex - Create a new entry in the constant pool or return
00917 /// an existing one.  User must specify the log2 of the minimum required
00918 /// alignment for the object.
00919 ///
00920 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
00921                                                    unsigned Alignment) {
00922   assert(Alignment && "Alignment must be specified!");
00923   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00924 
00925   // Check to see if we already have this constant.
00926   //
00927   // FIXME, this could be made much more efficient for large constant pools.
00928   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00929     if (!Constants[i].isMachineConstantPoolEntry() &&
00930         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
00931                                   getDataLayout())) {
00932       if ((unsigned)Constants[i].getAlignment() < Alignment)
00933         Constants[i].Alignment = Alignment;
00934       return i;
00935     }
00936 
00937   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
00938   return Constants.size()-1;
00939 }
00940 
00941 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
00942                                                    unsigned Alignment) {
00943   assert(Alignment && "Alignment must be specified!");
00944   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00945 
00946   // Check to see if we already have this constant.
00947   //
00948   // FIXME, this could be made much more efficient for large constant pools.
00949   int Idx = V->getExistingMachineCPValue(this, Alignment);
00950   if (Idx != -1) {
00951     MachineCPVsSharingEntries.insert(V);
00952     return (unsigned)Idx;
00953   }
00954 
00955   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
00956   return Constants.size()-1;
00957 }
00958 
00959 void MachineConstantPool::print(raw_ostream &OS) const {
00960   if (Constants.empty()) return;
00961 
00962   OS << "Constant Pool:\n";
00963   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
00964     OS << "  cp#" << i << ": ";
00965     if (Constants[i].isMachineConstantPoolEntry())
00966       Constants[i].Val.MachineCPVal->print(OS);
00967     else
00968       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
00969     OS << ", align=" << Constants[i].getAlignment();
00970     OS << "\n";
00971   }
00972 }
00973 
00974 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00975 void MachineConstantPool::dump() const { print(dbgs()); }
00976 #endif