Ugly hack! Add helper functions InsertInFlightSetEntry and
[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/Visibility.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
42 namespace {
43   struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
44     std::ostream *OS;
45     const std::string Banner;
46
47     Printer (std::ostream *_OS, const std::string &_Banner) :
48       OS (_OS), Banner (_Banner) { }
49
50     const char *getPassName() const { return "MachineFunction Printer"; }
51
52     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53       AU.setPreservesAll();
54     }
55
56     bool runOnMachineFunction(MachineFunction &MF) {
57       (*OS) << Banner;
58       MF.print (*OS);
59       return false;
60     }
61   };
62 }
63
64 /// Returns a newly-created MachineFunction Printer pass. The default output
65 /// stream is std::cerr; the default banner is empty.
66 ///
67 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
68                                                      const std::string &Banner){
69   return new Printer(OS, Banner);
70 }
71
72 namespace {
73   struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
74     const char *getPassName() const { return "Machine Code Deleter"; }
75
76     bool runOnMachineFunction(MachineFunction &MF) {
77       // Delete the annotation from the function now.
78       MachineFunction::destruct(MF.getFunction());
79       return true;
80     }
81   };
82 }
83
84 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
85 /// the current function, which should happen after the function has been
86 /// emitted to a .s file or to memory.
87 FunctionPass *llvm::createMachineCodeDeleter() {
88   return new Deleter();
89 }
90
91
92
93 //===---------------------------------------------------------------------===//
94 // MachineFunction implementation
95 //===---------------------------------------------------------------------===//
96
97 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
98   MachineBasicBlock* dummy = new MachineBasicBlock();
99   LeakDetector::removeGarbageObject(dummy);
100   return dummy;
101 }
102
103 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
104   iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
105   ilist_iterator<MachineBasicBlock> first,
106   ilist_iterator<MachineBasicBlock> last) {
107   if (Parent != toList.Parent)
108     for (; first != last; ++first)
109       first->Parent = toList.Parent;
110 }
111
112 MachineFunction::MachineFunction(const Function *F,
113                                  const TargetMachine &TM)
114   : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
115   SSARegMapping = new SSARegMap();
116   MFInfo = 0;
117   FrameInfo = new MachineFrameInfo();
118   ConstantPool = new MachineConstantPool(TM.getTargetData());
119   JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
120   BasicBlocks.Parent = this;
121 }
122
123 MachineFunction::~MachineFunction() {
124   BasicBlocks.clear();
125   delete SSARegMapping;
126   delete MFInfo;
127   delete FrameInfo;
128   delete ConstantPool;
129   delete JumpTableInfo;
130   delete[] UsedPhysRegs;
131 }
132
133 void MachineFunction::dump() const { print(std::cerr); }
134
135 void MachineFunction::print(std::ostream &OS) const {
136   OS << "# Machine code for " << Fn->getName () << "():\n";
137
138   // Print Frame Information
139   getFrameInfo()->print(*this, OS);
140   
141   // Print JumpTable Information
142   getJumpTableInfo()->print(OS);
143
144   // Print Constant Pool
145   getConstantPool()->print(OS);
146   
147   const MRegisterInfo *MRI = getTarget().getRegisterInfo();
148   
149   if (livein_begin() != livein_end()) {
150     OS << "Live Ins:";
151     for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
152       if (MRI)
153         OS << " " << MRI->getName(I->first);
154       else
155         OS << " Reg #" << I->first;
156       
157       if (I->second)
158         OS << " in VR#" << I->second << " ";
159     }
160     OS << "\n";
161   }
162   if (liveout_begin() != liveout_end()) {
163     OS << "Live Outs:";
164     for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
165       if (MRI)
166         OS << " " << MRI->getName(*I);
167       else
168         OS << " Reg #" << *I;
169     OS << "\n";
170   }
171   
172   for (const_iterator BB = begin(); BB != end(); ++BB)
173     BB->print(OS);
174
175   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
176 }
177
178 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
179 /// prints out the contents of basic blocks or not.  This is acceptable because
180 /// this code is only really used for debugging purposes.
181 ///
182 static bool CFGOnly = false;
183
184 namespace llvm {
185   template<>
186   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
187     static std::string getGraphName(const MachineFunction *F) {
188       return "CFG for '" + F->getFunction()->getName() + "' function";
189     }
190
191     static std::string getNodeLabel(const MachineBasicBlock *Node,
192                                     const MachineFunction *Graph) {
193       if (CFGOnly && Node->getBasicBlock() &&
194           !Node->getBasicBlock()->getName().empty())
195         return Node->getBasicBlock()->getName() + ":";
196
197       std::ostringstream Out;
198       if (CFGOnly) {
199         Out << Node->getNumber() << ':';
200         return Out.str();
201       }
202
203       Node->print(Out);
204
205       std::string OutStr = Out.str();
206       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
207
208       // Process string output to make it nicer...
209       for (unsigned i = 0; i != OutStr.length(); ++i)
210         if (OutStr[i] == '\n') {                            // Left justify
211           OutStr[i] = '\\';
212           OutStr.insert(OutStr.begin()+i+1, 'l');
213         }
214       return OutStr;
215     }
216   };
217 }
218
219 void MachineFunction::viewCFG() const
220 {
221 #ifndef NDEBUG
222   ViewGraph(this, "mf" + getFunction()->getName());
223 #else
224   std::cerr << "SelectionDAG::viewGraph is only available in debug builds on "
225             << "systems with Graphviz or gv!\n";
226 #endif // NDEBUG
227 }
228
229 void MachineFunction::viewCFGOnly() const
230 {
231   CFGOnly = true;
232   viewCFG();
233   CFGOnly = false;
234 }
235
236 // The next two methods are used to construct and to retrieve
237 // the MachineCodeForFunction object for the given function.
238 // construct() -- Allocates and initializes for a given function and target
239 // get()       -- Returns a handle to the object.
240 //                This should not be called before "construct()"
241 //                for a given Function.
242 //
243 MachineFunction&
244 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
245 {
246   assert(Fn->getAnnotation(MF_AID) == 0 &&
247          "Object already exists for this function!");
248   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
249   Fn->addAnnotation(mcInfo);
250   return *mcInfo;
251 }
252
253 void MachineFunction::destruct(const Function *Fn) {
254   bool Deleted = Fn->deleteAnnotation(MF_AID);
255   assert(Deleted && "Machine code did not exist for function!");
256 }
257
258 MachineFunction& MachineFunction::get(const Function *F)
259 {
260   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
261   assert(mc && "Call construct() method first to allocate the object");
262   return *mc;
263 }
264
265 void MachineFunction::clearSSARegMap() {
266   delete SSARegMapping;
267   SSARegMapping = 0;
268 }
269
270 //===----------------------------------------------------------------------===//
271 //  MachineFrameInfo implementation
272 //===----------------------------------------------------------------------===//
273
274 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
275   int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
276
277   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
278     const StackObject &SO = Objects[i];
279     OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
280     if (SO.Size == 0)
281       OS << "variable sized";
282     else
283       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
284     OS << " alignment is " << SO.Alignment << " byte"
285        << (SO.Alignment != 1 ? "s," : ",");
286
287     if (i < NumFixedObjects)
288       OS << " fixed";
289     if (i < NumFixedObjects || SO.SPOffset != -1) {
290       int Off = SO.SPOffset - ValOffset;
291       OS << " at location [SP";
292       if (Off > 0)
293         OS << "+" << Off;
294       else if (Off < 0)
295         OS << Off;
296       OS << "]";
297     }
298     OS << "\n";
299   }
300
301   if (HasVarSizedObjects)
302     OS << "  Stack frame contains variable sized objects\n";
303 }
304
305 void MachineFrameInfo::dump(const MachineFunction &MF) const {
306   print(MF, std::cerr);
307 }
308
309
310 //===----------------------------------------------------------------------===//
311 //  MachineJumpTableInfo implementation
312 //===----------------------------------------------------------------------===//
313
314 /// getJumpTableIndex - Create a new jump table entry in the jump table info
315 /// or return an existing one.
316 ///
317 unsigned MachineJumpTableInfo::getJumpTableIndex(
318                                      std::vector<MachineBasicBlock*> &DestBBs) {
319   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
320     if (JumpTables[i].MBBs == DestBBs)
321       return i;
322   
323   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
324   return JumpTables.size()-1;
325 }
326
327
328 void MachineJumpTableInfo::print(std::ostream &OS) const {
329   // FIXME: this is lame, maybe we could print out the MBB numbers or something
330   // like {1, 2, 4, 5, 3, 0}
331   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
332     OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size() 
333        << " entries\n";
334   }
335 }
336
337 unsigned MachineJumpTableInfo::getEntrySize() const { 
338   return TD->getPointerSize(); 
339 }
340
341 unsigned MachineJumpTableInfo::getAlignment() const { 
342   return TD->getPointerAlignment(); 
343 }
344
345 void MachineJumpTableInfo::dump() const { print(std::cerr); }
346
347
348 //===----------------------------------------------------------------------===//
349 //  MachineConstantPool implementation
350 //===----------------------------------------------------------------------===//
351
352 /// getConstantPoolIndex - Create a new entry in the constant pool or return
353 /// an existing one.  User must specify an alignment in bytes for the object.
354 ///
355 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C, 
356                                                    unsigned Alignment) {
357   assert(Alignment && "Alignment must be specified!");
358   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
359   
360   // Check to see if we already have this constant.
361   //
362   // FIXME, this could be made much more efficient for large constant pools.
363   unsigned AlignMask = (1 << Alignment)-1;
364   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
365     if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0)
366       return i;
367   
368   unsigned Offset = 0;
369   if (!Constants.empty()) {
370     Offset = Constants.back().Offset;
371     Offset += TD->getTypeSize(Constants.back().Val->getType());
372     Offset = (Offset+AlignMask)&~AlignMask;
373   }
374   
375   Constants.push_back(MachineConstantPoolEntry(C, Offset));
376   return Constants.size()-1;
377 }
378
379
380 void MachineConstantPool::print(std::ostream &OS) const {
381   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
382     OS << "  <cp #" << i << "> is" << *(Value*)Constants[i].Val;
383     OS << " , offset=" << Constants[i].Offset;
384     OS << "\n";
385   }
386 }
387
388 void MachineConstantPool::dump() const { print(std::cerr); }