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