d163c971d4bb85897a06e28d20fa447c5c1fde89
[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   /// Support for MachineBasicBlock::getNextNode().
335   static BasicBlockListType MachineFunction::*
336   getSublistAccess(MachineBasicBlock *) {
337     return &MachineFunction::BasicBlocks;
338   }
339
340   /// addLiveIn - Add the specified physical register as a live-in value and
341   /// create a corresponding virtual register for it.
342   unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC);
343
344   //===--------------------------------------------------------------------===//
345   // BasicBlock accessor functions.
346   //
347   iterator                 begin()       { return BasicBlocks.begin(); }
348   const_iterator           begin() const { return BasicBlocks.begin(); }
349   iterator                 end  ()       { return BasicBlocks.end();   }
350   const_iterator           end  () const { return BasicBlocks.end();   }
351
352   reverse_iterator        rbegin()       { return BasicBlocks.rbegin(); }
353   const_reverse_iterator  rbegin() const { return BasicBlocks.rbegin(); }
354   reverse_iterator        rend  ()       { return BasicBlocks.rend();   }
355   const_reverse_iterator  rend  () const { return BasicBlocks.rend();   }
356
357   unsigned                  size() const { return (unsigned)BasicBlocks.size();}
358   bool                     empty() const { return BasicBlocks.empty(); }
359   const MachineBasicBlock &front() const { return BasicBlocks.front(); }
360         MachineBasicBlock &front()       { return BasicBlocks.front(); }
361   const MachineBasicBlock & back() const { return BasicBlocks.back(); }
362         MachineBasicBlock & back()       { return BasicBlocks.back(); }
363
364   void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
365   void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
366   void insert(iterator MBBI, MachineBasicBlock *MBB) {
367     BasicBlocks.insert(MBBI, MBB);
368   }
369   void splice(iterator InsertPt, iterator MBBI) {
370     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
371   }
372   void splice(iterator InsertPt, MachineBasicBlock *MBB) {
373     BasicBlocks.splice(InsertPt, BasicBlocks, MBB);
374   }
375   void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
376     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
377   }
378
379   void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
380   void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
381   void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
382   void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
383
384   template <typename Comp>
385   void sort(Comp comp) {
386     BasicBlocks.sort(comp);
387   }
388
389   //===--------------------------------------------------------------------===//
390   // Internal functions used to automatically number MachineBasicBlocks
391   //
392
393   /// \brief Adds the MBB to the internal numbering. Returns the unique number
394   /// assigned to the MBB.
395   ///
396   unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
397     MBBNumbering.push_back(MBB);
398     return (unsigned)MBBNumbering.size()-1;
399   }
400
401   /// removeFromMBBNumbering - Remove the specific machine basic block from our
402   /// tracker, this is only really to be used by the MachineBasicBlock
403   /// implementation.
404   void removeFromMBBNumbering(unsigned N) {
405     assert(N < MBBNumbering.size() && "Illegal basic block #");
406     MBBNumbering[N] = nullptr;
407   }
408
409   /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
410   /// of `new MachineInstr'.
411   ///
412   MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID,
413                                    DebugLoc DL,
414                                    bool NoImp = false);
415
416   /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
417   /// 'Orig' instruction, identical in all ways except the instruction
418   /// has no parent, prev, or next.
419   ///
420   /// See also TargetInstrInfo::duplicate() for target-specific fixes to cloned
421   /// instructions.
422   MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
423
424   /// DeleteMachineInstr - Delete the given MachineInstr.
425   ///
426   void DeleteMachineInstr(MachineInstr *MI);
427
428   /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
429   /// instead of `new MachineBasicBlock'.
430   ///
431   MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr);
432
433   /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
434   ///
435   void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
436
437   /// getMachineMemOperand - Allocate a new MachineMemOperand.
438   /// MachineMemOperands are owned by the MachineFunction and need not be
439   /// explicitly deallocated.
440   MachineMemOperand *getMachineMemOperand(MachinePointerInfo PtrInfo,
441                                           unsigned f, uint64_t s,
442                                           unsigned base_alignment,
443                                           const AAMDNodes &AAInfo = AAMDNodes(),
444                                           const MDNode *Ranges = nullptr);
445
446   /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
447   /// an existing one, adjusting by an offset and using the given size.
448   /// MachineMemOperands are owned by the MachineFunction and need not be
449   /// explicitly deallocated.
450   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
451                                           int64_t Offset, uint64_t Size);
452
453   typedef ArrayRecycler<MachineOperand>::Capacity OperandCapacity;
454
455   /// Allocate an array of MachineOperands. This is only intended for use by
456   /// internal MachineInstr functions.
457   MachineOperand *allocateOperandArray(OperandCapacity Cap) {
458     return OperandRecycler.allocate(Cap, Allocator);
459   }
460
461   /// Dellocate an array of MachineOperands and recycle the memory. This is
462   /// only intended for use by internal MachineInstr functions.
463   /// Cap must be the same capacity that was used to allocate the array.
464   void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) {
465     OperandRecycler.deallocate(Cap, Array);
466   }
467
468   /// \brief Allocate and initialize a register mask with @p NumRegister bits.
469   uint32_t *allocateRegisterMask(unsigned NumRegister) {
470     unsigned Size = (NumRegister + 31) / 32;
471     uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
472     for (unsigned i = 0; i != Size; ++i)
473       Mask[i] = 0;
474     return Mask;
475   }
476
477   /// allocateMemRefsArray - Allocate an array to hold MachineMemOperand
478   /// pointers.  This array is owned by the MachineFunction.
479   MachineInstr::mmo_iterator allocateMemRefsArray(unsigned long Num);
480
481   /// extractLoadMemRefs - Allocate an array and populate it with just the
482   /// load information from the given MachineMemOperand sequence.
483   std::pair<MachineInstr::mmo_iterator,
484             MachineInstr::mmo_iterator>
485     extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
486                        MachineInstr::mmo_iterator End);
487
488   /// extractStoreMemRefs - Allocate an array and populate it with just the
489   /// store information from the given MachineMemOperand sequence.
490   std::pair<MachineInstr::mmo_iterator,
491             MachineInstr::mmo_iterator>
492     extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
493                         MachineInstr::mmo_iterator End);
494
495   /// Allocate a string and populate it with the given external symbol name.
496   const char *createExternalSymbolName(StringRef Name);
497
498   //===--------------------------------------------------------------------===//
499   // Label Manipulation.
500   //
501
502   /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
503   /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
504   /// normal 'L' label is returned.
505   MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
506                          bool isLinkerPrivate = false) const;
507
508   /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
509   /// base.
510   MCSymbol *getPICBaseSymbol() const;
511 };
512
513 //===--------------------------------------------------------------------===//
514 // GraphTraits specializations for function basic block graphs (CFGs)
515 //===--------------------------------------------------------------------===//
516
517 // Provide specializations of GraphTraits to be able to treat a
518 // machine function as a graph of machine basic blocks... these are
519 // the same as the machine basic block iterators, except that the root
520 // node is implicitly the first node of the function.
521 //
522 template <> struct GraphTraits<MachineFunction*> :
523   public GraphTraits<MachineBasicBlock*> {
524   static NodeType *getEntryNode(MachineFunction *F) {
525     return &F->front();
526   }
527
528   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
529   typedef MachineFunction::iterator nodes_iterator;
530   static nodes_iterator nodes_begin(MachineFunction *F) { return F->begin(); }
531   static nodes_iterator nodes_end  (MachineFunction *F) { return F->end(); }
532   static unsigned       size       (MachineFunction *F) { return F->size(); }
533 };
534 template <> struct GraphTraits<const MachineFunction*> :
535   public GraphTraits<const MachineBasicBlock*> {
536   static NodeType *getEntryNode(const MachineFunction *F) {
537     return &F->front();
538   }
539
540   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
541   typedef MachineFunction::const_iterator nodes_iterator;
542   static nodes_iterator nodes_begin(const MachineFunction *F) {
543     return F->begin();
544   }
545   static nodes_iterator nodes_end  (const MachineFunction *F) {
546     return F->end();
547   }
548   static unsigned       size       (const MachineFunction *F)  {
549     return F->size();
550   }
551 };
552
553
554 // Provide specializations of GraphTraits to be able to treat a function as a
555 // graph of basic blocks... and to walk it in inverse order.  Inverse order for
556 // a function is considered to be when traversing the predecessor edges of a BB
557 // instead of the successor edges.
558 //
559 template <> struct GraphTraits<Inverse<MachineFunction*> > :
560   public GraphTraits<Inverse<MachineBasicBlock*> > {
561   static NodeType *getEntryNode(Inverse<MachineFunction*> G) {
562     return &G.Graph->front();
563   }
564 };
565 template <> struct GraphTraits<Inverse<const MachineFunction*> > :
566   public GraphTraits<Inverse<const MachineBasicBlock*> > {
567   static NodeType *getEntryNode(Inverse<const MachineFunction *> G) {
568     return &G.Graph->front();
569   }
570 };
571
572 } // End llvm namespace
573
574 #endif