Debug dump error.
[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/TargetLowering.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetFrameInfo.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/GraphWriter.h"
31 #include "llvm/Support/LeakDetector.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/Config/config.h"
34 #include <fstream>
35 #include <sstream>
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   
122   // Set up jump table.
123   const TargetData &TD = *TM.getTargetData();
124   bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
125   unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
126   unsigned Alignment = IsPic ? TD.getIntAlignment() : TD.getPointerAlignment();
127   JumpTableInfo = new MachineJumpTableInfo(EntrySize, Alignment);
128   
129   BasicBlocks.Parent = this;
130 }
131
132 MachineFunction::~MachineFunction() {
133   BasicBlocks.clear();
134   delete SSARegMapping;
135   delete MFInfo;
136   delete FrameInfo;
137   delete ConstantPool;
138   delete JumpTableInfo;
139   delete[] UsedPhysRegs;
140 }
141
142
143 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
144 /// recomputes them.  This guarantees that the MBB numbers are sequential,
145 /// dense, and match the ordering of the blocks within the function.  If a
146 /// specific MachineBasicBlock is specified, only that block and those after
147 /// it are renumbered.
148 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
149   if (empty()) { MBBNumbering.clear(); return; }
150   MachineFunction::iterator MBBI, E = end();
151   if (MBB == 0)
152     MBBI = begin();
153   else
154     MBBI = MBB;
155   
156   // Figure out the block number this should have.
157   unsigned BlockNo = 0;
158   if (MBBI != begin())
159     BlockNo = prior(MBBI)->getNumber()+1;
160   
161   for (; MBBI != E; ++MBBI, ++BlockNo) {
162     if (MBBI->getNumber() != (int)BlockNo) {
163       // Remove use of the old number.
164       if (MBBI->getNumber() != -1) {
165         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
166                "MBB number mismatch!");
167         MBBNumbering[MBBI->getNumber()] = 0;
168       }
169       
170       // If BlockNo is already taken, set that block's number to -1.
171       if (MBBNumbering[BlockNo])
172         MBBNumbering[BlockNo]->setNumber(-1);
173
174       MBBNumbering[BlockNo] = MBBI;
175       MBBI->setNumber(BlockNo);
176     }
177   }    
178
179   // Okay, all the blocks are renumbered.  If we have compactified the block
180   // numbering, shrink MBBNumbering now.
181   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
182   MBBNumbering.resize(BlockNo);
183 }
184
185
186 void MachineFunction::dump() const { print(*cerr.stream()); }
187
188 void MachineFunction::print(std::ostream &OS) const {
189   OS << "# Machine code for " << Fn->getName () << "():\n";
190
191   // Print Frame Information
192   getFrameInfo()->print(*this, OS);
193   
194   // Print JumpTable Information
195   getJumpTableInfo()->print(OS);
196
197   // Print Constant Pool
198   getConstantPool()->print(OS);
199   
200   const MRegisterInfo *MRI = getTarget().getRegisterInfo();
201   
202   if (livein_begin() != livein_end()) {
203     OS << "Live Ins:";
204     for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
205       if (MRI)
206         OS << " " << MRI->getName(I->first);
207       else
208         OS << " Reg #" << I->first;
209       
210       if (I->second)
211         OS << " in VR#" << I->second << " ";
212     }
213     OS << "\n";
214   }
215   if (liveout_begin() != liveout_end()) {
216     OS << "Live Outs:";
217     for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
218       if (MRI)
219         OS << " " << MRI->getName(*I);
220       else
221         OS << " Reg #" << *I;
222     OS << "\n";
223   }
224   
225   for (const_iterator BB = begin(); BB != end(); ++BB)
226     BB->print(OS);
227
228   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
229 }
230
231 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
232 /// prints out the contents of basic blocks or not.  This is acceptable because
233 /// this code is only really used for debugging purposes.
234 ///
235 static bool CFGOnly = false;
236
237 namespace llvm {
238   template<>
239   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
240     static std::string getGraphName(const MachineFunction *F) {
241       return "CFG for '" + F->getFunction()->getName() + "' function";
242     }
243
244     static std::string getNodeLabel(const MachineBasicBlock *Node,
245                                     const MachineFunction *Graph) {
246       if (CFGOnly && Node->getBasicBlock() &&
247           !Node->getBasicBlock()->getName().empty())
248         return Node->getBasicBlock()->getName() + ":";
249
250       std::ostringstream Out;
251       if (CFGOnly) {
252         Out << Node->getNumber() << ':';
253         return Out.str();
254       }
255
256       Node->print(Out);
257
258       std::string OutStr = Out.str();
259       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
260
261       // Process string output to make it nicer...
262       for (unsigned i = 0; i != OutStr.length(); ++i)
263         if (OutStr[i] == '\n') {                            // Left justify
264           OutStr[i] = '\\';
265           OutStr.insert(OutStr.begin()+i+1, 'l');
266         }
267       return OutStr;
268     }
269   };
270 }
271
272 void MachineFunction::viewCFG() const
273 {
274 #ifndef NDEBUG
275   ViewGraph(this, "mf" + getFunction()->getName());
276 #else
277   cerr << "SelectionDAG::viewGraph is only available in debug builds on "
278        << "systems with Graphviz or gv!\n";
279 #endif // NDEBUG
280 }
281
282 void MachineFunction::viewCFGOnly() const
283 {
284   CFGOnly = true;
285   viewCFG();
286   CFGOnly = false;
287 }
288
289 // The next two methods are used to construct and to retrieve
290 // the MachineCodeForFunction object for the given function.
291 // construct() -- Allocates and initializes for a given function and target
292 // get()       -- Returns a handle to the object.
293 //                This should not be called before "construct()"
294 //                for a given Function.
295 //
296 MachineFunction&
297 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
298 {
299   assert(Fn->getAnnotation(MF_AID) == 0 &&
300          "Object already exists for this function!");
301   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
302   Fn->addAnnotation(mcInfo);
303   return *mcInfo;
304 }
305
306 void MachineFunction::destruct(const Function *Fn) {
307   bool Deleted = Fn->deleteAnnotation(MF_AID);
308   assert(Deleted && "Machine code did not exist for function!");
309 }
310
311 MachineFunction& MachineFunction::get(const Function *F)
312 {
313   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
314   assert(mc && "Call construct() method first to allocate the object");
315   return *mc;
316 }
317
318 void MachineFunction::clearSSARegMap() {
319   delete SSARegMapping;
320   SSARegMapping = 0;
321 }
322
323 //===----------------------------------------------------------------------===//
324 //  MachineFrameInfo implementation
325 //===----------------------------------------------------------------------===//
326
327 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
328   int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
329
330   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
331     const StackObject &SO = Objects[i];
332     OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
333     if (SO.Size == 0)
334       OS << "variable sized";
335     else
336       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
337     OS << " alignment is " << SO.Alignment << " byte"
338        << (SO.Alignment != 1 ? "s," : ",");
339
340     if (i < NumFixedObjects)
341       OS << " fixed";
342     if (i < NumFixedObjects || SO.SPOffset != -1) {
343       int Off = SO.SPOffset - ValOffset;
344       OS << " at location [SP";
345       if (Off > 0)
346         OS << "+" << Off;
347       else if (Off < 0)
348         OS << Off;
349       OS << "]";
350     }
351     OS << "\n";
352   }
353
354   if (HasVarSizedObjects)
355     OS << "  Stack frame contains variable sized objects\n";
356 }
357
358 void MachineFrameInfo::dump(const MachineFunction &MF) const {
359   print(MF, *cerr.stream());
360 }
361
362
363 //===----------------------------------------------------------------------===//
364 //  MachineJumpTableInfo implementation
365 //===----------------------------------------------------------------------===//
366
367 /// getJumpTableIndex - Create a new jump table entry in the jump table info
368 /// or return an existing one.
369 ///
370 unsigned MachineJumpTableInfo::getJumpTableIndex(
371                                const std::vector<MachineBasicBlock*> &DestBBs) {
372   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
373   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
374     if (JumpTables[i].MBBs == DestBBs)
375       return i;
376   
377   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
378   return JumpTables.size()-1;
379 }
380
381
382 void MachineJumpTableInfo::print(std::ostream &OS) const {
383   // FIXME: this is lame, maybe we could print out the MBB numbers or something
384   // like {1, 2, 4, 5, 3, 0}
385   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
386     OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size() 
387        << " entries\n";
388   }
389 }
390
391 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
392
393
394 //===----------------------------------------------------------------------===//
395 //  MachineConstantPool implementation
396 //===----------------------------------------------------------------------===//
397
398 const Type *MachineConstantPoolEntry::getType() const {
399   if (isMachineConstantPoolEntry())
400       return Val.MachineCPVal->getType();
401   return Val.ConstVal->getType();
402 }
403
404 MachineConstantPool::~MachineConstantPool() {
405   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
406     if (Constants[i].isMachineConstantPoolEntry())
407       delete Constants[i].Val.MachineCPVal;
408 }
409
410 /// getConstantPoolIndex - Create a new entry in the constant pool or return
411 /// an existing one.  User must specify an alignment in bytes for the object.
412 ///
413 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C, 
414                                                    unsigned Alignment) {
415   assert(Alignment && "Alignment must be specified!");
416   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
417   
418   // Check to see if we already have this constant.
419   //
420   // FIXME, this could be made much more efficient for large constant pools.
421   unsigned AlignMask = (1 << Alignment)-1;
422   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
423     if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
424       return i;
425   
426   unsigned Offset = 0;
427   if (!Constants.empty()) {
428     Offset = Constants.back().getOffset();
429     Offset += TD->getTypeSize(Constants.back().getType());
430     Offset = (Offset+AlignMask)&~AlignMask;
431   }
432   
433   Constants.push_back(MachineConstantPoolEntry(C, Offset));
434   return Constants.size()-1;
435 }
436
437 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
438                                                    unsigned Alignment) {
439   assert(Alignment && "Alignment must be specified!");
440   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
441   
442   // Check to see if we already have this constant.
443   //
444   // FIXME, this could be made much more efficient for large constant pools.
445   unsigned AlignMask = (1 << Alignment)-1;
446   int Idx = V->getExistingMachineCPValue(this, Alignment);
447   if (Idx != -1)
448     return (unsigned)Idx;
449   
450   unsigned Offset = 0;
451   if (!Constants.empty()) {
452     Offset = Constants.back().getOffset();
453     Offset += TD->getTypeSize(Constants.back().getType());
454     Offset = (Offset+AlignMask)&~AlignMask;
455   }
456   
457   Constants.push_back(MachineConstantPoolEntry(V, Offset));
458   return Constants.size()-1;
459 }
460
461
462 void MachineConstantPool::print(std::ostream &OS) const {
463   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
464     OS << "  <cp #" << i << "> is";
465     if (Constants[i].isMachineConstantPoolEntry())
466       Constants[i].Val.MachineCPVal->print(OS);
467     else
468       OS << *(Value*)Constants[i].Val.ConstVal;
469     OS << " , offset=" << Constants[i].getOffset();
470     OS << "\n";
471   }
472 }
473
474 void MachineConstantPool::dump() const { print(*cerr.stream()); }