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