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