Prune trailing whitespaces in comment lines.
[oota-llvm.git] / include / llvm / CodeGen / MachineFunction.h
1 //===-- llvm/CodeGen/MachineFunction.h --------------------------*- C++ -*-===//
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 for a function.  This class contains a list of
11 // MachineBasicBlock instances that make up the current compiled function.
12 //
13 // This class also contains pointers to various classes which hold
14 // target-specific information about the generated code.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
19 #define LLVM_CODEGEN_MACHINEFUNCTION_H
20
21 #include "llvm/ADT/ilist.h"
22 #include "llvm/CodeGen/MachineBasicBlock.h"
23 #include "llvm/IR/DebugLoc.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/ArrayRecycler.h"
27 #include "llvm/Support/Recycler.h"
28
29 namespace llvm {
30
31 class Value;
32 class Function;
33 class GCModuleInfo;
34 class MachineRegisterInfo;
35 class MachineFrameInfo;
36 class MachineConstantPool;
37 class MachineJumpTableInfo;
38 class MachineModuleInfo;
39 class MCContext;
40 class Pass;
41 class PseudoSourceValueManager;
42 class TargetMachine;
43 class TargetSubtargetInfo;
44 class TargetRegisterClass;
45 struct MachinePointerInfo;
46
47 template <>
48 struct ilist_traits<MachineBasicBlock>
49     : public ilist_default_traits<MachineBasicBlock> {
50   mutable ilist_half_node<MachineBasicBlock> Sentinel;
51 public:
52   MachineBasicBlock *createSentinel() const {
53     return static_cast<MachineBasicBlock*>(&Sentinel);
54   }
55   void destroySentinel(MachineBasicBlock *) const {}
56
57   MachineBasicBlock *provideInitialHead() const { return createSentinel(); }
58   MachineBasicBlock *ensureHead(MachineBasicBlock*) const {
59     return createSentinel();
60   }
61   static void noteHead(MachineBasicBlock*, MachineBasicBlock*) {}
62
63   void addNodeToList(MachineBasicBlock* MBB);
64   void removeNodeFromList(MachineBasicBlock* MBB);
65   void deleteNode(MachineBasicBlock *MBB);
66 private:
67   void createNode(const MachineBasicBlock &);
68 };
69
70 /// MachineFunctionInfo - This class can be derived from and used by targets to
71 /// hold private target-specific information for each MachineFunction.  Objects
72 /// of type are accessed/created with MF::getInfo and destroyed when the
73 /// MachineFunction is destroyed.
74 struct MachineFunctionInfo {
75   virtual ~MachineFunctionInfo();
76
77   /// \brief Factory function: default behavior is to call new using the
78   /// supplied allocator.
79   ///
80   /// This function can be overridden in a derive class.
81   template<typename Ty>
82   static Ty *create(BumpPtrAllocator &Allocator, MachineFunction &MF) {
83     return new (Allocator.Allocate<Ty>()) Ty(MF);
84   }
85 };
86
87 class MachineFunction {
88   const Function *Fn;
89   const TargetMachine &Target;
90   const TargetSubtargetInfo *STI;
91   MCContext &Ctx;
92   MachineModuleInfo &MMI;
93
94   // RegInfo - Information about each register in use in the function.
95   MachineRegisterInfo *RegInfo;
96
97   // Used to keep track of target-specific per-machine function information for
98   // the target implementation.
99   MachineFunctionInfo *MFInfo;
100
101   // Keep track of objects allocated on the stack.
102   MachineFrameInfo *FrameInfo;
103
104   // Keep track of constants which are spilled to memory
105   MachineConstantPool *ConstantPool;
106
107   // Keep track of jump tables for switch instructions
108   MachineJumpTableInfo *JumpTableInfo;
109
110   // Function-level unique numbering for MachineBasicBlocks.  When a
111   // MachineBasicBlock is inserted into a MachineFunction is it automatically
112   // numbered and this vector keeps track of the mapping from ID's to MBB's.
113   std::vector<MachineBasicBlock*> MBBNumbering;
114
115   // Pool-allocate MachineFunction-lifetime and IR objects.
116   BumpPtrAllocator Allocator;
117
118   // Allocation management for instructions in function.
119   Recycler<MachineInstr> InstructionRecycler;
120
121   // Allocation management for operand arrays on instructions.
122   ArrayRecycler<MachineOperand> OperandRecycler;
123
124   // Allocation management for basic blocks in function.
125   Recycler<MachineBasicBlock> BasicBlockRecycler;
126
127   // List of machine basic blocks in function
128   typedef ilist<MachineBasicBlock> BasicBlockListType;
129   BasicBlockListType BasicBlocks;
130
131   /// FunctionNumber - This provides a unique ID for each function emitted in
132   /// this translation unit.
133   ///
134   unsigned FunctionNumber;
135
136   /// Alignment - The alignment of the function.
137   unsigned Alignment;
138
139   /// ExposesReturnsTwice - True if the function calls setjmp or related
140   /// functions with attribute "returns twice", but doesn't have
141   /// the attribute itself.
142   /// This is used to limit optimizations which cannot reason
143   /// about the control flow of such functions.
144   bool ExposesReturnsTwice;
145
146   /// True if the function includes any inline assembly.
147   bool HasInlineAsm;
148
149   // Allocation management for pseudo source values.
150   std::unique_ptr<PseudoSourceValueManager> PSVManager;
151
152   MachineFunction(const MachineFunction &) = delete;
153   void operator=(const MachineFunction&) = delete;
154 public:
155   MachineFunction(const Function *Fn, const TargetMachine &TM,
156                   unsigned FunctionNum, MachineModuleInfo &MMI);
157   ~MachineFunction();
158
159   MachineModuleInfo &getMMI() const { return MMI; }
160   MCContext &getContext() const { return Ctx; }
161
162   PseudoSourceValueManager &getPSVManager() const { return *PSVManager; }
163
164   /// Return the DataLayout attached to the Module associated to this MF.
165   const DataLayout &getDataLayout() const;
166
167   /// getFunction - Return the LLVM function that this machine code represents
168   ///
169   const Function *getFunction() const { return Fn; }
170
171   /// getName - Return the name of the corresponding LLVM function.
172   ///
173   StringRef getName() const;
174
175   /// getFunctionNumber - Return a unique ID for the current function.
176   ///
177   unsigned getFunctionNumber() const { return FunctionNumber; }
178
179   /// getTarget - Return the target machine this machine code is compiled with
180   ///
181   const TargetMachine &getTarget() const { return Target; }
182
183   /// getSubtarget - Return the subtarget for which this machine code is being
184   /// compiled.
185   const TargetSubtargetInfo &getSubtarget() const { return *STI; }
186   void setSubtarget(const TargetSubtargetInfo *ST) { STI = ST; }
187
188   /// getSubtarget - This method returns a pointer to the specified type of
189   /// TargetSubtargetInfo.  In debug builds, it verifies that the object being
190   /// returned is of the correct type.
191   template<typename STC> const STC &getSubtarget() const {
192     return *static_cast<const STC *>(STI);
193   }
194
195   /// getRegInfo - Return information about the registers currently in use.
196   ///
197   MachineRegisterInfo &getRegInfo() { return *RegInfo; }
198   const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
199
200   /// getFrameInfo - Return the frame info object for the current function.
201   /// This object contains information about objects allocated on the stack
202   /// frame of the current function in an abstract way.
203   ///
204   MachineFrameInfo *getFrameInfo() { return FrameInfo; }
205   const MachineFrameInfo *getFrameInfo() const { return FrameInfo; }
206
207   /// getJumpTableInfo - Return the jump table info object for the current
208   /// function.  This object contains information about jump tables in the
209   /// current function.  If the current function has no jump tables, this will
210   /// return null.
211   const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
212   MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
213
214   /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
215   /// does already exist, allocate one.
216   MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
217
218   /// getConstantPool - Return the constant pool object for the current
219   /// function.
220   ///
221   MachineConstantPool *getConstantPool() { return ConstantPool; }
222   const MachineConstantPool *getConstantPool() const { return ConstantPool; }
223
224   /// getAlignment - Return the alignment (log2, not bytes) of the function.
225   ///
226   unsigned getAlignment() const { return Alignment; }
227
228   /// setAlignment - Set the alignment (log2, not bytes) of the function.
229   ///
230   void setAlignment(unsigned A) { Alignment = A; }
231
232   /// ensureAlignment - Make sure the function is at least 1 << A bytes aligned.
233   void ensureAlignment(unsigned A) {
234     if (Alignment < A) Alignment = A;
235   }
236
237   /// exposesReturnsTwice - Returns true if the function calls setjmp or
238   /// any other similar functions with attribute "returns twice" without
239   /// having the attribute itself.
240   bool exposesReturnsTwice() const {
241     return ExposesReturnsTwice;
242   }
243
244   /// setCallsSetJmp - Set a flag that indicates if there's a call to
245   /// a "returns twice" function.
246   void setExposesReturnsTwice(bool B) {
247     ExposesReturnsTwice = B;
248   }
249
250   /// Returns true if the function contains any inline assembly.
251   bool hasInlineAsm() const {
252     return HasInlineAsm;
253   }
254
255   /// Set a flag that indicates that the function contains inline assembly.
256   void setHasInlineAsm(bool B) {
257     HasInlineAsm = B;
258   }
259
260   /// getInfo - Keep track of various per-function pieces of information for
261   /// backends that would like to do so.
262   ///
263   template<typename Ty>
264   Ty *getInfo() {
265     if (!MFInfo)
266       MFInfo = Ty::template create<Ty>(Allocator, *this);
267     return static_cast<Ty*>(MFInfo);
268   }
269
270   template<typename Ty>
271   const Ty *getInfo() const {
272      return const_cast<MachineFunction*>(this)->getInfo<Ty>();
273   }
274
275   /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
276   /// are inserted into the machine function.  The block number for a machine
277   /// basic block can be found by using the MBB::getBlockNumber method, this
278   /// method provides the inverse mapping.
279   ///
280   MachineBasicBlock *getBlockNumbered(unsigned N) const {
281     assert(N < MBBNumbering.size() && "Illegal block number");
282     assert(MBBNumbering[N] && "Block was removed from the machine function!");
283     return MBBNumbering[N];
284   }
285
286   /// Should we be emitting segmented stack stuff for the function
287   bool shouldSplitStack();
288
289   /// getNumBlockIDs - Return the number of MBB ID's allocated.
290   ///
291   unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
292
293   /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
294   /// recomputes them.  This guarantees that the MBB numbers are sequential,
295   /// dense, and match the ordering of the blocks within the function.  If a
296   /// specific MachineBasicBlock is specified, only that block and those after
297   /// it are renumbered.
298   void RenumberBlocks(MachineBasicBlock *MBBFrom = nullptr);
299
300   /// print - Print out the MachineFunction in a format suitable for debugging
301   /// to the specified stream.
302   ///
303   void print(raw_ostream &OS, SlotIndexes* = nullptr) const;
304
305   /// viewCFG - This function is meant for use from the debugger.  You can just
306   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
307   /// program, displaying the CFG of the current function with the code for each
308   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
309   /// in your path.
310   ///
311   void viewCFG() const;
312
313   /// viewCFGOnly - This function is meant for use from the debugger.  It works
314   /// just like viewCFG, but it does not include the contents of basic blocks
315   /// into the nodes, just the label.  If you are only interested in the CFG
316   /// this can make the graph smaller.
317   ///
318   void viewCFGOnly() const;
319
320   /// dump - Print the current MachineFunction to cerr, useful for debugger use.
321   ///
322   void dump() const;
323
324   /// verify - Run the current MachineFunction through the machine code
325   /// verifier, useful for debugger use.
326   void verify(Pass *p = nullptr, const char *Banner = nullptr) const;
327
328   // Provide accessors for the MachineBasicBlock list...
329   typedef BasicBlockListType::iterator iterator;
330   typedef BasicBlockListType::const_iterator const_iterator;
331   typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
332   typedef std::reverse_iterator<iterator>             reverse_iterator;
333
334   /// addLiveIn - Add the specified physical register as a live-in value and
335   /// create a corresponding virtual register for it.
336   unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC);
337
338   //===--------------------------------------------------------------------===//
339   // BasicBlock accessor functions.
340   //
341   iterator                 begin()       { return BasicBlocks.begin(); }
342   const_iterator           begin() const { return BasicBlocks.begin(); }
343   iterator                 end  ()       { return BasicBlocks.end();   }
344   const_iterator           end  () const { return BasicBlocks.end();   }
345
346   reverse_iterator        rbegin()       { return BasicBlocks.rbegin(); }
347   const_reverse_iterator  rbegin() const { return BasicBlocks.rbegin(); }
348   reverse_iterator        rend  ()       { return BasicBlocks.rend();   }
349   const_reverse_iterator  rend  () const { return BasicBlocks.rend();   }
350
351   unsigned                  size() const { return (unsigned)BasicBlocks.size();}
352   bool                     empty() const { return BasicBlocks.empty(); }
353   const MachineBasicBlock &front() const { return BasicBlocks.front(); }
354         MachineBasicBlock &front()       { return BasicBlocks.front(); }
355   const MachineBasicBlock & back() const { return BasicBlocks.back(); }
356         MachineBasicBlock & back()       { return BasicBlocks.back(); }
357
358   void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
359   void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
360   void insert(iterator MBBI, MachineBasicBlock *MBB) {
361     BasicBlocks.insert(MBBI, MBB);
362   }
363   void splice(iterator InsertPt, iterator MBBI) {
364     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
365   }
366   void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
367     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
368   }
369
370   void remove(iterator MBBI) {
371     BasicBlocks.remove(MBBI);
372   }
373   void erase(iterator MBBI) {
374     BasicBlocks.erase(MBBI);
375   }
376
377   template <typename Comp>
378   void sort(Comp comp) {
379     BasicBlocks.sort(comp);
380   }
381
382   //===--------------------------------------------------------------------===//
383   // Internal functions used to automatically number MachineBasicBlocks
384   //
385
386   /// \brief Adds the MBB to the internal numbering. Returns the unique number
387   /// assigned to the MBB.
388   ///
389   unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
390     MBBNumbering.push_back(MBB);
391     return (unsigned)MBBNumbering.size()-1;
392   }
393
394   /// removeFromMBBNumbering - Remove the specific machine basic block from our
395   /// tracker, this is only really to be used by the MachineBasicBlock
396   /// implementation.
397   void removeFromMBBNumbering(unsigned N) {
398     assert(N < MBBNumbering.size() && "Illegal basic block #");
399     MBBNumbering[N] = nullptr;
400   }
401
402   /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
403   /// of `new MachineInstr'.
404   ///
405   MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID,
406                                    DebugLoc DL,
407                                    bool NoImp = false);
408
409   /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
410   /// 'Orig' instruction, identical in all ways except the instruction
411   /// has no parent, prev, or next.
412   ///
413   /// See also TargetInstrInfo::duplicate() for target-specific fixes to cloned
414   /// instructions.
415   MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
416
417   /// DeleteMachineInstr - Delete the given MachineInstr.
418   ///
419   void DeleteMachineInstr(MachineInstr *MI);
420
421   /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
422   /// instead of `new MachineBasicBlock'.
423   ///
424   MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr);
425
426   /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
427   ///
428   void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
429
430   /// getMachineMemOperand - Allocate a new MachineMemOperand.
431   /// MachineMemOperands are owned by the MachineFunction and need not be
432   /// explicitly deallocated.
433   MachineMemOperand *getMachineMemOperand(MachinePointerInfo PtrInfo,
434                                           unsigned f, uint64_t s,
435                                           unsigned base_alignment,
436                                           const AAMDNodes &AAInfo = AAMDNodes(),
437                                           const MDNode *Ranges = nullptr);
438
439   /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
440   /// an existing one, adjusting by an offset and using the given size.
441   /// MachineMemOperands are owned by the MachineFunction and need not be
442   /// explicitly deallocated.
443   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
444                                           int64_t Offset, uint64_t Size);
445
446   typedef ArrayRecycler<MachineOperand>::Capacity OperandCapacity;
447
448   /// Allocate an array of MachineOperands. This is only intended for use by
449   /// internal MachineInstr functions.
450   MachineOperand *allocateOperandArray(OperandCapacity Cap) {
451     return OperandRecycler.allocate(Cap, Allocator);
452   }
453
454   /// Dellocate an array of MachineOperands and recycle the memory. This is
455   /// only intended for use by internal MachineInstr functions.
456   /// Cap must be the same capacity that was used to allocate the array.
457   void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) {
458     OperandRecycler.deallocate(Cap, Array);
459   }
460
461   /// \brief Allocate and initialize a register mask with @p NumRegister bits.
462   uint32_t *allocateRegisterMask(unsigned NumRegister) {
463     unsigned Size = (NumRegister + 31) / 32;
464     uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
465     for (unsigned i = 0; i != Size; ++i)
466       Mask[i] = 0;
467     return Mask;
468   }
469
470   /// allocateMemRefsArray - Allocate an array to hold MachineMemOperand
471   /// pointers.  This array is owned by the MachineFunction.
472   MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num);
473
474   /// extractLoadMemRefs - Allocate an array and populate it with just the
475   /// load information from the given MachineMemOperand sequence.
476   std::pair<MachineInstr::mmo_iterator,
477             MachineInstr::mmo_iterator>
478     extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
479                        MachineInstr::mmo_iterator End);
480
481   /// extractStoreMemRefs - Allocate an array and populate it with just the
482   /// store information from the given MachineMemOperand sequence.
483   std::pair<MachineInstr::mmo_iterator,
484             MachineInstr::mmo_iterator>
485     extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
486                         MachineInstr::mmo_iterator End);
487
488   /// Allocate a string and populate it with the given external symbol name.
489   const char *createExternalSymbolName(StringRef Name);
490
491   //===--------------------------------------------------------------------===//
492   // Label Manipulation.
493   //
494
495   /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
496   /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
497   /// normal 'L' label is returned.
498   MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx, 
499                          bool isLinkerPrivate = false) const;
500
501   /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
502   /// base.
503   MCSymbol *getPICBaseSymbol() const;
504 };
505
506 //===--------------------------------------------------------------------===//
507 // GraphTraits specializations for function basic block graphs (CFGs)
508 //===--------------------------------------------------------------------===//
509
510 // Provide specializations of GraphTraits to be able to treat a
511 // machine function as a graph of machine basic blocks... these are
512 // the same as the machine basic block iterators, except that the root
513 // node is implicitly the first node of the function.
514 //
515 template <> struct GraphTraits<MachineFunction*> :
516   public GraphTraits<MachineBasicBlock*> {
517   static NodeType *getEntryNode(MachineFunction *F) {
518     return &F->front();
519   }
520
521   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
522   typedef MachineFunction::iterator nodes_iterator;
523   static nodes_iterator nodes_begin(MachineFunction *F) { return F->begin(); }
524   static nodes_iterator nodes_end  (MachineFunction *F) { return F->end(); }
525   static unsigned       size       (MachineFunction *F) { return F->size(); }
526 };
527 template <> struct GraphTraits<const MachineFunction*> :
528   public GraphTraits<const MachineBasicBlock*> {
529   static NodeType *getEntryNode(const MachineFunction *F) {
530     return &F->front();
531   }
532
533   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
534   typedef MachineFunction::const_iterator nodes_iterator;
535   static nodes_iterator nodes_begin(const MachineFunction *F) {
536     return F->begin();
537   }
538   static nodes_iterator nodes_end  (const MachineFunction *F) {
539     return F->end();
540   }
541   static unsigned       size       (const MachineFunction *F)  {
542     return F->size();
543   }
544 };
545
546
547 // Provide specializations of GraphTraits to be able to treat a function as a
548 // graph of basic blocks... and to walk it in inverse order.  Inverse order for
549 // a function is considered to be when traversing the predecessor edges of a BB
550 // instead of the successor edges.
551 //
552 template <> struct GraphTraits<Inverse<MachineFunction*> > :
553   public GraphTraits<Inverse<MachineBasicBlock*> > {
554   static NodeType *getEntryNode(Inverse<MachineFunction*> G) {
555     return &G.Graph->front();
556   }
557 };
558 template <> struct GraphTraits<Inverse<const MachineFunction*> > :
559   public GraphTraits<Inverse<const MachineBasicBlock*> > {
560   static NodeType *getEntryNode(Inverse<const MachineFunction *> G) {
561     return &G.Graph->front();
562   }
563 };
564
565 } // End llvm namespace
566
567 #endif