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/DerivedTypes.h"
17 #include "llvm/CodeGen/MachineFunctionPass.h"
18 #include "llvm/CodeGen/MachineInstr.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Function.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Support/Compiler.h"
31 #include "llvm/Support/GraphWriter.h"
32 #include "llvm/Support/LeakDetector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Config/config.h"
39 static AnnotationID MF_AID(
40 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
42 // Out of line virtual function to home classes.
43 void MachineFunctionPass::virtfn() {}
46 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
48 const std::string Banner;
50 Printer (std::ostream *_OS, const std::string &_Banner) :
51 OS (_OS), Banner (_Banner) { }
53 const char *getPassName() const { return "MachineFunction Printer"; }
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 bool runOnMachineFunction(MachineFunction &MF) {
67 /// Returns a newly-created MachineFunction Printer pass. The default output
68 /// stream is std::cerr; the default banner is empty.
70 FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
71 const std::string &Banner){
72 return new Printer(OS, Banner);
76 struct VISIBILITY_HIDDEN Deleter : public MachineFunctionPass {
77 const char *getPassName() const { return "Machine Code Deleter"; }
79 bool runOnMachineFunction(MachineFunction &MF) {
80 // Delete the annotation from the function now.
81 MachineFunction::destruct(MF.getFunction());
87 /// MachineCodeDeletion Pass - This pass deletes all of the machine code for
88 /// the current function, which should happen after the function has been
89 /// emitted to a .s file or to memory.
90 FunctionPass *llvm::createMachineCodeDeleter() {
96 //===---------------------------------------------------------------------===//
97 // MachineFunction implementation
98 //===---------------------------------------------------------------------===//
100 MachineBasicBlock* ilist_traits<MachineBasicBlock>::createSentinel() {
101 MachineBasicBlock* dummy = new MachineBasicBlock();
102 LeakDetector::removeGarbageObject(dummy);
106 void ilist_traits<MachineBasicBlock>::transferNodesFromList(
107 iplist<MachineBasicBlock, ilist_traits<MachineBasicBlock> >& toList,
108 ilist_iterator<MachineBasicBlock> first,
109 ilist_iterator<MachineBasicBlock> last) {
110 if (Parent != toList.Parent)
111 for (; first != last; ++first)
112 first->Parent = toList.Parent;
115 MachineFunction::MachineFunction(const Function *F,
116 const TargetMachine &TM)
117 : Annotation(MF_AID), Fn(F), Target(TM), UsedPhysRegs(0) {
118 SSARegMapping = new SSARegMap();
120 FrameInfo = new MachineFrameInfo();
121 ConstantPool = new MachineConstantPool(TM.getTargetData());
123 // Set up jump table.
124 const TargetData &TD = *TM.getTargetData();
125 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
126 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
127 unsigned Alignment = IsPic ? TD.getABITypeAlignment(Type::Int32Ty)
128 : TD.getPointerABIAlignment();
129 JumpTableInfo = new MachineJumpTableInfo(EntrySize, Alignment);
131 BasicBlocks.Parent = this;
134 MachineFunction::~MachineFunction() {
136 delete SSARegMapping;
140 delete JumpTableInfo;
141 delete[] UsedPhysRegs;
145 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
146 /// recomputes them. This guarantees that the MBB numbers are sequential,
147 /// dense, and match the ordering of the blocks within the function. If a
148 /// specific MachineBasicBlock is specified, only that block and those after
149 /// it are renumbered.
150 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
151 if (empty()) { MBBNumbering.clear(); return; }
152 MachineFunction::iterator MBBI, E = end();
158 // Figure out the block number this should have.
159 unsigned BlockNo = 0;
161 BlockNo = prior(MBBI)->getNumber()+1;
163 for (; MBBI != E; ++MBBI, ++BlockNo) {
164 if (MBBI->getNumber() != (int)BlockNo) {
165 // Remove use of the old number.
166 if (MBBI->getNumber() != -1) {
167 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
168 "MBB number mismatch!");
169 MBBNumbering[MBBI->getNumber()] = 0;
172 // If BlockNo is already taken, set that block's number to -1.
173 if (MBBNumbering[BlockNo])
174 MBBNumbering[BlockNo]->setNumber(-1);
176 MBBNumbering[BlockNo] = MBBI;
177 MBBI->setNumber(BlockNo);
181 // Okay, all the blocks are renumbered. If we have compactified the block
182 // numbering, shrink MBBNumbering now.
183 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
184 MBBNumbering.resize(BlockNo);
188 void MachineFunction::dump() const { print(*cerr.stream()); }
190 void MachineFunction::print(std::ostream &OS) const {
191 OS << "# Machine code for " << Fn->getName () << "():\n";
193 // Print Frame Information
194 getFrameInfo()->print(*this, OS);
196 // Print JumpTable Information
197 getJumpTableInfo()->print(OS);
199 // Print Constant Pool
200 getConstantPool()->print(OS);
202 const MRegisterInfo *MRI = getTarget().getRegisterInfo();
204 if (livein_begin() != livein_end()) {
206 for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I) {
208 OS << " " << MRI->getName(I->first);
210 OS << " Reg #" << I->first;
213 OS << " in VR#" << I->second << " ";
217 if (liveout_begin() != liveout_end()) {
219 for (liveout_iterator I = liveout_begin(), E = liveout_end(); I != E; ++I)
221 OS << " " << MRI->getName(*I);
223 OS << " Reg #" << *I;
227 for (const_iterator BB = begin(); BB != end(); ++BB)
230 OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
233 /// CFGOnly flag - This is used to control whether or not the CFG graph printer
234 /// prints out the contents of basic blocks or not. This is acceptable because
235 /// this code is only really used for debugging purposes.
237 static bool CFGOnly = false;
241 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
242 static std::string getGraphName(const MachineFunction *F) {
243 return "CFG for '" + F->getFunction()->getName() + "' function";
246 static std::string getNodeLabel(const MachineBasicBlock *Node,
247 const MachineFunction *Graph) {
248 if (CFGOnly && Node->getBasicBlock() &&
249 !Node->getBasicBlock()->getName().empty())
250 return Node->getBasicBlock()->getName() + ":";
252 std::ostringstream Out;
254 Out << Node->getNumber() << ':';
260 std::string OutStr = Out.str();
261 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
263 // Process string output to make it nicer...
264 for (unsigned i = 0; i != OutStr.length(); ++i)
265 if (OutStr[i] == '\n') { // Left justify
267 OutStr.insert(OutStr.begin()+i+1, 'l');
274 void MachineFunction::viewCFG() const
277 ViewGraph(this, "mf" + getFunction()->getName());
279 cerr << "SelectionDAG::viewGraph is only available in debug builds on "
280 << "systems with Graphviz or gv!\n";
284 void MachineFunction::viewCFGOnly() const
291 // The next two methods are used to construct and to retrieve
292 // the MachineCodeForFunction object for the given function.
293 // construct() -- Allocates and initializes for a given function and target
294 // get() -- Returns a handle to the object.
295 // This should not be called before "construct()"
296 // for a given Function.
299 MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
301 assert(Fn->getAnnotation(MF_AID) == 0 &&
302 "Object already exists for this function!");
303 MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
304 Fn->addAnnotation(mcInfo);
308 void MachineFunction::destruct(const Function *Fn) {
309 bool Deleted = Fn->deleteAnnotation(MF_AID);
310 assert(Deleted && "Machine code did not exist for function!");
313 MachineFunction& MachineFunction::get(const Function *F)
315 MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
316 assert(mc && "Call construct() method first to allocate the object");
320 void MachineFunction::clearSSARegMap() {
321 delete SSARegMapping;
325 //===----------------------------------------------------------------------===//
326 // MachineFrameInfo implementation
327 //===----------------------------------------------------------------------===//
329 void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
330 int ValOffset = MF.getTarget().getFrameInfo()->getOffsetOfLocalArea();
332 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
333 const StackObject &SO = Objects[i];
334 OS << " <fi #" << (int)(i-NumFixedObjects) << ">: ";
336 OS << "variable sized";
338 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
339 OS << " alignment is " << SO.Alignment << " byte"
340 << (SO.Alignment != 1 ? "s," : ",");
342 if (i < NumFixedObjects)
344 if (i < NumFixedObjects || SO.SPOffset != -1) {
345 int64_t Off = SO.SPOffset - ValOffset;
346 OS << " at location [SP";
356 if (HasVarSizedObjects)
357 OS << " Stack frame contains variable sized objects\n";
360 void MachineFrameInfo::dump(const MachineFunction &MF) const {
361 print(MF, *cerr.stream());
365 //===----------------------------------------------------------------------===//
366 // MachineJumpTableInfo implementation
367 //===----------------------------------------------------------------------===//
369 /// getJumpTableIndex - Create a new jump table entry in the jump table info
370 /// or return an existing one.
372 unsigned MachineJumpTableInfo::getJumpTableIndex(
373 const std::vector<MachineBasicBlock*> &DestBBs) {
374 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
375 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
376 if (JumpTables[i].MBBs == DestBBs)
379 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
380 return JumpTables.size()-1;
384 void MachineJumpTableInfo::print(std::ostream &OS) const {
385 // FIXME: this is lame, maybe we could print out the MBB numbers or something
386 // like {1, 2, 4, 5, 3, 0}
387 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
388 OS << " <jt #" << i << "> has " << JumpTables[i].MBBs.size()
393 void MachineJumpTableInfo::dump() const { print(*cerr.stream()); }
396 //===----------------------------------------------------------------------===//
397 // MachineConstantPool implementation
398 //===----------------------------------------------------------------------===//
400 const Type *MachineConstantPoolEntry::getType() const {
401 if (isMachineConstantPoolEntry())
402 return Val.MachineCPVal->getType();
403 return Val.ConstVal->getType();
406 MachineConstantPool::~MachineConstantPool() {
407 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
408 if (Constants[i].isMachineConstantPoolEntry())
409 delete Constants[i].Val.MachineCPVal;
412 /// getConstantPoolIndex - Create a new entry in the constant pool or return
413 /// an existing one. User must specify an alignment in bytes for the object.
415 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
416 unsigned Alignment) {
417 assert(Alignment && "Alignment must be specified!");
418 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
420 // Check to see if we already have this constant.
422 // FIXME, this could be made much more efficient for large constant pools.
423 unsigned AlignMask = (1 << Alignment)-1;
424 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
425 if (Constants[i].Val.ConstVal == C && (Constants[i].Offset & AlignMask)== 0)
429 if (!Constants.empty()) {
430 Offset = Constants.back().getOffset();
431 Offset += TD->getTypeSize(Constants.back().getType());
432 Offset = (Offset+AlignMask)&~AlignMask;
435 Constants.push_back(MachineConstantPoolEntry(C, Offset));
436 return Constants.size()-1;
439 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
440 unsigned Alignment) {
441 assert(Alignment && "Alignment must be specified!");
442 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
444 // Check to see if we already have this constant.
446 // FIXME, this could be made much more efficient for large constant pools.
447 unsigned AlignMask = (1 << Alignment)-1;
448 int Idx = V->getExistingMachineCPValue(this, Alignment);
450 return (unsigned)Idx;
453 if (!Constants.empty()) {
454 Offset = Constants.back().getOffset();
455 Offset += TD->getTypeSize(Constants.back().getType());
456 Offset = (Offset+AlignMask)&~AlignMask;
459 Constants.push_back(MachineConstantPoolEntry(V, Offset));
460 return Constants.size()-1;
464 void MachineConstantPool::print(std::ostream &OS) const {
465 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
466 OS << " <cp #" << i << "> is";
467 if (Constants[i].isMachineConstantPoolEntry())
468 Constants[i].Val.MachineCPVal->print(OS);
470 OS << *(Value*)Constants[i].Val.ConstVal;
471 OS << " , offset=" << Constants[i].getOffset();
476 void MachineConstantPool::dump() const { print(*cerr.stream()); }