xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision ee7eaa25cffa482517b4edea6cfb32e474916bb0)
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/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/Config/config.h"
31 #include <fstream>
32 #include <iostream>
33 #include <sstream>
34 
35 using namespace llvm;
36 
37 static AnnotationID MF_AID(
38   AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
39 
40 
41 namespace {
42   struct Printer : public MachineFunctionPass {
43     std::ostream *OS;
44     const std::string Banner;
45 
46     Printer (std::ostream *_OS, const std::string &_Banner) :
47       OS (_OS), Banner (_Banner) { }
48 
49     const char *getPassName() const { return "MachineFunction Printer"; }
50 
51     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52       AU.setPreservesAll();
53     }
54 
55     bool runOnMachineFunction(MachineFunction &MF) {
56       (*OS) << Banner;
57       MF.print (*OS);
58       return false;
59     }
60   };
61 }
62 
63 /// Returns a newly-created MachineFunction Printer pass. The default output
64 /// stream is std::cerr; the default banner is empty.
65 ///
66 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
67                                                      const std::string &Banner){
68   return new Printer(OS, Banner);
69 }
70 
71 namespace {
72   struct Deleter : public MachineFunctionPass {
73     const char *getPassName() const { return "Machine Code Deleter"; }
74 
75     bool runOnMachineFunction(MachineFunction &MF) {
76       // Delete the annotation from the function now.
77       MachineFunction::destruct(MF.getFunction());
78       return true;
79     }
80   };
81 }
82 
83 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
84 /// the current function, which should happen after the function has been
85 /// emitted to a .s file or to memory.
86 FunctionPass *llvm::createMachineCodeDeleter() {
87   return new Deleter();
88 }
89 
90 
91 
92 //===---------------------------------------------------------------------===//
93 // MachineFunction implementation
94 //===---------------------------------------------------------------------===//
95 
96 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
97   MachineBasicBlock* dummy = new MachineBasicBlock();
98   LeakDetector::removeGarbageObject(dummy);
99   return dummy;
100 }
101 
102 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
103   iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
104   ilist_iterator<MachineBasicBlock> first,
105   ilist_iterator<MachineBasicBlock> last) {
106   if (Parent != toList.Parent)
107     for (; first != last; ++first)
108       first->Parent = toList.Parent;
109 }
110 
111 MachineFunction::MachineFunction(const Function *F,
112                                  const TargetMachine &TM)
113   : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
114   SSARegMapping = new SSARegMap();
115   MFInfo = 0;
116   FrameInfo = new MachineFrameInfo();
117   ConstantPool = new MachineConstantPool(TM.getTargetData());
118   JumpTableInfo = new MachineJumpTableInfo(TM.getTargetData());
119   BasicBlocks.Parent = this;
120 }
121 
122 MachineFunction::~MachineFunction() {
123   BasicBlocks.clear();
124   delete SSARegMapping;
125   delete MFInfo;
126   delete FrameInfo;
127   delete ConstantPool;
128   delete JumpTableInfo;
129   delete[] UsedPhysRegs;
130 }
131 
132 void MachineFunction::dump() const { print(std::cerr); }
133 
134 void MachineFunction::print(std::ostream &OS) const {
135   OS << "# Machine code for " << Fn->getName () << "():\n";
136 
137   // Print Frame Information
138   getFrameInfo()->print(*this, OS);
139 
140   // Print JumpTable Information
141   getJumpTableInfo()->print(OS);
142 
143   // Print Constant Pool
144   getConstantPool()->print(OS);
145 
146   const MRegisterInfo *MRI = getTarget().getRegisterInfo();
147 
148   if (livein_begin() != livein_end()) {
149     OS << "Live Ins:";
150     for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
151       if (MRI)
152         OS << " " << MRI->getName(I->first);
153       else
154         OS << " Reg #" << I->first;
155 
156       if (I->second)
157         OS << " in VR#" << I->second << " ";
158     }
159     OS << "\n";
160   }
161   if (liveout_begin() != liveout_end()) {
162     OS << "Live Outs:";
163     for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
164       if (MRI)
165         OS << " " << MRI->getName(*I);
166       else
167         OS << " Reg #" << *I;
168     OS << "\n";
169   }
170 
171   for (const_iterator BB = begin(); BB != end(); ++BB)
172     BB->print(OS);
173 
174   OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
175 }
176 
177 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
178 /// prints out the contents of basic blocks or not.  This is acceptable because
179 /// this code is only really used for debugging purposes.
180 ///
181 static bool CFGOnly = false;
182 
183 namespace llvm {
184   template<>
185   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
186     static std::string getGraphName(const MachineFunction *F) {
187       return "CFG for '" + F->getFunction()->getName() + "' function";
188     }
189 
190     static std::string getNodeLabel(const MachineBasicBlock *Node,
191                                     const MachineFunction *Graph) {
192       if (CFGOnly && Node->getBasicBlock() &&
193           !Node->getBasicBlock()->getName().empty())
194         return Node->getBasicBlock()->getName() + ":";
195 
196       std::ostringstream Out;
197       if (CFGOnly) {
198         Out << Node->getNumber() << ':';
199         return Out.str();
200       }
201 
202       Node->print(Out);
203 
204       std::string OutStr = Out.str();
205       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
206 
207       // Process string output to make it nicer...
208       for (unsigned i = 0; i != OutStr.length(); ++i)
209         if (OutStr[i] == '\n') {                            // Left justify
210           OutStr[i] = '\\';
211           OutStr.insert(OutStr.begin()+i+1, 'l');
212         }
213       return OutStr;
214     }
215   };
216 }
217 
218 void MachineFunction::viewCFG() const
219 {
220 #ifndef NDEBUG
221   ViewGraph(this, "mf" + getFunction()->getName());
222 #else
223   std::cerr << "SelectionDAG::viewGraph is only available in debug builds on "
224             << "systems with Graphviz or gv!\n";
225 #endif // NDEBUG
226 }
227 
228 void MachineFunction::viewCFGOnly() const
229 {
230   CFGOnly = true;
231   viewCFG();
232   CFGOnly = false;
233 }
234 
235 // The next two methods are used to construct and to retrieve
236 // the MachineCodeForFunction object for the given function.
237 // construct() -- Allocates and initializes for a given function and target
238 // get()       -- Returns a handle to the object.
239 //                This should not be called before "construct()"
240 //                for a given Function.
241 //
242 MachineFunction&
243 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
244 {
245   assert(Fn->getAnnotation(MF_AID) == 0 &&
246          "Object already exists for this function!");
247   MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
248   Fn->addAnnotation(mcInfo);
249   return *mcInfo;
250 }
251 
252 void MachineFunction::destruct(const Function *Fn) {
253   bool Deleted = Fn->deleteAnnotation(MF_AID);
254   assert(Deleted && "Machine code did not exist for function!");
255 }
256 
257 MachineFunction& MachineFunction::get(const Function *F)
258 {
259   MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
260   assert(mc && "Call construct() method first to allocate the object");
261   return *mc;
262 }
263 
264 void MachineFunction::clearSSARegMap() {
265   delete SSARegMapping;
266   SSARegMapping = 0;
267 }
268 
269 //===----------------------------------------------------------------------===//
270 //  MachineFrameInfo implementation
271 //===----------------------------------------------------------------------===//
272 
273 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
274   int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
275 
276   for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
277     const StackObject &SO = Objects[i];
278     OS << "  <fi #" << (int)(i-NumFixedObjects) << ">: ";
279     if (SO.Size == 0)
280       OS << "variable sized";
281     else
282       OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
283     OS << " alignment is " << SO.Alignment << " byte"
284        << (SO.Alignment != 1 ? "s," : ",");
285 
286     if (i < NumFixedObjects)
287       OS << " fixed";
288     if (i < NumFixedObjects || SO.SPOffset != -1) {
289       int Off = SO.SPOffset - ValOffset;
290       OS << " at location [SP";
291       if (Off > 0)
292         OS << "+" << Off;
293       else if (Off < 0)
294         OS << Off;
295       OS << "]";
296     }
297     OS << "\n";
298   }
299 
300   if (HasVarSizedObjects)
301     OS << "  Stack frame contains variable sized objects\n";
302 }
303 
304 void MachineFrameInfo::dump(const MachineFunction &MF) const {
305   print(MF, std::cerr);
306 }
307 
308 
309 //===----------------------------------------------------------------------===//
310 //  MachineJumpTableInfo implementation
311 //===----------------------------------------------------------------------===//
312 
313 /// getJumpTableIndex - Create a new jump table entry in the jump table info
314 /// or return an existing one.
315 ///
316 unsigned MachineJumpTableInfo::getJumpTableIndex(
317                                      std::vector<MachineBasicBlock*> &DestBBs) {
318   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
319     if (JumpTables[i].MBBs == DestBBs)
320       return i;
321 
322   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
323   return JumpTables.size()-1;
324 }
325 
326 
327 void MachineJumpTableInfo::print(std::ostream &OS) const {
328   // FIXME: this is lame, maybe we could print out the MBB numbers or something
329   // like {1, 2, 4, 5, 3, 0}
330   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
331     OS << "  <jt #" << i << "> has " << JumpTables[i].MBBs.size()
332        << " entries\n";
333   }
334 }
335 
336 unsigned MachineJumpTableInfo::getEntrySize() const {
337   return TD->getPointerSize();
338 }
339 
340 unsigned MachineJumpTableInfo::getAlignment() const {
341   return TD->getPointerAlignment();
342 }
343 
344 void MachineJumpTableInfo::dump() const { print(std::cerr); }
345 
346 
347 //===----------------------------------------------------------------------===//
348 //  MachineConstantPool implementation
349 //===----------------------------------------------------------------------===//
350 
351 /// getConstantPoolIndex - Create a new entry in the constant pool or return
352 /// an existing one.  User must specify an alignment in bytes for the object.
353 ///
354 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
355                                                    unsigned Alignment) {
356   assert(Alignment && "Alignment must be specified!");
357   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
358 
359   // Check to see if we already have this constant.
360   //
361   // FIXME, this could be made much more efficient for large constant pools.
362   unsigned AlignMask = (1 << Alignment)-1;
363   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
364     if (Constants[i].Val == C && (Constants[i].Offset & AlignMask) == 0)
365       return i;
366 
367   unsigned Offset = 0;
368   if (!Constants.empty()) {
369     Offset = Constants.back().Offset;
370     Offset += TD->getTypeSize(Constants.back().Val->getType());
371     Offset = (Offset+AlignMask)&~AlignMask;
372   }
373 
374   Constants.push_back(MachineConstantPoolEntry(C, Offset));
375   return Constants.size()-1;
376 }
377 
378 
379 void MachineConstantPool::print(std::ostream &OS) const {
380   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
381     OS << "  <cp #" << i << "> is" << *(Value*)Constants[i].Val;
382     OS << " , offset=" << Constants[i].Offset;
383     OS << "\n";
384   }
385 }
386 
387 void MachineConstantPool::dump() const { print(std::cerr); }
388