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 #define DEBUG_TYPE "codegen"
00042 
00043 //===----------------------------------------------------------------------===//
00044 // MachineFunction implementation
00045 //===----------------------------------------------------------------------===//
00046 
00047 // Out of line virtual method.
00048 MachineFunctionInfo::~MachineFunctionInfo() {}
00049 
00050 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
00051   MBB->getParent()->DeleteMachineBasicBlock(MBB);
00052 }
00053 
00054 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
00055                                  unsigned FunctionNum, MachineModuleInfo &mmi,
00056                                  GCModuleInfo* gmi)
00057   : Fn(F), Target(TM), Ctx(mmi.getContext()), MMI(mmi), GMI(gmi) {
00058   if (TM.getRegisterInfo())
00059     RegInfo = new (Allocator) MachineRegisterInfo(TM);
00060   else
00061     RegInfo = nullptr;
00062 
00063   MFInfo = nullptr;
00064   FrameInfo =
00065     new (Allocator) MachineFrameInfo(TM,!F->hasFnAttribute("no-realign-stack"));
00066 
00067   if (Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00068                                        Attribute::StackAlignment))
00069     FrameInfo->ensureMaxAlignment(Fn->getAttributes().
00070                                 getStackAlignment(AttributeSet::FunctionIndex));
00071 
00072   ConstantPool = new (Allocator) MachineConstantPool(TM);
00073   Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
00074 
00075   // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
00076   if (!Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00077                                         Attribute::OptimizeForSize))
00078     Alignment = std::max(Alignment,
00079                          TM.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 MDNode *TBAAInfo,
00233                                       const MDNode *Ranges) {
00234   return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
00235                                            TBAAInfo, 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(), nullptr);
00247   return new (Allocator)
00248              MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
00249                                                   MMO->getOffset()+Offset),
00250                                MMO->getFlags(), Size,
00251                                MMO->getBaseAlignment(), nullptr);
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)->getTBAAInfo());
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)->getTBAAInfo());
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 = getTarget().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_iterator BB = begin(), E = end(); BB != E; ++BB) {
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 const TargetFrameLowering *MachineFrameInfo::getFrameLowering() const {
00487   return TM.getFrameLowering();
00488 }
00489 
00490 /// ensureMaxAlignment - Make sure the function is at least Align bytes
00491 /// aligned.
00492 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
00493   if (!getFrameLowering()->isStackRealignable() || !RealignOption)
00494     assert(Align <= getFrameLowering()->getStackAlignment() &&
00495            "For targets without stack realignment, Align is out of limit!");
00496   if (MaxAlignment < Align) MaxAlignment = Align;
00497 }
00498 
00499 /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
00500 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
00501                                            unsigned StackAlign) {
00502   if (!ShouldClamp || Align <= StackAlign)
00503     return Align;
00504   DEBUG(dbgs() << "Warning: requested alignment " << Align
00505                << " exceeds the stack alignment " << StackAlign
00506                << " when stack realignment is off" << '\n');
00507   return StackAlign;
00508 }
00509 
00510 /// CreateStackObject - Create a new statically sized stack object, returning
00511 /// a nonnegative identifier to represent it.
00512 ///
00513 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
00514                       bool isSS, const AllocaInst *Alloca) {
00515   assert(Size != 0 && "Cannot allocate zero size stack objects!");
00516   Alignment =
00517     clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
00518                           !RealignOption,
00519                         Alignment, getFrameLowering()->getStackAlignment());
00520   Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca));
00521   int Index = (int)Objects.size() - NumFixedObjects - 1;
00522   assert(Index >= 0 && "Bad frame index!");
00523   ensureMaxAlignment(Alignment);
00524   return Index;
00525 }
00526 
00527 /// CreateSpillStackObject - Create a new statically sized stack object that
00528 /// represents a spill slot, returning a nonnegative identifier to represent
00529 /// it.
00530 ///
00531 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
00532                                              unsigned Alignment) {
00533   Alignment =
00534     clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
00535                           !RealignOption,
00536                         Alignment, getFrameLowering()->getStackAlignment()); 
00537   CreateStackObject(Size, Alignment, true);
00538   int Index = (int)Objects.size() - NumFixedObjects - 1;
00539   ensureMaxAlignment(Alignment);
00540   return Index;
00541 }
00542 
00543 /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
00544 /// variable sized object has been created.  This must be created whenever a
00545 /// variable sized object is created, whether or not the index returned is
00546 /// actually used.
00547 ///
00548 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
00549                                                 const AllocaInst *Alloca) {
00550   HasVarSizedObjects = true;
00551   Alignment =
00552     clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
00553                           !RealignOption,
00554                         Alignment, getFrameLowering()->getStackAlignment()); 
00555   Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca));
00556   ensureMaxAlignment(Alignment);
00557   return (int)Objects.size()-NumFixedObjects-1;
00558 }
00559 
00560 /// CreateFixedObject - Create a new object at a fixed location on the stack.
00561 /// All fixed objects should be created before other objects are created for
00562 /// efficiency. By default, fixed objects are immutable. This returns an
00563 /// index with a negative value.
00564 ///
00565 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
00566                                         bool Immutable) {
00567   assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
00568   // The alignment of the frame index can be determined from its offset from
00569   // the incoming frame position.  If the frame object is at offset 32 and
00570   // the stack is guaranteed to be 16-byte aligned, then we know that the
00571   // object is 16-byte aligned.
00572   unsigned StackAlign = getFrameLowering()->getStackAlignment();
00573   unsigned Align = MinAlign(SPOffset, StackAlign);
00574   Align =
00575     clampStackAlignment(!getFrameLowering()->isStackRealignable() ||
00576                           !RealignOption,
00577                         Align, getFrameLowering()->getStackAlignment()); 
00578   Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
00579                                               /*isSS*/   false,
00580                                               /*Alloca*/ nullptr));
00581   return -++NumFixedObjects;
00582 }
00583 
00584 
00585 BitVector
00586 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
00587   assert(MBB && "MBB must be valid");
00588   const MachineFunction *MF = MBB->getParent();
00589   assert(MF && "MBB must be part of a MachineFunction");
00590   const TargetMachine &TM = MF->getTarget();
00591   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
00592   BitVector BV(TRI->getNumRegs());
00593 
00594   // Before CSI is calculated, no registers are considered pristine. They can be
00595   // freely used and PEI will make sure they are saved.
00596   if (!isCalleeSavedInfoValid())
00597     return BV;
00598 
00599   for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
00600     BV.set(*CSR);
00601 
00602   // The entry MBB always has all CSRs pristine.
00603   if (MBB == &MF->front())
00604     return BV;
00605 
00606   // On other MBBs the saved CSRs are not pristine.
00607   const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
00608   for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
00609          E = CSI.end(); I != E; ++I)
00610     BV.reset(I->getReg());
00611 
00612   return BV;
00613 }
00614 
00615 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
00616   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
00617   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
00618   unsigned MaxAlign = getMaxAlignment();
00619   int Offset = 0;
00620 
00621   // This code is very, very similar to PEI::calculateFrameObjectOffsets().
00622   // It really should be refactored to share code. Until then, changes
00623   // should keep in mind that there's tight coupling between the two.
00624 
00625   for (int i = getObjectIndexBegin(); i != 0; ++i) {
00626     int FixedOff = -getObjectOffset(i);
00627     if (FixedOff > Offset) Offset = FixedOff;
00628   }
00629   for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
00630     if (isDeadObjectIndex(i))
00631       continue;
00632     Offset += getObjectSize(i);
00633     unsigned Align = getObjectAlignment(i);
00634     // Adjust to alignment boundary
00635     Offset = (Offset+Align-1)/Align*Align;
00636 
00637     MaxAlign = std::max(Align, MaxAlign);
00638   }
00639 
00640   if (adjustsStack() && TFI->hasReservedCallFrame(MF))
00641     Offset += getMaxCallFrameSize();
00642 
00643   // Round up the size to a multiple of the alignment.  If the function has
00644   // any calls or alloca's, align to the target's StackAlignment value to
00645   // ensure that the callee's frame or the alloca data is suitably aligned;
00646   // otherwise, for leaf functions, align to the TransientStackAlignment
00647   // value.
00648   unsigned StackAlign;
00649   if (adjustsStack() || hasVarSizedObjects() ||
00650       (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
00651     StackAlign = TFI->getStackAlignment();
00652   else
00653     StackAlign = TFI->getTransientStackAlignment();
00654 
00655   // If the frame pointer is eliminated, all frame offsets will be relative to
00656   // SP not FP. Align to MaxAlign so this works.
00657   StackAlign = std::max(StackAlign, MaxAlign);
00658   unsigned AlignMask = StackAlign - 1;
00659   Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
00660 
00661   return (unsigned)Offset;
00662 }
00663 
00664 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
00665   if (Objects.empty()) return;
00666 
00667   const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
00668   int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
00669 
00670   OS << "Frame Objects:\n";
00671 
00672   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
00673     const StackObject &SO = Objects[i];
00674     OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
00675     if (SO.Size == ~0ULL) {
00676       OS << "dead\n";
00677       continue;
00678     }
00679     if (SO.Size == 0)
00680       OS << "variable sized";
00681     else
00682       OS << "size=" << SO.Size;
00683     OS << ", align=" << SO.Alignment;
00684 
00685     if (i < NumFixedObjects)
00686       OS << ", fixed";
00687     if (i < NumFixedObjects || SO.SPOffset != -1) {
00688       int64_t Off = SO.SPOffset - ValOffset;
00689       OS << ", at location [SP";
00690       if (Off > 0)
00691         OS << "+" << Off;
00692       else if (Off < 0)
00693         OS << Off;
00694       OS << "]";
00695     }
00696     OS << "\n";
00697   }
00698 }
00699 
00700 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00701 void MachineFrameInfo::dump(const MachineFunction &MF) const {
00702   print(MF, dbgs());
00703 }
00704 #endif
00705 
00706 //===----------------------------------------------------------------------===//
00707 //  MachineJumpTableInfo implementation
00708 //===----------------------------------------------------------------------===//
00709 
00710 /// getEntrySize - Return the size of each entry in the jump table.
00711 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
00712   // The size of a jump table entry is 4 bytes unless the entry is just the
00713   // address of a block, in which case it is the pointer size.
00714   switch (getEntryKind()) {
00715   case MachineJumpTableInfo::EK_BlockAddress:
00716     return TD.getPointerSize();
00717   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
00718     return 8;
00719   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
00720   case MachineJumpTableInfo::EK_LabelDifference32:
00721   case MachineJumpTableInfo::EK_Custom32:
00722     return 4;
00723   case MachineJumpTableInfo::EK_Inline:
00724     return 0;
00725   }
00726   llvm_unreachable("Unknown jump table encoding!");
00727 }
00728 
00729 /// getEntryAlignment - Return the alignment of each entry in the jump table.
00730 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
00731   // The alignment of a jump table entry is the alignment of int32 unless the
00732   // entry is just the address of a block, in which case it is the pointer
00733   // alignment.
00734   switch (getEntryKind()) {
00735   case MachineJumpTableInfo::EK_BlockAddress:
00736     return TD.getPointerABIAlignment();
00737   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
00738     return TD.getABIIntegerTypeAlignment(64);
00739   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
00740   case MachineJumpTableInfo::EK_LabelDifference32:
00741   case MachineJumpTableInfo::EK_Custom32:
00742     return TD.getABIIntegerTypeAlignment(32);
00743   case MachineJumpTableInfo::EK_Inline:
00744     return 1;
00745   }
00746   llvm_unreachable("Unknown jump table encoding!");
00747 }
00748 
00749 /// createJumpTableIndex - Create a new jump table entry in the jump table info.
00750 ///
00751 unsigned MachineJumpTableInfo::createJumpTableIndex(
00752                                const std::vector<MachineBasicBlock*> &DestBBs) {
00753   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
00754   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
00755   return JumpTables.size()-1;
00756 }
00757 
00758 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
00759 /// the jump tables to branch to New instead.
00760 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
00761                                                   MachineBasicBlock *New) {
00762   assert(Old != New && "Not making a change?");
00763   bool MadeChange = false;
00764   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
00765     ReplaceMBBInJumpTable(i, Old, New);
00766   return MadeChange;
00767 }
00768 
00769 /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
00770 /// the jump table to branch to New instead.
00771 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
00772                                                  MachineBasicBlock *Old,
00773                                                  MachineBasicBlock *New) {
00774   assert(Old != New && "Not making a change?");
00775   bool MadeChange = false;
00776   MachineJumpTableEntry &JTE = JumpTables[Idx];
00777   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
00778     if (JTE.MBBs[j] == Old) {
00779       JTE.MBBs[j] = New;
00780       MadeChange = true;
00781     }
00782   return MadeChange;
00783 }
00784 
00785 void MachineJumpTableInfo::print(raw_ostream &OS) const {
00786   if (JumpTables.empty()) return;
00787 
00788   OS << "Jump Tables:\n";
00789 
00790   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
00791     OS << "  jt#" << i << ": ";
00792     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
00793       OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
00794   }
00795 
00796   OS << '\n';
00797 }
00798 
00799 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00800 void MachineJumpTableInfo::dump() const { print(dbgs()); }
00801 #endif
00802 
00803 
00804 //===----------------------------------------------------------------------===//
00805 //  MachineConstantPool implementation
00806 //===----------------------------------------------------------------------===//
00807 
00808 void MachineConstantPoolValue::anchor() { }
00809 
00810 const DataLayout *MachineConstantPool::getDataLayout() const {
00811   return TM.getDataLayout();
00812 }
00813 
00814 Type *MachineConstantPoolEntry::getType() const {
00815   if (isMachineConstantPoolEntry())
00816     return Val.MachineCPVal->getType();
00817   return Val.ConstVal->getType();
00818 }
00819 
00820 
00821 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
00822   if (isMachineConstantPoolEntry())
00823     return Val.MachineCPVal->getRelocationInfo();
00824   return Val.ConstVal->getRelocationInfo();
00825 }
00826 
00827 MachineConstantPool::~MachineConstantPool() {
00828   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00829     if (Constants[i].isMachineConstantPoolEntry())
00830       delete Constants[i].Val.MachineCPVal;
00831   for (DenseSet<MachineConstantPoolValue*>::iterator I =
00832        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
00833        I != E; ++I)
00834     delete *I;
00835 }
00836 
00837 /// CanShareConstantPoolEntry - Test whether the given two constants
00838 /// can be allocated the same constant pool entry.
00839 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
00840                                       const DataLayout *TD) {
00841   // Handle the trivial case quickly.
00842   if (A == B) return true;
00843 
00844   // If they have the same type but weren't the same constant, quickly
00845   // reject them.
00846   if (A->getType() == B->getType()) return false;
00847 
00848   // We can't handle structs or arrays.
00849   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
00850       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
00851     return false;
00852   
00853   // For now, only support constants with the same size.
00854   uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
00855   if (StoreSize != TD->getTypeStoreSize(B->getType()) || 
00856       StoreSize > 128)
00857     return false;
00858 
00859   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
00860 
00861   // Try constant folding a bitcast of both instructions to an integer.  If we
00862   // get two identical ConstantInt's, then we are good to share them.  We use
00863   // the constant folding APIs to do this so that we get the benefit of
00864   // DataLayout.
00865   if (isa<PointerType>(A->getType()))
00866     A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
00867                                  const_cast<Constant*>(A), TD);
00868   else if (A->getType() != IntTy)
00869     A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
00870                                  const_cast<Constant*>(A), TD);
00871   if (isa<PointerType>(B->getType()))
00872     B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
00873                                  const_cast<Constant*>(B), TD);
00874   else if (B->getType() != IntTy)
00875     B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
00876                                  const_cast<Constant*>(B), TD);
00877 
00878   return A == B;
00879 }
00880 
00881 /// getConstantPoolIndex - Create a new entry in the constant pool or return
00882 /// an existing one.  User must specify the log2 of the minimum required
00883 /// alignment for the object.
00884 ///
00885 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 
00886                                                    unsigned Alignment) {
00887   assert(Alignment && "Alignment must be specified!");
00888   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00889 
00890   // Check to see if we already have this constant.
00891   //
00892   // FIXME, this could be made much more efficient for large constant pools.
00893   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
00894     if (!Constants[i].isMachineConstantPoolEntry() &&
00895         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C,
00896                                   getDataLayout())) {
00897       if ((unsigned)Constants[i].getAlignment() < Alignment)
00898         Constants[i].Alignment = Alignment;
00899       return i;
00900     }
00901 
00902   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
00903   return Constants.size()-1;
00904 }
00905 
00906 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
00907                                                    unsigned Alignment) {
00908   assert(Alignment && "Alignment must be specified!");
00909   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
00910 
00911   // Check to see if we already have this constant.
00912   //
00913   // FIXME, this could be made much more efficient for large constant pools.
00914   int Idx = V->getExistingMachineCPValue(this, Alignment);
00915   if (Idx != -1) {
00916     MachineCPVsSharingEntries.insert(V);
00917     return (unsigned)Idx;
00918   }
00919 
00920   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
00921   return Constants.size()-1;
00922 }
00923 
00924 void MachineConstantPool::print(raw_ostream &OS) const {
00925   if (Constants.empty()) return;
00926 
00927   OS << "Constant Pool:\n";
00928   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
00929     OS << "  cp#" << i << ": ";
00930     if (Constants[i].isMachineConstantPoolEntry())
00931       Constants[i].Val.MachineCPVal->print(OS);
00932     else
00933       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
00934     OS << ", align=" << Constants[i].getAlignment();
00935     OS << "\n";
00936   }
00937 }
00938 
00939 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00940 void MachineConstantPool::dump() const { print(dbgs()); }
00941 #endif