Refactor MachineFunction::print() into MachineBasicBlock::print().
[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/MachineCodeForInstruction.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/CodeGen/MachineFunctionInfo.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Target/TargetCacheInfo.h"
27 #include "llvm/Function.h"
28 #include "llvm/iOther.h"
29 using namespace llvm;
30
31 static AnnotationID MF_AID(
32                  AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
33
34
35 namespace {
36   struct Printer : public MachineFunctionPass {
37     std::ostream *OS;
38     const std::string Banner;
39
40     Printer (std::ostream *_OS, const std::string &_Banner) :
41       OS (_OS), Banner (_Banner) { }
42
43     const char *getPassName() const { return "MachineFunction Printer"; }
44
45     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46       AU.setPreservesAll();
47     }
48
49     bool runOnMachineFunction(MachineFunction &MF) {
50       (*OS) << Banner;
51       MF.print (*OS);
52       return false;
53     }
54   };
55 }
56
57 /// Returns a newly-created MachineFunction Printer pass. The default output
58 /// stream is std::cerr; the default banner is empty.
59 ///
60 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
61                                                      const std::string &Banner) {
62   return new Printer(OS, Banner);
63 }
64
65 //===---------------------------------------------------------------------===//
66 // MachineFunction implementation
67 //===---------------------------------------------------------------------===//
68
69 MachineFunction::MachineFunction(const Function *F,
70                                  const TargetMachine &TM)
71   : Annotation(MF_AID), Fn(F), Target(TM) {
72   SSARegMapping = new SSARegMap();
73   MFInfo = new MachineFunctionInfo(*this);
74   FrameInfo = new MachineFrameInfo();
75   ConstantPool = new MachineConstantPool();
76 }
77
78 MachineFunction::~MachineFunction() { 
79   delete SSARegMapping;
80   delete MFInfo;
81   delete FrameInfo;
82   delete ConstantPool;
83 }
84
85 void MachineFunction::dump() const { print(std::cerr); }
86
87 void MachineFunction::print(std::ostream &OS) const {
88   OS << "\n" << *(Value*)Fn->getFunctionType() << " \"" << Fn->getName()
89      << "\"\n";
90
91   // Print Frame Information
92   getFrameInfo()->print(*this, OS);
93
94   // Print Constant Pool
95   getConstantPool()->print(OS);
96   
97   for (const_iterator BB = begin(); BB != end(); ++BB)
98     BB->print(OS);
99   OS << "\nEnd function \"" << Fn->getName() << "\"\n\n";
100 }
101
102 void MachineBasicBlock::dump() const { print(std::cerr); }
103
104 void MachineBasicBlock::print(std::ostream &OS) const {
105   const BasicBlock *LBB = getBasicBlock();
106   OS << "\n" << LBB->getName() << " (" << (const void*)LBB << "):\n";
107   for (const_iterator I = begin(); I != end(); ++I) {
108     OS << "\t";
109     I->print(OS, MachineFunction::get(LBB->getParent()).getTarget());
110   }
111 }
112
113 // The next two methods are used to construct and to retrieve
114 // the MachineCodeForFunction object for the given function.
115 // construct() -- Allocates and initializes for a given function and target
116 // get()       -- Returns a handle to the object.
117 //                This should not be called before "construct()"
118 //                for a given Function.
119 // 
120 MachineFunction&
121 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
122 {
123   assert(Fn->getAnnotation(MF_AID) == 0 &&
124          "Object already exists for this function!");
125   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
126   Fn->addAnnotation(mcInfo);
127   return *mcInfo;
128 }
129
130 void MachineFunction::destruct(const Function *Fn) {
131   bool Deleted = Fn->deleteAnnotation(MF_AID);
132   assert(Deleted && "Machine code did not exist for function!");
133 }
134
135 MachineFunction& MachineFunction::get(const Function *F)
136 {
137   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
138   assert(mc && "Call construct() method first to allocate the object");
139   return *mc;
140 }
141
142 void MachineFunction::clearSSARegMap() {
143   delete SSARegMapping;
144   SSARegMapping = 0;
145 }
146
147 //===----------------------------------------------------------------------===//
148 //  MachineFrameInfo implementation
149 //===----------------------------------------------------------------------===//
150
151 /// CreateStackObject - Create a stack object for a value of the specified type.
152 ///
153 int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
154   return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));
155 }
156
157 int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {
158   return CreateStackObject(RC->getSize(), RC->getAlignment());
159 }
160
161
162 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
163   int ValOffset = MF.getTarget().getFrameInfo().getOffsetOfLocalArea();
164
165   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
166     const StackObject &SO = Objects[i];
167     OS << "  <fi #" << (int)(i-NumFixedObjects) << "> is ";
168     if (SO.Size == 0)
169       OS << "variable sized";
170     else
171       OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");
172     
173     if (i < NumFixedObjects)
174       OS << " fixed";
175     if (i < NumFixedObjects || SO.SPOffset != -1) {
176       int Off = SO.SPOffset + ValOffset;
177       OS << " at location [SP";
178       if (Off > 0)
179         OS << "+" << Off;
180       else if (Off < 0)
181         OS << Off;
182       OS << "]";
183     }
184     OS << "\n";
185   }
186
187   if (HasVarSizedObjects)
188     OS << "  Stack frame contains variable sized objects\n";
189 }
190
191 void MachineFrameInfo::dump(const MachineFunction &MF) const {
192   print(MF, std::cerr);
193 }
194
195
196 //===----------------------------------------------------------------------===//
197 //  MachineConstantPool implementation
198 //===----------------------------------------------------------------------===//
199
200 void MachineConstantPool::print(std::ostream &OS) const {
201   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
202     OS << "  <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
203 }
204
205 void MachineConstantPool::dump() const { print(std::cerr); }
206
207 //===----------------------------------------------------------------------===//
208 //  MachineFunctionInfo implementation
209 //===----------------------------------------------------------------------===//
210
211 static unsigned
212 ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
213                            unsigned &maxOptionalNumArgs)
214 {
215   const TargetFrameInfo &frameInfo = target.getFrameInfo();
216   
217   unsigned maxSize = 0;
218   
219   for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
220     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
221       if (const CallInst *callInst = dyn_cast<CallInst>(I))
222         {
223           unsigned numOperands = callInst->getNumOperands() - 1;
224           int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
225           if (numExtra <= 0)
226             continue;
227           
228           unsigned sizeForThisCall;
229           if (frameInfo.argsOnStackHaveFixedSize())
230             {
231               int argSize = frameInfo.getSizeOfEachArgOnStack(); 
232               sizeForThisCall = numExtra * (unsigned) argSize;
233             }
234           else
235             {
236               assert(0 && "UNTESTED CODE: Size per stack argument is not "
237                      "fixed on this architecture: use actual arg sizes to "
238                      "compute MaxOptionalArgsSize");
239               sizeForThisCall = 0;
240               for (unsigned i = 0; i < numOperands; ++i)
241                 sizeForThisCall += target.getTargetData().getTypeSize(callInst->
242                                               getOperand(i)->getType());
243             }
244           
245           if (maxSize < sizeForThisCall)
246             maxSize = sizeForThisCall;
247           
248           if ((int)maxOptionalNumArgs < numExtra)
249             maxOptionalNumArgs = (unsigned) numExtra;
250         }
251   
252   return maxSize;
253 }
254
255 // Align data larger than one L1 cache line on L1 cache line boundaries.
256 // Align all smaller data on the next higher 2^x boundary (4, 8, ...),
257 // but not higher than the alignment of the largest type we support
258 // (currently a double word). -- see class TargetData).
259 //
260 // This function is similar to the corresponding function in EmitAssembly.cpp
261 // but they are unrelated.  This one does not align at more than a
262 // double-word boundary whereas that one might.
263 // 
264 inline unsigned
265 SizeToAlignment(unsigned size, const TargetMachine& target)
266 {
267   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
268   if (size > (unsigned) cacheLineSize / 2)
269     return cacheLineSize;
270   else
271     for (unsigned sz=1; /*no condition*/; sz *= 2)
272       if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
273         return sz;
274 }
275
276
277 void MachineFunctionInfo::CalculateArgSize() {
278   maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
279                                                    MF.getFunction(),
280                                                    maxOptionalNumArgs);
281   staticStackSize = maxOptionalArgsSize
282     + MF.getTarget().getFrameInfo().getMinStackFrameSize();
283 }
284
285 int
286 MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
287                                               unsigned &getPaddedSize,
288                                               unsigned  sizeToUse)
289 {
290   if (sizeToUse == 0)
291     sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType());
292   unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());
293
294   bool growUp;
295   int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF,
296                                                                              growUp);
297   int offset = growUp? firstOffset + getAutomaticVarsSize()
298                      : firstOffset - (getAutomaticVarsSize() + sizeToUse);
299
300   int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
301   getPaddedSize = sizeToUse + abs(aligned - offset);
302
303   return aligned;
304 }
305
306
307 int MachineFunctionInfo::allocateLocalVar(const Value* val,
308                                           unsigned sizeToUse) {
309   assert(! automaticVarsAreaFrozen &&
310          "Size of auto vars area has been used to compute an offset so "
311          "no more automatic vars should be allocated!");
312   
313   // Check if we've allocated a stack slot for this value already
314   // 
315   hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
316   if (pair != offsets.end())
317     return pair->second;
318
319   unsigned getPaddedSize;
320   unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
321   offsets[val] = offset;
322   incrementAutomaticVarsSize(getPaddedSize);
323   return offset;
324 }
325
326 int
327 MachineFunctionInfo::allocateSpilledValue(const Type* type)
328 {
329   assert(! spillsAreaFrozen &&
330          "Size of reg spills area has been used to compute an offset so "
331          "no more register spill slots should be allocated!");
332   
333   unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);
334   unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);
335   
336   bool growUp;
337   int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp);
338   
339   int offset = growUp? firstOffset + getRegSpillsSize()
340                      : firstOffset - (getRegSpillsSize() + size);
341
342   int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
343   size += abs(aligned - offset); // include alignment padding in size
344   
345   incrementRegSpillsSize(size);  // update size of reg. spills area
346
347   return aligned;
348 }
349
350 int
351 MachineFunctionInfo::pushTempValue(unsigned size)
352 {
353   unsigned align = SizeToAlignment(size, MF.getTarget());
354
355   bool growUp;
356   int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp);
357
358   int offset = growUp? firstOffset + currentTmpValuesSize
359                      : firstOffset - (currentTmpValuesSize + size);
360
361   int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp,
362                                                               align);
363   size += abs(aligned - offset); // include alignment padding in size
364
365   incrementTmpAreaSize(size);    // update "current" size of tmp area
366
367   return aligned;
368 }
369
370 void MachineFunctionInfo::popAllTempValues() {
371   resetTmpAreaSize();            // clear tmp area to reuse
372 }
373