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/LeakDetector.h"
29 #include "llvm/Support/GraphWriter.h"
30 #include "llvm/System/Path.h"
31 #include "llvm/System/Program.h"
32 #include "llvm/Config/config.h"
39 static AnnotationID MF_AID(
40 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
44 struct 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 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;
134 void MachineFunction::dump() const { print(std::cerr); }
136 void MachineFunction::print(std::ostream &OS) const {
137 OS << "# Machine code for " << Fn->getName () << "():\n";
139 // Print Frame Information
140 getFrameInfo()->print(*this, OS);
142 // Print JumpTable Information
143 getJumpTableInfo()->print(OS);
145 // Print Constant Pool
146 getConstantPool()->print(OS);
148 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
150 if (livein_begin() != livein_end()) {
152 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
154 OS << " " << MRI->getName(I->first);
156 OS << " Reg #" << I->first;
159 OS << " in VR#" << I->second << " ";
163 if (liveout_begin() != liveout_end()) {
165 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
167 OS << " " << MRI->getName(*I);
169 OS << " Reg #" << *I;
173 for (const_iterator BB = begin(); BB != end(); ++BB)
176 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
179 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
180 /// prints out the contents of basic blocks or not. This is acceptable because
181 /// this code is only really used for debugging purposes.
183 static bool CFGOnly = false;
187 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
188 static std::string getGraphName(const MachineFunction *F) {
189 return "CFG for '" + F->getFunction()->getName() + "' function";
192 static std::string getNodeLabel(const MachineBasicBlock *Node,
193 const MachineFunction *Graph) {
194 if (CFGOnly && Node->getBasicBlock() &&
195 !Node->getBasicBlock()->getName().empty())
196 return Node->getBasicBlock()->getName() + ":";
198 std::ostringstream Out;
200 Out << Node->getNumber() << ':';
206 std::string OutStr = Out.str();
207 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
209 // Process string output to make it nicer...
210 for (unsigned i = 0; i != OutStr.length(); ++i)
211 if (OutStr[i] == '\n') { // Left justify
213 OutStr.insert(OutStr.begin()+i+1, 'l');
220 void MachineFunction::viewCFG() const
225 sprintf(pathsuff, "%06u", unsigned(rand()));
227 sys::Path TempDir = sys::Path::GetTemporaryDirectory();
228 sys::Path Filename = TempDir;
229 Filename.appendComponent("mf" + getFunction()->getName() + "." + pathsuff + ".dot");
230 std::cerr << "Writing '" << Filename << "'... ";
231 std::ofstream F(Filename.c_str());
234 std::cerr << " error opening file for writing!\n";
243 sys::Path Graphviz(LLVM_PATH_GRAPHVIZ);
244 std::vector<const char*> args;
245 args.push_back(Graphviz.c_str());
246 args.push_back(Filename.c_str());
249 std::cerr << "Running 'Graphviz' program... " << std::flush;
250 if (sys::Program::ExecuteAndWait(Graphviz, &args[0])) {
251 std::cerr << "Error viewing graph: 'Graphviz' not in path?\n";
253 Filename.eraseFromDisk();
256 #elif (HAVE_GV && HAVE_DOT)
257 sys::Path PSFilename = TempDir;
258 PSFilename.appendComponent(std::string("mf.tempgraph") + "." + pathsuff + ".ps");
260 sys::Path dot(LLVM_PATH_DOT);
261 std::vector<const char*> args;
262 args.push_back(dot.c_str());
263 args.push_back("-Tps");
264 args.push_back("-Nfontname=Courier");
265 args.push_back("-Gsize=7.5,10");
266 args.push_back(Filename.c_str());
267 args.push_back("-o");
268 args.push_back(PSFilename.c_str());
271 std::cerr << "Running 'dot' program... " << std::flush;
272 if (sys::Program::ExecuteAndWait(dot, &args[0])) {
273 std::cerr << "Error viewing graph: 'dot' not in path?\n";
277 sys::Path gv(LLVM_PATH_GV);
279 args.push_back(gv.c_str());
280 args.push_back(PSFilename.c_str());
283 sys::Program::ExecuteAndWait(gv, &args[0]);
285 Filename.eraseFromDisk();
286 PSFilename.eraseFromDisk();
289 sys::Path dotty(LLVM_PATH_DOTTY);
290 std::vector<const char*> args;
291 args.push_back(dotty.c_str());
292 args.push_back(Filename.c_str());
295 std::cerr << "Running 'dotty' program... " << std::flush;
296 if (sys::Program::ExecuteAndWait(dotty, &args[0])) {
297 std::cerr << "Error viewing graph: 'dotty' not in path?\n";
299 #ifndef __MINGW32__ // Dotty spawns another app and doesn't wait until it returns
300 Filename.eraseFromDisk();
307 std::cerr << "MachineFunction::viewCFG is only available in debug builds on "
308 << "systems with Graphviz or gv!\n";
311 Filename.eraseFromDisk();
312 TempDir.eraseFromDisk(true);
316 void MachineFunction::viewCFGOnly() const
323 // The next two methods are used to construct and to retrieve
324 // the MachineCodeForFunction object for the given function.
325 // construct() -- Allocates and initializes for a given function and target
326 // get() -- Returns a handle to the object.
327 // This should not be called before "construct()"
328 // for a given Function.
331 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
333 assert(Fn->getAnnotation(MF_AID) == 0 &&
334 "Object already exists for this function!");
335 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
336 Fn->addAnnotation(mcInfo);
340 void MachineFunction::destruct(const Function *Fn) {
341 bool Deleted = Fn->deleteAnnotation(MF_AID);
342 assert(Deleted && "Machine code did not exist for function!");
345 MachineFunction& MachineFunction::get(const Function *F)
347 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
348 assert(mc && "Call construct() method first to allocate the object");
352 void MachineFunction::clearSSARegMap() {
353 delete SSARegMapping;
357 //===----------------------------------------------------------------------===//
358 // MachineFrameInfo implementation
359 //===----------------------------------------------------------------------===//
361 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
362 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
364 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
365 const StackObject &SO = Objects[i];
366 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
368 OS << "variable sized";
370 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
371 OS << " alignment is " << SO.Alignment << " byte"
372 << (SO.Alignment != 1 ? "s," : ",");
374 if (i < NumFixedObjects)
376 if (i < NumFixedObjects || SO.SPOffset != -1) {
377 int Off = SO.SPOffset - ValOffset;
378 OS << " at location [SP";
388 if (HasVarSizedObjects)
389 OS << " Stack frame contains variable sized objects\n";
392 void MachineFrameInfo::dump(const MachineFunction &MF) const {
393 print(MF, std::cerr);
397 //===----------------------------------------------------------------------===//
398 // MachineJumpTableInfo implementation
399 //===----------------------------------------------------------------------===//
401 /// getJumpTableIndex - Create a new jump table entry in the jump table info
402 /// or return an existing one.
404 unsigned MachineJumpTableInfo::getJumpTableIndex(
405 std::vector<MachineBasicBlock*> &DestBBs) {
406 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
407 if (JumpTables[i].MBBs == DestBBs)
410 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
411 return JumpTables.size()-1;
415 void MachineJumpTableInfo::print(std::ostream &OS) const {
416 // FIXME: this is lame, maybe we could print out the MBB numbers or something
417 // like {1, 2, 4, 5, 3, 0}
418 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
419 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
424 unsigned MachineJumpTableInfo::getEntrySize() const {
425 return TD->getPointerSize();
428 unsigned MachineJumpTableInfo::getAlignment() const {
429 return TD->getPointerAlignment();
432 void MachineJumpTableInfo::dump() const { print(std::cerr); }
435 //===----------------------------------------------------------------------===//
436 // MachineConstantPool implementation
437 //===----------------------------------------------------------------------===//
439 /// getConstantPoolIndex - Create a new entry in the constant pool or return
440 /// an existing one. User must specify an alignment in bytes for the object.
442 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
443 unsigned Alignment) {
444 assert(Alignment && "Alignment must be specified!");
445 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
447 // Check to see if we already have this constant.
449 // FIXME, this could be made much more efficient for large constant pools.
450 unsigned AlignMask = (1 << Alignment)-1;
451 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
452 if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0)
456 if (!Constants.empty()) {
457 Offset = Constants.back().Offset;
458 Offset += TD->getTypeSize(Constants.back().Val->getType());
459 Offset = (Offset+AlignMask)&~AlignMask;
462 Constants.push_back(MachineConstantPoolEntry(C, Offset));
463 return Constants.size()-1;
467 void MachineConstantPool::print(std::ostream &OS) const {
468 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
469 OS << " <cp #" << i << "> is" << *(Value*)Constants[i].Val;
470 OS << " , offset=" << Constants[i].Offset;
475 void MachineConstantPool::dump() const { print(std::cerr); }