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