1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
14 //===----------------------------------------------------------------------===//
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineInstr.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Function.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/GraphWriter.h"
32 #include "llvm/Support/LeakDetector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Config/config.h"
39 static AnnotationID MF_AID(
40 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
42 // Out of line virtual function to home classes.
43 void MachineFunctionPass::virtfn() {}
46 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
50 const std::string Banner;
52 Printer (std::ostream *_OS, const std::string &_Banner)
53 : MachineFunctionPass((intptr_t)&ID), OS (_OS), Banner (_Banner) { }
55 const char *getPassName() const { return "MachineFunction Printer"; }
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 bool runOnMachineFunction(MachineFunction &MF) {
70 /// Returns a newly-created MachineFunction Printer pass. The default output
71 /// stream is std::cerr; the default banner is empty.
73 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
74 const std::string &Banner){
75 return new Printer(OS, Banner);
79 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
81 Deleter() : MachineFunctionPass((intptr_t)&ID) {}
83 const char *getPassName() const { return "Machine Code Deleter"; }
85 bool runOnMachineFunction(MachineFunction &MF) {
86 // Delete the annotation from the function now.
87 MachineFunction::destruct(MF.getFunction());
94 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
95 /// the current function, which should happen after the function has been
96 /// emitted to a .s file or to memory.
97 FunctionPass *llvm::createMachineCodeDeleter() {
103 //===---------------------------------------------------------------------===//
104 // MachineFunction implementation
105 //===---------------------------------------------------------------------===//
107 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
108 MachineBasicBlock* dummy = new MachineBasicBlock();
109 LeakDetector::removeGarbageObject(dummy);
113 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
114 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
115 ilist_iterator<MachineBasicBlock> first,
116 ilist_iterator<MachineBasicBlock> last) {
117 if (Parent != toList.Parent)
118 for (; first != last; ++first)
119 first->Parent = toList.Parent;
122 MachineFunction::MachineFunction(const Function *F,
123 const TargetMachine &TM)
124 : Annotation(MF_AID), Fn(F), Target(TM) {
125 RegInfo = new MachineRegisterInfo(*TM.getRegisterInfo());
127 FrameInfo = new MachineFrameInfo();
128 ConstantPool = new MachineConstantPool(TM.getTargetData());
130 // Set up jump table.
131 const TargetData &TD = *TM.getTargetData();
132 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
133 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
134 unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
135 : TD.getPointerABIAlignment();
136 JumpTableInfo = new MachineJumpTableInfo(EntrySize, Alignment);
138 BasicBlocks.Parent = this;
141 MachineFunction::~MachineFunction() {
147 delete JumpTableInfo;
151 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
152 /// recomputes them. This guarantees that the MBB numbers are sequential,
153 /// dense, and match the ordering of the blocks within the function. If a
154 /// specific MachineBasicBlock is specified, only that block and those after
155 /// it are renumbered.
156 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
157 if (empty()) { MBBNumbering.clear(); return; }
158 MachineFunction::iterator MBBI, E = end();
164 // Figure out the block number this should have.
165 unsigned BlockNo = 0;
167 BlockNo = prior(MBBI)->getNumber()+1;
169 for (; MBBI != E; ++MBBI, ++BlockNo) {
170 if (MBBI->getNumber() != (int)BlockNo) {
171 // Remove use of the old number.
172 if (MBBI->getNumber() != -1) {
173 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
174 "MBB number mismatch!");
175 MBBNumbering[MBBI->getNumber()] = 0;
178 // If BlockNo is already taken, set that block's number to -1.
179 if (MBBNumbering[BlockNo])
180 MBBNumbering[BlockNo]->setNumber(-1);
182 MBBNumbering[BlockNo] = MBBI;
183 MBBI->setNumber(BlockNo);
187 // Okay, all the blocks are renumbered. If we have compactified the block
188 // numbering, shrink MBBNumbering now.
189 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
190 MBBNumbering.resize(BlockNo);
194 void MachineFunction::dump() const { print(*cerr.stream()); }
196 void MachineFunction::print(std::ostream &OS) const {
197 OS << "# Machine code for " << Fn->getName () << "():\n";
199 // Print Frame Information
200 getFrameInfo()->print(*this, OS);
202 // Print JumpTable Information
203 getJumpTableInfo()->print(OS);
205 // Print Constant Pool
206 getConstantPool()->print(OS);
208 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
210 if (!RegInfo->livein_empty()) {
212 for (MachineRegisterInfo::livein_iterator
213 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
215 OS << " " << MRI->getName(I->first);
217 OS << " Reg #" << I->first;
220 OS << " in VR#" << I->second << " ";
224 if (!RegInfo->liveout_empty()) {
226 for (MachineRegisterInfo::liveout_iterator
227 I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
229 OS << " " << MRI->getName(*I);
231 OS << " Reg #" << *I;
235 for (const_iterator BB = begin(); BB != end(); ++BB)
238 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
241 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
242 /// prints out the contents of basic blocks or not. This is acceptable because
243 /// this code is only really used for debugging purposes.
245 static bool CFGOnly = false;
249 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
250 static std::string getGraphName(const MachineFunction *F) {
251 return "CFG for '" + F->getFunction()->getName() + "' function";
254 static std::string getNodeLabel(const MachineBasicBlock *Node,
255 const MachineFunction *Graph) {
256 if (CFGOnly && Node->getBasicBlock() &&
257 !Node->getBasicBlock()->getName().empty())
258 return Node->getBasicBlock()->getName() + ":";
260 std::ostringstream Out;
262 Out << Node->getNumber() << ':';
268 std::string OutStr = Out.str();
269 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
271 // Process string output to make it nicer...
272 for (unsigned i = 0; i != OutStr.length(); ++i)
273 if (OutStr[i] == '\n') { // Left justify
275 OutStr.insert(OutStr.begin()+i+1, 'l');
282 void MachineFunction::viewCFG() const
285 ViewGraph(this, "mf" + getFunction()->getName());
287 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
288 << "systems with Graphviz or gv!\n";
292 void MachineFunction::viewCFGOnly() const
299 // The next two methods are used to construct and to retrieve
300 // the MachineCodeForFunction object for the given function.
301 // construct() -- Allocates and initializes for a given function and target
302 // get() -- Returns a handle to the object.
303 // This should not be called before "construct()"
304 // for a given Function.
307 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
309 assert(Fn->getAnnotation(MF_AID) == 0 &&
310 "Object already exists for this function!");
311 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
312 Fn->addAnnotation(mcInfo);
316 void MachineFunction::destruct(const Function *Fn) {
317 bool Deleted = Fn->deleteAnnotation(MF_AID);
318 assert(Deleted && "Machine code did not exist for function!");
321 MachineFunction& MachineFunction::get(const Function *F)
323 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
324 assert(mc && "Call construct() method first to allocate the object");
328 //===----------------------------------------------------------------------===//
329 // MachineFrameInfo implementation
330 //===----------------------------------------------------------------------===//
332 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
333 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
335 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
336 const StackObject &SO = Objects[i];
337 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
339 OS << "variable sized";
341 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
342 OS << " alignment is " << SO.Alignment << " byte"
343 << (SO.Alignment != 1 ? "s," : ",");
345 if (i < NumFixedObjects)
347 if (i < NumFixedObjects || SO.SPOffset != -1) {
348 int64_t Off = SO.SPOffset - ValOffset;
349 OS << " at location [SP";
359 if (HasVarSizedObjects)
360 OS << " Stack frame contains variable sized objects\n";
363 void MachineFrameInfo::dump(const MachineFunction &MF) const {
364 print(MF, *cerr.stream());
368 //===----------------------------------------------------------------------===//
369 // MachineJumpTableInfo implementation
370 //===----------------------------------------------------------------------===//
372 /// getJumpTableIndex - Create a new jump table entry in the jump table info
373 /// or return an existing one.
375 unsigned MachineJumpTableInfo::getJumpTableIndex(
376 const std::vector<MachineBasicBlock*> &DestBBs) {
377 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
378 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
379 if (JumpTables[i].MBBs == DestBBs)
382 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
383 return JumpTables.size()-1;
387 void MachineJumpTableInfo::print(std::ostream &OS) const {
388 // FIXME: this is lame, maybe we could print out the MBB numbers or something
389 // like {1, 2, 4, 5, 3, 0}
390 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
391 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
396 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
399 //===----------------------------------------------------------------------===//
400 // MachineConstantPool implementation
401 //===----------------------------------------------------------------------===//
403 const Type *MachineConstantPoolEntry::getType() const {
404 if (isMachineConstantPoolEntry())
405 return Val.MachineCPVal->getType();
406 return Val.ConstVal->getType();
409 MachineConstantPool::~MachineConstantPool() {
410 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
411 if (Constants[i].isMachineConstantPoolEntry())
412 delete Constants[i].Val.MachineCPVal;
415 /// getConstantPoolIndex - Create a new entry in the constant pool or return
416 /// an existing one. User must specify an alignment in bytes for the object.
418 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
419 unsigned Alignment) {
420 assert(Alignment && "Alignment must be specified!");
421 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
423 // Check to see if we already have this constant.
425 // FIXME, this could be made much more efficient for large constant pools.
426 unsigned AlignMask = (1 << Alignment)-1;
427 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
428 if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
432 if (!Constants.empty()) {
433 Offset = Constants.back().getOffset();
434 Offset += TD->getABITypeSize(Constants.back().getType());
435 Offset = (Offset+AlignMask)&~AlignMask;
438 Constants.push_back(MachineConstantPoolEntry(C, Offset));
439 return Constants.size()-1;
442 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
443 unsigned Alignment) {
444 assert(Alignment && "Alignment must be specified!");
445 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
447 // Check to see if we already have this constant.
449 // FIXME, this could be made much more efficient for large constant pools.
450 unsigned AlignMask = (1 << Alignment)-1;
451 int Idx = V->getExistingMachineCPValue(this, Alignment);
453 return (unsigned)Idx;
456 if (!Constants.empty()) {
457 Offset = Constants.back().getOffset();
458 Offset += TD->getABITypeSize(Constants.back().getType());
459 Offset = (Offset+AlignMask)&~AlignMask;
462 Constants.push_back(MachineConstantPoolEntry(V, Offset));
463 return Constants.size()-1;
467 void MachineConstantPool::print(std::ostream &OS) const {
468 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
469 OS << " <cp #" << i << "> is";
470 if (Constants[i].isMachineConstantPoolEntry())
471 Constants[i].Val.MachineCPVal->print(OS);
473 OS << *(Value*)Constants[i].Val.ConstVal;
474 OS << " , offset=" << Constants[i].getOffset();
479 void MachineConstantPool::dump() const { print(*cerr.stream()); }