1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
14 //===----------------------------------------------------------------------===//
16 #include "llvm/CodeGen/MachineFunction.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/Target/TargetMachine.h"
24 #include "llvm/Target/TargetFrameInfo.h"
25 #include "llvm/Target/TargetCacheInfo.h"
26 #include "llvm/Function.h"
27 #include "llvm/iOther.h"
28 #include "llvm/Pass.h"
29 #include "Config/limits.h"
31 const int INVALID_FRAME_OFFSET = INT_MAX; // std::numeric_limits<int>::max();
33 static AnnotationID MF_AID(
34 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
37 //===---------------------------------------------------------------------===//
38 // Code generation/destruction passes
39 //===---------------------------------------------------------------------===//
42 class ConstructMachineFunction : public FunctionPass {
43 TargetMachine &Target;
45 ConstructMachineFunction(TargetMachine &T) : Target(T) {}
47 const char *getPassName() const {
48 return "ConstructMachineFunction";
51 bool runOnFunction(Function &F) {
52 MachineFunction::construct(&F, Target).getInfo()->CalculateArgSize();
57 struct DestroyMachineFunction : public FunctionPass {
58 const char *getPassName() const { return "FreeMachineFunction"; }
60 static void freeMachineCode(Instruction &I) {
61 MachineCodeForInstruction::destroy(&I);
64 bool runOnFunction(Function &F) {
65 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
66 for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
67 MachineCodeForInstruction::get(I).dropAllReferences();
69 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
70 for_each(FI->begin(), FI->end(), freeMachineCode);
76 struct Printer : public FunctionPass {
77 const char *getPassName() const { return "MachineFunction Printer"; }
79 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 bool runOnFunction(Function &F) {
84 MachineFunction::get(&F).dump();
90 FunctionPass *createMachineCodeConstructionPass(TargetMachine &Target) {
91 return new ConstructMachineFunction(Target);
94 FunctionPass *createMachineCodeDestructionPass() {
95 return new DestroyMachineFunction();
98 FunctionPass *createMachineFunctionPrinterPass() {
103 //===---------------------------------------------------------------------===//
104 // MachineFunction implementation
105 //===---------------------------------------------------------------------===//
107 MachineFunction::MachineFunction(const Function *F,
108 const TargetMachine &TM)
109 : Annotation(MF_AID), Fn(F), Target(TM) {
110 SSARegMapping = new SSARegMap();
111 MFInfo = new MachineFunctionInfo(*this);
112 FrameInfo = new MachineFrameInfo();
113 ConstantPool = new MachineConstantPool();
116 MachineFunction::~MachineFunction() {
117 delete SSARegMapping;
123 void MachineFunction::dump() const { print(std::cerr); }
125 void MachineFunction::print(std::ostream &OS) const {
126 OS << "\n" << *(Value*)Fn->getFunctionType() << " \"" << Fn->getName()
129 // Print Frame Information
130 getFrameInfo()->print(*this, OS);
132 // Print Constant Pool
133 getConstantPool()->print(OS);
135 for (const_iterator BB = begin(); BB != end(); ++BB) {
136 const BasicBlock *LBB = BB->getBasicBlock();
137 OS << "\n" << LBB->getName() << " (" << (const void*)LBB << "):\n";
138 for (MachineBasicBlock::const_iterator I = BB->begin(); I != BB->end();++I){
140 (*I)->print(OS, Target);
143 OS << "\nEnd function \"" << Fn->getName() << "\"\n\n";
147 // The next two methods are used to construct and to retrieve
148 // the MachineCodeForFunction object for the given function.
149 // construct() -- Allocates and initializes for a given function and target
150 // get() -- Returns a handle to the object.
151 // This should not be called before "construct()"
152 // for a given Function.
155 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
157 assert(Fn->getAnnotation(MF_AID) == 0 &&
158 "Object already exists for this function!");
159 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
160 Fn->addAnnotation(mcInfo);
165 MachineFunction::destruct(const Function *Fn)
167 bool Deleted = Fn->deleteAnnotation(MF_AID);
168 assert(Deleted && "Machine code did not exist for function!");
171 MachineFunction& MachineFunction::get(const Function *F)
173 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
174 assert(mc && "Call construct() method first to allocate the object");
178 void MachineFunction::clearSSARegMap() {
179 delete SSARegMapping;
183 //===----------------------------------------------------------------------===//
184 // MachineFrameInfo implementation
185 //===----------------------------------------------------------------------===//
187 /// CreateStackObject - Create a stack object for a value of the specified type.
189 int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
190 return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));
193 int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {
194 return CreateStackObject(RC->getSize(), RC->getAlignment());
198 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
199 int ValOffset = MF.getTarget().getFrameInfo().getOffsetOfLocalArea();
201 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
202 const StackObject &SO = Objects[i];
203 OS << " <fi #" << (int)(i-NumFixedObjects) << "> is ";
205 OS << "variable sized";
207 OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");
209 if (i < NumFixedObjects)
211 if (i < NumFixedObjects || SO.SPOffset != -1) {
212 int Off = SO.SPOffset + ValOffset;
213 OS << " at location [SP";
223 if (HasVarSizedObjects)
224 OS << " Stack frame contains variable sized objects\n";
227 void MachineFrameInfo::dump(const MachineFunction &MF) const {
228 print(MF, std::cerr);
232 //===----------------------------------------------------------------------===//
233 // MachineConstantPool implementation
234 //===----------------------------------------------------------------------===//
236 void MachineConstantPool::print(std::ostream &OS) const {
237 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
238 OS << " <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
241 void MachineConstantPool::dump() const { print(std::cerr); }
243 //===----------------------------------------------------------------------===//
244 // MachineFunctionInfo implementation
245 //===----------------------------------------------------------------------===//
248 ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
249 unsigned &maxOptionalNumArgs)
251 const TargetFrameInfo &frameInfo = target.getFrameInfo();
253 unsigned maxSize = 0;
255 for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
256 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
257 if (const CallInst *callInst = dyn_cast<CallInst>(I))
259 unsigned numOperands = callInst->getNumOperands() - 1;
260 int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
264 unsigned sizeForThisCall;
265 if (frameInfo.argsOnStackHaveFixedSize())
267 int argSize = frameInfo.getSizeOfEachArgOnStack();
268 sizeForThisCall = numExtra * (unsigned) argSize;
272 assert(0 && "UNTESTED CODE: Size per stack argument is not "
273 "fixed on this architecture: use actual arg sizes to "
274 "compute MaxOptionalArgsSize");
276 for (unsigned i = 0; i < numOperands; ++i)
277 sizeForThisCall += target.getTargetData().getTypeSize(callInst->
278 getOperand(i)->getType());
281 if (maxSize < sizeForThisCall)
282 maxSize = sizeForThisCall;
284 if ((int)maxOptionalNumArgs < numExtra)
285 maxOptionalNumArgs = (unsigned) numExtra;
291 // Align data larger than one L1 cache line on L1 cache line boundaries.
292 // Align all smaller data on the next higher 2^x boundary (4, 8, ...),
293 // but not higher than the alignment of the largest type we support
294 // (currently a double word). -- see class TargetData).
296 // This function is similar to the corresponding function in EmitAssembly.cpp
297 // but they are unrelated. This one does not align at more than a
298 // double-word boundary whereas that one might.
301 SizeToAlignment(unsigned size, const TargetMachine& target)
303 unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
304 if (size > (unsigned) cacheLineSize / 2)
305 return cacheLineSize;
307 for (unsigned sz=1; /*no condition*/; sz *= 2)
308 if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
313 void MachineFunctionInfo::CalculateArgSize() {
314 maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
317 staticStackSize = maxOptionalArgsSize
318 + MF.getTarget().getFrameInfo().getMinStackFrameSize();
322 MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
323 unsigned &getPaddedSize,
327 sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType());
328 unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());
331 int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF,
333 int offset = growUp? firstOffset + getAutomaticVarsSize()
334 : firstOffset - (getAutomaticVarsSize() + sizeToUse);
336 int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
337 getPaddedSize = sizeToUse + abs(aligned - offset);
343 MachineFunctionInfo::allocateLocalVar(const Value* val,
346 assert(! automaticVarsAreaFrozen &&
347 "Size of auto vars area has been used to compute an offset so "
348 "no more automatic vars should be allocated!");
350 // Check if we've allocated a stack slot for this value already
352 int offset = getOffset(val);
353 if (offset == INVALID_FRAME_OFFSET)
355 unsigned getPaddedSize;
356 offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
357 offsets[val] = offset;
358 incrementAutomaticVarsSize(getPaddedSize);
364 MachineFunctionInfo::allocateSpilledValue(const Type* type)
366 assert(! spillsAreaFrozen &&
367 "Size of reg spills area has been used to compute an offset so "
368 "no more register spill slots should be allocated!");
370 unsigned size = MF.getTarget().getTargetData().getTypeSize(type);
371 unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);
374 int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp);
376 int offset = growUp? firstOffset + getRegSpillsSize()
377 : firstOffset - (getRegSpillsSize() + size);
379 int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
380 size += abs(aligned - offset); // include alignment padding in size
382 incrementRegSpillsSize(size); // update size of reg. spills area
388 MachineFunctionInfo::pushTempValue(unsigned size)
390 unsigned align = SizeToAlignment(size, MF.getTarget());
393 int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp);
395 int offset = growUp? firstOffset + currentTmpValuesSize
396 : firstOffset - (currentTmpValuesSize + size);
398 int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp,
400 size += abs(aligned - offset); // include alignment padding in size
402 incrementTmpAreaSize(size); // update "current" size of tmp area
407 void MachineFunctionInfo::popAllTempValues() {
408 resetTmpAreaSize(); // clear tmp area to reuse
412 MachineFunctionInfo::getOffset(const Value* val) const
414 hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
415 return (pair == offsets.end()) ? INVALID_FRAME_OFFSET : pair->second;