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