21f41b95b00cb20f9091da95dd698ada2fe0d3d7
[oota-llvm.git] / lib / CodeGen / MachineFunction.cpp
1 //===-- MachineFunction.cpp -----------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect native machine code information for a function.  This allows
11 // target-specific information about the generated code to be stored with each
12 // function.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineInstr.h"
18 #include "llvm/CodeGen/SSARegMap.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Support/LeakDetector.h"
29 #include "llvm/Support/GraphWriter.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Config/config.h"
32 #include <fstream>
33 #include <iostream>
34 #include <sstream>
35
36 using namespace llvm;
37
38 static AnnotationID MF_AID(
39   AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
40
41 // Out of line virtual function to home classes.
42 void MachineFunctionPass::virtfn() {}
43
44 namespace {
45   struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
46     std::ostream *OS;
47     const std::string Banner;
48
49     Printer (std::ostream *_OS, const std::string &_Banner) :
50       OS (_OS), Banner (_Banner) { }
51
52     const char *getPassName() const { return "MachineFunction Printer"; }
53
54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       AU.setPreservesAll();
56     }
57
58     bool runOnMachineFunction(MachineFunction &MF) {
59       (*OS) << Banner;
60       MF.print (*OS);
61       return false;
62     }
63   };
64 }
65
66 /// Returns a newly-created MachineFunction Printer pass. The default output
67 /// stream is std::cerr; the default banner is empty.
68 ///
69 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
70                                                      const std::string &Banner){
71   return new Printer(OS, Banner);
72 }
73
74 namespace {
75   struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
76     const char *getPassName() const { return "Machine Code Deleter"; }
77
78     bool runOnMachineFunction(MachineFunction &MF) {
79       // Delete the annotation from the function now.
80       MachineFunction::destruct(MF.getFunction());
81       return true;
82     }
83   };
84 }
85
86 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
87 /// the current function, which should happen after the function has been
88 /// emitted to a .s file or to memory.
89 FunctionPass *llvm::createMachineCodeDeleter() {
90   return new Deleter();
91 }
92
93
94
95 //===---------------------------------------------------------------------===//
96 // MachineFunction implementation
97 //===---------------------------------------------------------------------===//
98
99 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
100   MachineBasicBlock* dummy = new MachineBasicBlock();
101   LeakDetector::removeGarbageObject(dummy);
102   return dummy;
103 }
104
105 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
106   iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
107   ilist_iterator<MachineBasicBlock> first,
108   ilist_iterator<MachineBasicBlock> last) {
109   if (Parent != toList.Parent)
110     for (; first != last; ++first)
111       first->Parent = toList.Parent;
112 }
113
114 MachineFunction::MachineFunction(const Function *F,
115                                  const TargetMachine &TM)
116   : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
117   SSARegMapping = new SSARegMap();
118   MFInfo = 0;
119   FrameInfo = new MachineFrameInfo();
120   ConstantPool = new MachineConstantPool(TM.getTargetData());
121   JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
122   BasicBlocks.Parent = this;
123 }
124
125 MachineFunction::~MachineFunction() {
126   BasicBlocks.clear();
127   delete SSARegMapping;
128   delete MFInfo;
129   delete FrameInfo;
130   delete ConstantPool;
131   delete JumpTableInfo;
132   delete[] UsedPhysRegs;
133 }
134
135
136 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
137 /// recomputes them.  This guarantees that the MBB numbers are sequential,
138 /// dense, and match the ordering of the blocks within the function.  If a
139 /// specific MachineBasicBlock is specified, only that block and those after
140 /// it are renumbered.
141 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
142   if (empty()) { MBBNumbering.clear(); return; }
143   MachineFunction::iterator MBBI, E = end();
144   if (MBB == 0)
145     MBBI = begin();
146   else
147     MBBI = MBB;
148   
149   // Figure out the block number this should have.
150   unsigned BlockNo = 0;
151   if (MBB != &front()) {
152     MachineFunction::iterator I = MBB;
153     --I;
154     BlockNo = I->getNumber()+1;
155   }
156   
157   for (; MBBI != E; ++MBBI, ++BlockNo) {
158     if (MBBI->getNumber() != (int)BlockNo) {
159       // Remove use of the old number.
160       if (MBBI->getNumber() != -1) {
161         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
162                "MBB number mismatch!");
163         MBBNumbering[MBBI->getNumber()] = 0;
164       }
165       
166       // If BlockNo is already taken, set that block's number to -1.
167       if (MBBNumbering[BlockNo])
168         MBBNumbering[BlockNo]->setNumber(-1);
169
170       MBBNumbering[BlockNo] = MBBI;
171       MBBI->setNumber(BlockNo);
172     }
173   }    
174
175   // Okay, all the blocks are renumbered.  If we have compactified the block
176   // numbering, shrink MBBNumbering now.
177   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
178   MBBNumbering.resize(BlockNo);
179 }
180
181
182 void MachineFunction::dump() const { print(std::cerr); }
183
184 void MachineFunction::print(std::ostream &OS) const {
185   OS << "# Machine code for " << Fn->getName () << "():\n";
186
187   // Print Frame Information
188   getFrameInfo()->print(*this, OS);
189   
190   // Print JumpTable Information
191   getJumpTableInfo()->print(OS);
192
193   // Print Constant Pool
194   getConstantPool()->print(OS);
195   
196   const MRegisterInfo *MRI = getTarget().getRegisterInfo();
197   
198   if (livein_begin() != livein_end()) {
199     OS << "Live Ins:";
200     for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
201       if (MRI)
202         OS << " " << MRI->getName(I->first);
203       else
204         OS << " Reg #" << I->first;
205       
206       if (I->second)
207         OS << " in VR#" << I->second << " ";
208     }
209     OS << "\n";
210   }
211   if (liveout_begin() != liveout_end()) {
212     OS << "Live Outs:";
213     for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
214       if (MRI)
215         OS << " " << MRI->getName(*I);
216       else
217         OS << " Reg #" << *I;
218     OS << "\n";
219   }
220   
221   for (const_iterator BB = begin(); BB != end(); ++BB)
222     BB->print(OS);
223
224   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
225 }
226
227 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
228 /// prints out the contents of basic blocks or not.  This is acceptable because
229 /// this code is only really used for debugging purposes.
230 ///
231 static bool CFGOnly = false;
232
233 namespace llvm {
234   template<>
235   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
236     static std::string getGraphName(const MachineFunction *F) {
237       return "CFG for '" + F->getFunction()->getName() + "' function";
238     }
239
240     static std::string getNodeLabel(const MachineBasicBlock *Node,
241                                     const MachineFunction *Graph) {
242       if (CFGOnly && Node->getBasicBlock() &&
243           !Node->getBasicBlock()->getName().empty())
244         return Node->getBasicBlock()->getName() + ":";
245
246       std::ostringstream Out;
247       if (CFGOnly) {
248         Out << Node->getNumber() << ':';
249         return Out.str();
250       }
251
252       Node->print(Out);
253
254       std::string OutStr = Out.str();
255       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
256
257       // Process string output to make it nicer...
258       for (unsigned i = 0; i != OutStr.length(); ++i)
259         if (OutStr[i] == '\n') {                            // Left justify
260           OutStr[i] = '\\';
261           OutStr.insert(OutStr.begin()+i+1, 'l');
262         }
263       return OutStr;
264     }
265   };
266 }
267
268 void MachineFunction::viewCFG() const
269 {
270 #ifndef NDEBUG
271   ViewGraph(this, "mf" + getFunction()->getName());
272 #else
273   std::cerr << "SelectionDAG::viewGraph is only available in debug builds on "
274             << "systems with Graphviz or gv!\n";
275 #endif // NDEBUG
276 }
277
278 void MachineFunction::viewCFGOnly() const
279 {
280   CFGOnly = true;
281   viewCFG();
282   CFGOnly = false;
283 }
284
285 // The next two methods are used to construct and to retrieve
286 // the MachineCodeForFunction object for the given function.
287 // construct() -- Allocates and initializes for a given function and target
288 // get()       -- Returns a handle to the object.
289 //                This should not be called before "construct()"
290 //                for a given Function.
291 //
292 MachineFunction&
293 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
294 {
295   assert(Fn->getAnnotation(MF_AID) == 0 &&
296          "Object already exists for this function!");
297   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
298   Fn->addAnnotation(mcInfo);
299   return *mcInfo;
300 }
301
302 void MachineFunction::destruct(const Function *Fn) {
303   bool Deleted = Fn->deleteAnnotation(MF_AID);
304   assert(Deleted && "Machine code did not exist for function!");
305 }
306
307 MachineFunction& MachineFunction::get(const Function *F)
308 {
309   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
310   assert(mc && "Call construct() method first to allocate the object");
311   return *mc;
312 }
313
314 void MachineFunction::clearSSARegMap() {
315   delete SSARegMapping;
316   SSARegMapping = 0;
317 }
318
319 //===----------------------------------------------------------------------===//
320 //  MachineFrameInfo implementation
321 //===----------------------------------------------------------------------===//
322
323 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
324   int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
325
326   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
327     const StackObject &SO = Objects[i];
328     OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
329     if (SO.Size == 0)
330       OS << "variable sized";
331     else
332       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
333     OS << " alignment is " << SO.Alignment << " byte"
334        << (SO.Alignment != 1 ? "s," : ",");
335
336     if (i < NumFixedObjects)
337       OS << " fixed";
338     if (i < NumFixedObjects || SO.SPOffset != -1) {
339       int Off = SO.SPOffset - ValOffset;
340       OS << " at location [SP";
341       if (Off > 0)
342         OS << "+" << Off;
343       else if (Off < 0)
344         OS << Off;
345       OS << "]";
346     }
347     OS << "\n";
348   }
349
350   if (HasVarSizedObjects)
351     OS << "  Stack frame contains variable sized objects\n";
352 }
353
354 void MachineFrameInfo::dump(const MachineFunction &MF) const {
355   print(MF, std::cerr);
356 }
357
358
359 //===----------------------------------------------------------------------===//
360 //  MachineJumpTableInfo implementation
361 //===----------------------------------------------------------------------===//
362
363 /// getJumpTableIndex - Create a new jump table entry in the jump table info
364 /// or return an existing one.
365 ///
366 unsigned MachineJumpTableInfo::getJumpTableIndex(
367                                      std::vector<MachineBasicBlock*> &DestBBs) {
368   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
369     if (JumpTables[i].MBBs == DestBBs)
370       return i;
371   
372   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
373   return JumpTables.size()-1;
374 }
375
376
377 void MachineJumpTableInfo::print(std::ostream &OS) const {
378   // FIXME: this is lame, maybe we could print out the MBB numbers or something
379   // like {1, 2, 4, 5, 3, 0}
380   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
381     OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size() 
382        << " entries\n";
383   }
384 }
385
386 unsigned MachineJumpTableInfo::getEntrySize() const { 
387   return TD->getPointerSize(); 
388 }
389
390 unsigned MachineJumpTableInfo::getAlignment() const { 
391   return TD->getPointerAlignment(); 
392 }
393
394 void MachineJumpTableInfo::dump() const { print(std::cerr); }
395
396
397 //===----------------------------------------------------------------------===//
398 //  MachineConstantPool implementation
399 //===----------------------------------------------------------------------===//
400
401 const Type *MachineConstantPoolEntry::getType() const {
402   if (isMachineConstantPoolEntry())
403       return Val.MachineCPVal->getType();
404   return Val.ConstVal->getType();
405 }
406
407 MachineConstantPool::~MachineConstantPool() {
408   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
409     if (Constants[i].isMachineConstantPoolEntry())
410       delete Constants[i].Val.MachineCPVal;
411 }
412
413 /// getConstantPoolIndex - Create a new entry in the constant pool or return
414 /// an existing one.  User must specify an alignment in bytes for the object.
415 ///
416 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C, 
417                                                    unsigned Alignment) {
418   assert(Alignment && "Alignment must be specified!");
419   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
420   
421   // Check to see if we already have this constant.
422   //
423   // FIXME, this could be made much more efficient for large constant pools.
424   unsigned AlignMask = (1 << Alignment)-1;
425   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
426     if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
427       return i;
428   
429   unsigned Offset = 0;
430   if (!Constants.empty()) {
431     Offset = Constants.back().getOffset();
432     Offset += TD->getTypeSize(Constants.back().getType());
433     Offset = (Offset+AlignMask)&~AlignMask;
434   }
435   
436   Constants.push_back(MachineConstantPoolEntry(C, Offset));
437   return Constants.size()-1;
438 }
439
440 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
441                                                    unsigned Alignment) {
442   assert(Alignment && "Alignment must be specified!");
443   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
444   
445   // Check to see if we already have this constant.
446   //
447   // FIXME, this could be made much more efficient for large constant pools.
448   unsigned AlignMask = (1 << Alignment)-1;
449   int Idx = V->getExistingMachineCPValue(this, Alignment);
450   if (Idx != -1)
451     return (unsigned)Idx;
452   
453   unsigned Offset = 0;
454   if (!Constants.empty()) {
455     Offset = Constants.back().getOffset();
456     Offset += TD->getTypeSize(Constants.back().getType());
457     Offset = (Offset+AlignMask)&~AlignMask;
458   }
459   
460   Constants.push_back(MachineConstantPoolEntry(V, Offset));
461   return Constants.size()-1;
462 }
463
464
465 void MachineConstantPool::print(std::ostream &OS) const {
466   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
467     OS << "  <cp #" << i << "> is";
468     if (Constants[i].isMachineConstantPoolEntry())
469       Constants[i].Val.MachineCPVal->print(OS);
470     else
471       OS << *(Value*)Constants[i].Val.ConstVal;
472     OS << " , offset=" << Constants[i].Offset;
473     OS << "\n";
474   }
475 }
476
477 void MachineConstantPool::dump() const { print(std::cerr); }