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