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