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/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineInstr.h"
18 #include "llvm/CodeGen/SSARegMap.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineJumpTableInfo.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetFrameInfo.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Support/Compiler.h"
29 #include "llvm/Support/GraphWriter.h"
30 #include "llvm/Support/LeakDetector.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/Config/config.h"
37 static AnnotationID MF_AID(
38 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
40 // Out of line virtual function to home classes.
41 void MachineFunctionPass::virtfn() {}
44 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
46 const std::string Banner;
48 Printer (std::ostream *_OS, const std::string &_Banner) :
49 OS (_OS), Banner (_Banner) { }
51 const char *getPassName() const { return "MachineFunction Printer"; }
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 bool runOnMachineFunction(MachineFunction &MF) {
65 /// Returns a newly-created MachineFunction Printer pass. The default output
66 /// stream is std::cerr; the default banner is empty.
68 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
69 const std::string &Banner){
70 return new Printer(OS, Banner);
74 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
75 const char *getPassName() const { return "Machine Code Deleter"; }
77 bool runOnMachineFunction(MachineFunction &MF) {
78 // Delete the annotation from the function now.
79 MachineFunction::destruct(MF.getFunction());
85 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
86 /// the current function, which should happen after the function has been
87 /// emitted to a .s file or to memory.
88 FunctionPass *llvm::createMachineCodeDeleter() {
94 //===---------------------------------------------------------------------===//
95 // MachineFunction implementation
96 //===---------------------------------------------------------------------===//
98 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
99 MachineBasicBlock* dummy = new MachineBasicBlock();
100 LeakDetector::removeGarbageObject(dummy);
104 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
105 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
106 ilist_iterator<MachineBasicBlock> first,
107 ilist_iterator<MachineBasicBlock> last) {
108 if (Parent != toList.Parent)
109 for (; first != last; ++first)
110 first->Parent = toList.Parent;
113 MachineFunction::MachineFunction(const Function *F,
114 const TargetMachine &TM)
115 : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
116 SSARegMapping = new SSARegMap();
118 FrameInfo = new MachineFrameInfo();
119 ConstantPool = new MachineConstantPool(TM.getTargetData());
120 JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
121 BasicBlocks.Parent = this;
124 MachineFunction::~MachineFunction() {
126 delete SSARegMapping;
130 delete JumpTableInfo;
131 delete[] UsedPhysRegs;
135 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
136 /// recomputes them. This guarantees that the MBB numbers are sequential,
137 /// dense, and match the ordering of the blocks within the function. If a
138 /// specific MachineBasicBlock is specified, only that block and those after
139 /// it are renumbered.
140 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
141 if (empty()) { MBBNumbering.clear(); return; }
142 MachineFunction::iterator MBBI, E = end();
148 // Figure out the block number this should have.
149 unsigned BlockNo = 0;
151 BlockNo = prior(MBBI)->getNumber()+1;
153 for (; MBBI != E; ++MBBI, ++BlockNo) {
154 if (MBBI->getNumber() != (int)BlockNo) {
155 // Remove use of the old number.
156 if (MBBI->getNumber() != -1) {
157 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
158 "MBB number mismatch!");
159 MBBNumbering[MBBI->getNumber()] = 0;
162 // If BlockNo is already taken, set that block's number to -1.
163 if (MBBNumbering[BlockNo])
164 MBBNumbering[BlockNo]->setNumber(-1);
166 MBBNumbering[BlockNo] = MBBI;
167 MBBI->setNumber(BlockNo);
171 // Okay, all the blocks are renumbered. If we have compactified the block
172 // numbering, shrink MBBNumbering now.
173 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
174 MBBNumbering.resize(BlockNo);
178 void MachineFunction::dump() const { print(*cerr.stream()); }
180 void MachineFunction::print(std::ostream &OS) const {
181 OS << "# Machine code for " << Fn->getName () << "():\n";
183 // Print Frame Information
184 getFrameInfo()->print(*this, OS);
186 // Print JumpTable Information
187 getJumpTableInfo()->print(OS);
189 // Print Constant Pool
190 getConstantPool()->print(OS);
192 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
194 if (livein_begin() != livein_end()) {
196 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
198 OS << " " << MRI->getName(I->first);
200 OS << " Reg #" << I->first;
203 OS << " in VR#" << I->second << " ";
207 if (liveout_begin() != liveout_end()) {
209 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
211 OS << " " << MRI->getName(*I);
213 OS << " Reg #" << *I;
217 for (const_iterator BB = begin(); BB != end(); ++BB)
220 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
223 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
224 /// prints out the contents of basic blocks or not. This is acceptable because
225 /// this code is only really used for debugging purposes.
227 static bool CFGOnly = false;
231 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
232 static std::string getGraphName(const MachineFunction *F) {
233 return "CFG for '" + F->getFunction()->getName() + "' function";
236 static std::string getNodeLabel(const MachineBasicBlock *Node,
237 const MachineFunction *Graph) {
238 if (CFGOnly && Node->getBasicBlock() &&
239 !Node->getBasicBlock()->getName().empty())
240 return Node->getBasicBlock()->getName() + ":";
242 std::ostringstream Out;
244 Out << Node->getNumber() << ':';
250 std::string OutStr = Out.str();
251 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
253 // Process string output to make it nicer...
254 for (unsigned i = 0; i != OutStr.length(); ++i)
255 if (OutStr[i] == '\n') { // Left justify
257 OutStr.insert(OutStr.begin()+i+1, 'l');
264 void MachineFunction::viewCFG() const
267 ViewGraph(this, "mf" + getFunction()->getName());
269 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
270 << "systems with Graphviz or gv!\n";
274 void MachineFunction::viewCFGOnly() const
281 // The next two methods are used to construct and to retrieve
282 // the MachineCodeForFunction object for the given function.
283 // construct() -- Allocates and initializes for a given function and target
284 // get() -- Returns a handle to the object.
285 // This should not be called before "construct()"
286 // for a given Function.
289 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
291 assert(Fn->getAnnotation(MF_AID) == 0 &&
292 "Object already exists for this function!");
293 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
294 Fn->addAnnotation(mcInfo);
298 void MachineFunction::destruct(const Function *Fn) {
299 bool Deleted = Fn->deleteAnnotation(MF_AID);
300 assert(Deleted && "Machine code did not exist for function!");
303 MachineFunction& MachineFunction::get(const Function *F)
305 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
306 assert(mc && "Call construct() method first to allocate the object");
310 void MachineFunction::clearSSARegMap() {
311 delete SSARegMapping;
315 //===----------------------------------------------------------------------===//
316 // MachineFrameInfo implementation
317 //===----------------------------------------------------------------------===//
319 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
320 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
322 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
323 const StackObject &SO = Objects[i];
324 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
326 OS << "variable sized";
328 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
329 OS << " alignment is " << SO.Alignment << " byte"
330 << (SO.Alignment != 1 ? "s," : ",");
332 if (i < NumFixedObjects)
334 if (i < NumFixedObjects || SO.SPOffset != -1) {
335 int Off = SO.SPOffset - ValOffset;
336 OS << " at location [SP";
346 if (HasVarSizedObjects)
347 OS << " Stack frame contains variable sized objects\n";
350 void MachineFrameInfo::dump(const MachineFunction &MF) const {
351 print(MF, *cerr.stream());
355 //===----------------------------------------------------------------------===//
356 // MachineJumpTableInfo implementation
357 //===----------------------------------------------------------------------===//
359 /// getJumpTableIndex - Create a new jump table entry in the jump table info
360 /// or return an existing one.
362 unsigned MachineJumpTableInfo::getJumpTableIndex(
363 const std::vector<MachineBasicBlock*> &DestBBs) {
364 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
365 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
366 if (JumpTables[i].MBBs == DestBBs)
369 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
370 return JumpTables.size()-1;
374 void MachineJumpTableInfo::print(std::ostream &OS) const {
375 // FIXME: this is lame, maybe we could print out the MBB numbers or something
376 // like {1, 2, 4, 5, 3, 0}
377 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
378 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
383 unsigned MachineJumpTableInfo::getEntrySize() const {
384 return TD->getPointerSize();
387 unsigned MachineJumpTableInfo::getAlignment() const {
388 return TD->getPointerAlignment();
391 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
394 //===----------------------------------------------------------------------===//
395 // MachineConstantPool implementation
396 //===----------------------------------------------------------------------===//
398 const Type *MachineConstantPoolEntry::getType() const {
399 if (isMachineConstantPoolEntry())
400 return Val.MachineCPVal->getType();
401 return Val.ConstVal->getType();
404 MachineConstantPool::~MachineConstantPool() {
405 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
406 if (Constants[i].isMachineConstantPoolEntry())
407 delete Constants[i].Val.MachineCPVal;
410 /// getConstantPoolIndex - Create a new entry in the constant pool or return
411 /// an existing one. User must specify an alignment in bytes for the object.
413 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
414 unsigned Alignment) {
415 assert(Alignment && "Alignment must be specified!");
416 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
418 // Check to see if we already have this constant.
420 // FIXME, this could be made much more efficient for large constant pools.
421 unsigned AlignMask = (1 << Alignment)-1;
422 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
423 if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
427 if (!Constants.empty()) {
428 Offset = Constants.back().getOffset();
429 Offset += TD->getTypeSize(Constants.back().getType());
430 Offset = (Offset+AlignMask)&~AlignMask;
433 Constants.push_back(MachineConstantPoolEntry(C, Offset));
434 return Constants.size()-1;
437 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
438 unsigned Alignment) {
439 assert(Alignment && "Alignment must be specified!");
440 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
442 // Check to see if we already have this constant.
444 // FIXME, this could be made much more efficient for large constant pools.
445 unsigned AlignMask = (1 << Alignment)-1;
446 int Idx = V->getExistingMachineCPValue(this, Alignment);
448 return (unsigned)Idx;
451 if (!Constants.empty()) {
452 Offset = Constants.back().getOffset();
453 Offset += TD->getTypeSize(Constants.back().getType());
454 Offset = (Offset+AlignMask)&~AlignMask;
457 Constants.push_back(MachineConstantPoolEntry(V, Offset));
458 return Constants.size()-1;
462 void MachineConstantPool::print(std::ostream &OS) const {
463 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
464 OS << " <cp #" << i << "> is";
465 if (Constants[i].isMachineConstantPoolEntry())
466 Constants[i].Val.MachineCPVal->print(OS);
468 OS << *(Value*)Constants[i].Val.ConstVal;
469 OS << " , offset=" << Constants[i].Offset;
474 void MachineConstantPool::dump() const { print(*cerr.stream()); }