Add support for constant pool
[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 <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 Pass *createMachineCodeConstructionPass(TargetMachine &Target) {
84   return new ConstructMachineFunction(Target);
85 }
86
87 Pass *createMachineCodeDestructionPass() {
88   return new DestroyMachineFunction();
89 }
90
91 Pass *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(OS);
124
125   // Print Constant Pool
126   getConstantPool()->print(OS);
127   
128   for (const_iterator BB = begin(); BB != end(); ++BB) {
129     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(std::ostream &OS) const {
192   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
193     const StackObject &SO = Objects[i];
194     OS << "  <fi #" << (int)(i-NumFixedObjects) << "> is ";
195     if (SO.Size == 0)
196       OS << "variable sized";
197     else
198       OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");
199     
200     if (i < NumFixedObjects)
201       OS << " fixed";
202     if (i < NumFixedObjects || SO.SPOffset != -1) {
203       OS << " at location [SP";
204       if (SO.SPOffset > 0)
205         OS << "+" << SO.SPOffset;
206       else if (SO.SPOffset < 0)
207         OS << SO.SPOffset;
208       OS << "]";
209     }
210     OS << "\n";
211   }
212
213   if (HasVarSizedObjects)
214     OS << "  Stack frame contains variable sized objects\n";
215 }
216
217 void MachineFrameInfo::dump() const { print(std::cerr); }
218
219
220 //===----------------------------------------------------------------------===//
221 //  MachineConstantPool implementation
222 //===----------------------------------------------------------------------===//
223
224 void MachineConstantPool::print(std::ostream &OS) const {
225   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
226     OS << "  <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
227 }
228
229 void MachineConstantPool::dump() const { print(std::cerr); }
230
231 //===----------------------------------------------------------------------===//
232 //  MachineFunctionInfo implementation
233 //===----------------------------------------------------------------------===//
234
235 static unsigned
236 ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
237                            unsigned &maxOptionalNumArgs)
238 {
239   const TargetFrameInfo &frameInfo = target.getFrameInfo();
240   
241   unsigned maxSize = 0;
242   
243   for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
244     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
245       if (const CallInst *callInst = dyn_cast<CallInst>(&*I))
246         {
247           unsigned numOperands = callInst->getNumOperands() - 1;
248           int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
249           if (numExtra <= 0)
250             continue;
251           
252           unsigned sizeForThisCall;
253           if (frameInfo.argsOnStackHaveFixedSize())
254             {
255               int argSize = frameInfo.getSizeOfEachArgOnStack(); 
256               sizeForThisCall = numExtra * (unsigned) argSize;
257             }
258           else
259             {
260               assert(0 && "UNTESTED CODE: Size per stack argument is not "
261                      "fixed on this architecture: use actual arg sizes to "
262                      "compute MaxOptionalArgsSize");
263               sizeForThisCall = 0;
264               for (unsigned i = 0; i < numOperands; ++i)
265                 sizeForThisCall += target.getTargetData().getTypeSize(callInst->
266                                               getOperand(i)->getType());
267             }
268           
269           if (maxSize < sizeForThisCall)
270             maxSize = sizeForThisCall;
271           
272           if ((int)maxOptionalNumArgs < numExtra)
273             maxOptionalNumArgs = (unsigned) numExtra;
274         }
275   
276   return maxSize;
277 }
278
279 // Align data larger than one L1 cache line on L1 cache line boundaries.
280 // Align all smaller data on the next higher 2^x boundary (4, 8, ...),
281 // but not higher than the alignment of the largest type we support
282 // (currently a double word). -- see class TargetData).
283 //
284 // This function is similar to the corresponding function in EmitAssembly.cpp
285 // but they are unrelated.  This one does not align at more than a
286 // double-word boundary whereas that one might.
287 // 
288 inline unsigned
289 SizeToAlignment(unsigned size, const TargetMachine& target)
290 {
291   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
292   if (size > (unsigned) cacheLineSize / 2)
293     return cacheLineSize;
294   else
295     for (unsigned sz=1; /*no condition*/; sz *= 2)
296       if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
297         return sz;
298 }
299
300
301 void MachineFunctionInfo::CalculateArgSize() {
302   maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
303                                                    MF.getFunction(),
304                                                    maxOptionalNumArgs);
305   staticStackSize = maxOptionalArgsSize
306     + MF.getTarget().getFrameInfo().getMinStackFrameSize();
307 }
308
309 int
310 MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
311                                               unsigned &getPaddedSize,
312                                               unsigned  sizeToUse)
313 {
314   if (sizeToUse == 0)
315     sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType());
316   unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());
317
318   bool growUp;
319   int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF,
320                                                                              growUp);
321   int offset = growUp? firstOffset + getAutomaticVarsSize()
322                      : firstOffset - (getAutomaticVarsSize() + sizeToUse);
323
324   int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
325   getPaddedSize = sizeToUse + abs(aligned - offset);
326
327   return aligned;
328 }
329
330 int
331 MachineFunctionInfo::allocateLocalVar(const Value* val,
332                                       unsigned sizeToUse)
333 {
334   assert(! automaticVarsAreaFrozen &&
335          "Size of auto vars area has been used to compute an offset so "
336          "no more automatic vars should be allocated!");
337   
338   // Check if we've allocated a stack slot for this value already
339   // 
340   int offset = getOffset(val);
341   if (offset == INVALID_FRAME_OFFSET)
342     {
343       unsigned getPaddedSize;
344       offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
345       offsets[val] = offset;
346       incrementAutomaticVarsSize(getPaddedSize);
347     }
348   return offset;
349 }
350
351 int
352 MachineFunctionInfo::allocateSpilledValue(const Type* type)
353 {
354   assert(! spillsAreaFrozen &&
355          "Size of reg spills area has been used to compute an offset so "
356          "no more register spill slots should be allocated!");
357   
358   unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);
359   unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);
360   
361   bool growUp;
362   int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp);
363   
364   int offset = growUp? firstOffset + getRegSpillsSize()
365                      : firstOffset - (getRegSpillsSize() + size);
366
367   int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
368   size += abs(aligned - offset); // include alignment padding in size
369   
370   incrementRegSpillsSize(size);  // update size of reg. spills area
371
372   return aligned;
373 }
374
375 int
376 MachineFunctionInfo::pushTempValue(unsigned size)
377 {
378   unsigned align = SizeToAlignment(size, MF.getTarget());
379
380   bool growUp;
381   int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp);
382
383   int offset = growUp? firstOffset + currentTmpValuesSize
384                      : firstOffset - (currentTmpValuesSize + size);
385
386   int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp,
387                                                               align);
388   size += abs(aligned - offset); // include alignment padding in size
389
390   incrementTmpAreaSize(size);    // update "current" size of tmp area
391
392   return aligned;
393 }
394
395 void MachineFunctionInfo::popAllTempValues() {
396   resetTmpAreaSize();            // clear tmp area to reuse
397 }
398
399 int
400 MachineFunctionInfo::getOffset(const Value* val) const
401 {
402   hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
403   return (pair == offsets.end()) ? INVALID_FRAME_OFFSET : pair->second;
404 }