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