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