Fix comment for consistency sake.
[llvm/avr.git] / lib / CodeGen / MachineFunction.cpp
blob14ba36011f0ed8cfb11edd22a4f84e8a17428ba2
1 //===-- MachineFunction.cpp -----------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineJumpTableInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetFrameInfo.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/GraphWriter.h"
35 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm;
38 namespace {
39 struct VISIBILITY_HIDDEN Printer : public MachineFunctionPass {
40 static char ID;
42 raw_ostream &OS;
43 const std::string Banner;
45 Printer(raw_ostream &os, const std::string &banner)
46 : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
48 const char *getPassName() const { return "MachineFunction Printer"; }
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.setPreservesAll();
52 MachineFunctionPass::getAnalysisUsage(AU);
55 bool runOnMachineFunction(MachineFunction &MF) {
56 OS << Banner;
57 MF.print(OS);
58 return false;
61 char Printer::ID = 0;
64 /// Returns a newly-created MachineFunction Printer pass. The default banner is
65 /// empty.
66 ///
67 FunctionPass *llvm::createMachineFunctionPrinterPass(raw_ostream &OS,
68 const std::string &Banner){
69 return new Printer(OS, Banner);
72 //===---------------------------------------------------------------------===//
73 // MachineFunction implementation
74 //===---------------------------------------------------------------------===//
76 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
77 MBB->getParent()->DeleteMachineBasicBlock(MBB);
80 MachineFunction::MachineFunction(Function *F,
81 const TargetMachine &TM)
82 : Fn(F), Target(TM) {
83 if (TM.getRegisterInfo())
84 RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
85 MachineRegisterInfo(*TM.getRegisterInfo());
86 else
87 RegInfo = 0;
88 MFInfo = 0;
89 FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
90 MachineFrameInfo(*TM.getFrameInfo());
91 ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
92 MachineConstantPool(TM.getTargetData());
93 Alignment = TM.getTargetLowering()->getFunctionAlignment(F);
95 // Set up jump table.
96 const TargetData &TD = *TM.getTargetData();
97 bool IsPic = TM.getRelocationModel() == Reloc::PIC_;
98 unsigned EntrySize = IsPic ? 4 : TD.getPointerSize();
99 unsigned TyAlignment = IsPic ?
100 TD.getABITypeAlignment(Type::getInt32Ty(F->getContext()))
101 : TD.getPointerABIAlignment();
102 JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
103 MachineJumpTableInfo(EntrySize, TyAlignment);
106 MachineFunction::~MachineFunction() {
107 BasicBlocks.clear();
108 InstructionRecycler.clear(Allocator);
109 BasicBlockRecycler.clear(Allocator);
110 if (RegInfo) {
111 RegInfo->~MachineRegisterInfo();
112 Allocator.Deallocate(RegInfo);
114 if (MFInfo) {
115 MFInfo->~MachineFunctionInfo();
116 Allocator.Deallocate(MFInfo);
118 FrameInfo->~MachineFrameInfo(); Allocator.Deallocate(FrameInfo);
119 ConstantPool->~MachineConstantPool(); Allocator.Deallocate(ConstantPool);
120 JumpTableInfo->~MachineJumpTableInfo(); Allocator.Deallocate(JumpTableInfo);
124 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
125 /// recomputes them. This guarantees that the MBB numbers are sequential,
126 /// dense, and match the ordering of the blocks within the function. If a
127 /// specific MachineBasicBlock is specified, only that block and those after
128 /// it are renumbered.
129 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
130 if (empty()) { MBBNumbering.clear(); return; }
131 MachineFunction::iterator MBBI, E = end();
132 if (MBB == 0)
133 MBBI = begin();
134 else
135 MBBI = MBB;
137 // Figure out the block number this should have.
138 unsigned BlockNo = 0;
139 if (MBBI != begin())
140 BlockNo = prior(MBBI)->getNumber()+1;
142 for (; MBBI != E; ++MBBI, ++BlockNo) {
143 if (MBBI->getNumber() != (int)BlockNo) {
144 // Remove use of the old number.
145 if (MBBI->getNumber() != -1) {
146 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
147 "MBB number mismatch!");
148 MBBNumbering[MBBI->getNumber()] = 0;
151 // If BlockNo is already taken, set that block's number to -1.
152 if (MBBNumbering[BlockNo])
153 MBBNumbering[BlockNo]->setNumber(-1);
155 MBBNumbering[BlockNo] = MBBI;
156 MBBI->setNumber(BlockNo);
160 // Okay, all the blocks are renumbered. If we have compactified the block
161 // numbering, shrink MBBNumbering now.
162 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
163 MBBNumbering.resize(BlockNo);
166 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
167 /// of `new MachineInstr'.
169 MachineInstr *
170 MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID,
171 DebugLoc DL, bool NoImp) {
172 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
173 MachineInstr(TID, DL, NoImp);
176 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
177 /// 'Orig' instruction, identical in all ways except the the instruction
178 /// has no parent, prev, or next.
180 MachineInstr *
181 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
182 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
183 MachineInstr(*this, *Orig);
186 /// DeleteMachineInstr - Delete the given MachineInstr.
188 void
189 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
190 // Clear the instructions memoperands. This must be done manually because
191 // the instruction's parent pointer is now null, so it can't properly
192 // deallocate them on its own.
193 MI->clearMemOperands(*this);
195 MI->~MachineInstr();
196 InstructionRecycler.Deallocate(Allocator, MI);
199 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
200 /// instead of `new MachineBasicBlock'.
202 MachineBasicBlock *
203 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
204 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
205 MachineBasicBlock(*this, bb);
208 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
210 void
211 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
212 assert(MBB->getParent() == this && "MBB parent mismatch!");
213 MBB->~MachineBasicBlock();
214 BasicBlockRecycler.Deallocate(Allocator, MBB);
217 void MachineFunction::dump() const {
218 print(errs());
221 void MachineFunction::print(raw_ostream &OS) const {
222 OS << "# Machine code for " << Fn->getName() << "():\n";
224 // Print Frame Information
225 FrameInfo->print(*this, OS);
227 // Print JumpTable Information
228 JumpTableInfo->print(OS);
230 // Print Constant Pool
231 ConstantPool->print(OS);
233 const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
235 if (RegInfo && !RegInfo->livein_empty()) {
236 OS << "Live Ins:";
237 for (MachineRegisterInfo::livein_iterator
238 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
239 if (TRI)
240 OS << " " << TRI->getName(I->first);
241 else
242 OS << " Reg #" << I->first;
244 if (I->second)
245 OS << " in VR#" << I->second << ' ';
247 OS << '\n';
249 if (RegInfo && !RegInfo->liveout_empty()) {
250 OS << "Live Outs:";
251 for (MachineRegisterInfo::liveout_iterator
252 I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
253 if (TRI)
254 OS << ' ' << TRI->getName(*I);
255 else
256 OS << " Reg #" << *I;
257 OS << '\n';
260 for (const_iterator BB = begin(), E = end(); BB != E; ++BB)
261 BB->print(OS);
263 OS << "\n# End machine code for " << Fn->getName() << "().\n\n";
266 namespace llvm {
267 template<>
268 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
269 static std::string getGraphName(const MachineFunction *F) {
270 return "CFG for '" + F->getFunction()->getNameStr() + "' function";
273 static std::string getNodeLabel(const MachineBasicBlock *Node,
274 const MachineFunction *Graph,
275 bool ShortNames) {
276 if (ShortNames && Node->getBasicBlock() &&
277 !Node->getBasicBlock()->getName().empty())
278 return Node->getBasicBlock()->getNameStr() + ":";
280 std::string OutStr;
282 raw_string_ostream OSS(OutStr);
284 if (ShortNames)
285 OSS << Node->getNumber() << ':';
286 else
287 Node->print(OSS);
290 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
292 // Process string output to make it nicer...
293 for (unsigned i = 0; i != OutStr.length(); ++i)
294 if (OutStr[i] == '\n') { // Left justify
295 OutStr[i] = '\\';
296 OutStr.insert(OutStr.begin()+i+1, 'l');
298 return OutStr;
303 void MachineFunction::viewCFG() const
305 #ifndef NDEBUG
306 ViewGraph(this, "mf" + getFunction()->getNameStr());
307 #else
308 errs() << "SelectionDAG::viewGraph is only available in debug builds on "
309 << "systems with Graphviz or gv!\n";
310 #endif // NDEBUG
313 void MachineFunction::viewCFGOnly() const
315 #ifndef NDEBUG
316 ViewGraph(this, "mf" + getFunction()->getNameStr(), true);
317 #else
318 errs() << "SelectionDAG::viewGraph is only available in debug builds on "
319 << "systems with Graphviz or gv!\n";
320 #endif // NDEBUG
323 /// addLiveIn - Add the specified physical register as a live-in value and
324 /// create a corresponding virtual register for it.
325 unsigned MachineFunction::addLiveIn(unsigned PReg,
326 const TargetRegisterClass *RC) {
327 assert(RC->contains(PReg) && "Not the correct regclass!");
328 unsigned VReg = getRegInfo().createVirtualRegister(RC);
329 getRegInfo().addLiveIn(PReg, VReg);
330 return VReg;
333 /// getOrCreateDebugLocID - Look up the DebugLocTuple index with the given
334 /// source file, line, and column. If none currently exists, create a new
335 /// DebugLocTuple, and insert it into the DebugIdMap.
336 unsigned MachineFunction::getOrCreateDebugLocID(MDNode *CompileUnit,
337 unsigned Line, unsigned Col) {
338 DebugLocTuple Tuple(CompileUnit, Line, Col);
339 DenseMap<DebugLocTuple, unsigned>::iterator II
340 = DebugLocInfo.DebugIdMap.find(Tuple);
341 if (II != DebugLocInfo.DebugIdMap.end())
342 return II->second;
343 // Add a new tuple.
344 unsigned Id = DebugLocInfo.DebugLocations.size();
345 DebugLocInfo.DebugLocations.push_back(Tuple);
346 DebugLocInfo.DebugIdMap[Tuple] = Id;
347 return Id;
350 /// getDebugLocTuple - Get the DebugLocTuple for a given DebugLoc object.
351 DebugLocTuple MachineFunction::getDebugLocTuple(DebugLoc DL) const {
352 unsigned Idx = DL.getIndex();
353 assert(Idx < DebugLocInfo.DebugLocations.size() &&
354 "Invalid index into debug locations!");
355 return DebugLocInfo.DebugLocations[Idx];
358 //===----------------------------------------------------------------------===//
359 // MachineFrameInfo implementation
360 //===----------------------------------------------------------------------===//
362 /// CreateFixedObject - Create a new object at a fixed location on the stack.
363 /// All fixed objects should be created before other objects are created for
364 /// efficiency. By default, fixed objects are immutable. This returns an
365 /// index with a negative value.
367 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
368 bool Immutable) {
369 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
370 Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable));
371 return -++NumFixedObjects;
375 BitVector
376 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
377 assert(MBB && "MBB must be valid");
378 const MachineFunction *MF = MBB->getParent();
379 assert(MF && "MBB must be part of a MachineFunction");
380 const TargetMachine &TM = MF->getTarget();
381 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
382 BitVector BV(TRI->getNumRegs());
384 // Before CSI is calculated, no registers are considered pristine. They can be
385 // freely used and PEI will make sure they are saved.
386 if (!isCalleeSavedInfoValid())
387 return BV;
389 for (const unsigned *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
390 BV.set(*CSR);
392 // The entry MBB always has all CSRs pristine.
393 if (MBB == &MF->front())
394 return BV;
396 // On other MBBs the saved CSRs are not pristine.
397 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
398 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
399 E = CSI.end(); I != E; ++I)
400 BV.reset(I->getReg());
402 return BV;
406 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
407 const TargetFrameInfo *FI = MF.getTarget().getFrameInfo();
408 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
410 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
411 const StackObject &SO = Objects[i];
412 OS << " <fi#" << (int)(i-NumFixedObjects) << ">: ";
413 if (SO.Size == ~0ULL) {
414 OS << "dead\n";
415 continue;
417 if (SO.Size == 0)
418 OS << "variable sized";
419 else
420 OS << "size is " << SO.Size << " byte" << (SO.Size != 1 ? "s," : ",");
421 OS << " alignment is " << SO.Alignment << " byte"
422 << (SO.Alignment != 1 ? "s," : ",");
424 if (i < NumFixedObjects)
425 OS << " fixed";
426 if (i < NumFixedObjects || SO.SPOffset != -1) {
427 int64_t Off = SO.SPOffset - ValOffset;
428 OS << " at location [SP";
429 if (Off > 0)
430 OS << "+" << Off;
431 else if (Off < 0)
432 OS << Off;
433 OS << "]";
435 OS << "\n";
438 if (HasVarSizedObjects)
439 OS << " Stack frame contains variable sized objects\n";
442 void MachineFrameInfo::dump(const MachineFunction &MF) const {
443 print(MF, errs());
446 //===----------------------------------------------------------------------===//
447 // MachineJumpTableInfo implementation
448 //===----------------------------------------------------------------------===//
450 /// getJumpTableIndex - Create a new jump table entry in the jump table info
451 /// or return an existing one.
453 unsigned MachineJumpTableInfo::getJumpTableIndex(
454 const std::vector<MachineBasicBlock*> &DestBBs) {
455 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
456 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i)
457 if (JumpTables[i].MBBs == DestBBs)
458 return i;
460 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
461 return JumpTables.size()-1;
464 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
465 /// the jump tables to branch to New instead.
466 bool
467 MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
468 MachineBasicBlock *New) {
469 assert(Old != New && "Not making a change?");
470 bool MadeChange = false;
471 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) {
472 MachineJumpTableEntry &JTE = JumpTables[i];
473 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
474 if (JTE.MBBs[j] == Old) {
475 JTE.MBBs[j] = New;
476 MadeChange = true;
479 return MadeChange;
482 void MachineJumpTableInfo::print(raw_ostream &OS) const {
483 // FIXME: this is lame, maybe we could print out the MBB numbers or something
484 // like {1, 2, 4, 5, 3, 0}
485 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
486 OS << " <jt#" << i << "> has " << JumpTables[i].MBBs.size()
487 << " entries\n";
491 void MachineJumpTableInfo::dump() const { print(errs()); }
494 //===----------------------------------------------------------------------===//
495 // MachineConstantPool implementation
496 //===----------------------------------------------------------------------===//
498 const Type *MachineConstantPoolEntry::getType() const {
499 if (isMachineConstantPoolEntry())
500 return Val.MachineCPVal->getType();
501 return Val.ConstVal->getType();
505 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
506 if (isMachineConstantPoolEntry())
507 return Val.MachineCPVal->getRelocationInfo();
508 return Val.ConstVal->getRelocationInfo();
511 MachineConstantPool::~MachineConstantPool() {
512 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
513 if (Constants[i].isMachineConstantPoolEntry())
514 delete Constants[i].Val.MachineCPVal;
517 /// getConstantPoolIndex - Create a new entry in the constant pool or return
518 /// an existing one. User must specify the log2 of the minimum required
519 /// alignment for the object.
521 unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
522 unsigned Alignment) {
523 assert(Alignment && "Alignment must be specified!");
524 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
526 // Check to see if we already have this constant.
528 // FIXME, this could be made much more efficient for large constant pools.
529 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
530 if (Constants[i].Val.ConstVal == C &&
531 (Constants[i].getAlignment() & (Alignment - 1)) == 0)
532 return i;
534 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
535 return Constants.size()-1;
538 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
539 unsigned Alignment) {
540 assert(Alignment && "Alignment must be specified!");
541 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
543 // Check to see if we already have this constant.
545 // FIXME, this could be made much more efficient for large constant pools.
546 int Idx = V->getExistingMachineCPValue(this, Alignment);
547 if (Idx != -1)
548 return (unsigned)Idx;
550 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
551 return Constants.size()-1;
554 void MachineConstantPool::print(raw_ostream &OS) const {
555 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
556 OS << " <cp#" << i << "> is";
557 if (Constants[i].isMachineConstantPoolEntry())
558 Constants[i].Val.MachineCPVal->print(OS);
559 else
560 OS << *(Value*)Constants[i].Val.ConstVal;
561 OS << " , alignment=" << Constants[i].getAlignment();
562 OS << "\n";
566 void MachineConstantPool::dump() const { print(errs()); }