blob: 7471b31484644e47c76b316f2826b5563070dbe2 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- 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/ArrayRef.h"
22#include "llvm/ADT/BitVector.h"
23#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/GraphTraits.h"
25#include "llvm/ADT/Optional.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/ilist.h"
29#include "llvm/ADT/iterator.h"
30#include "llvm/Analysis/EHPersonalities.h"
31#include "llvm/CodeGen/MachineBasicBlock.h"
32#include "llvm/CodeGen/MachineInstr.h"
33#include "llvm/CodeGen/MachineMemOperand.h"
34#include "llvm/IR/DebugLoc.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Metadata.h"
37#include "llvm/MC/MCDwarf.h"
38#include "llvm/MC/MCSymbol.h"
39#include "llvm/Support/Allocator.h"
40#include "llvm/Support/ArrayRecycler.h"
41#include "llvm/Support/AtomicOrdering.h"
42#include "llvm/Support/Compiler.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/Recycler.h"
45#include <cassert>
46#include <cstdint>
47#include <memory>
48#include <utility>
49#include <vector>
50
51namespace llvm {
52
53class BasicBlock;
54class BlockAddress;
55class DataLayout;
56class DIExpression;
57class DILocalVariable;
58class DILocation;
59class Function;
60class GlobalValue;
61class MachineConstantPool;
62class MachineFrameInfo;
63class MachineFunction;
64class MachineJumpTableInfo;
65class MachineModuleInfo;
66class MachineRegisterInfo;
67class MCContext;
68class MCInstrDesc;
69class Pass;
70class PseudoSourceValueManager;
71class raw_ostream;
72class SlotIndexes;
73class TargetMachine;
74class TargetRegisterClass;
75class TargetSubtargetInfo;
Andrew Scullcdfcccc2018-10-05 20:58:37 +010076struct WasmEHFuncInfo;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010077struct WinEHFuncInfo;
78
79template <> struct ilist_alloc_traits<MachineBasicBlock> {
80 void deleteNode(MachineBasicBlock *MBB);
81};
82
83template <> struct ilist_callback_traits<MachineBasicBlock> {
Andrew Scullcdfcccc2018-10-05 20:58:37 +010084 void addNodeToList(MachineBasicBlock* N);
85 void removeNodeFromList(MachineBasicBlock* N);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010086
87 template <class Iterator>
88 void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator) {
89 llvm_unreachable("Never transfer between lists");
90 }
91};
92
93/// MachineFunctionInfo - This class can be derived from and used by targets to
94/// hold private target-specific information for each MachineFunction. Objects
95/// of type are accessed/created with MF::getInfo and destroyed when the
96/// MachineFunction is destroyed.
97struct MachineFunctionInfo {
98 virtual ~MachineFunctionInfo();
99
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100100 /// Factory function: default behavior is to call new using the
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100101 /// supplied allocator.
102 ///
103 /// This function can be overridden in a derive class.
104 template<typename Ty>
105 static Ty *create(BumpPtrAllocator &Allocator, MachineFunction &MF) {
106 return new (Allocator.Allocate<Ty>()) Ty(MF);
107 }
108};
109
110/// Properties which a MachineFunction may have at a given point in time.
111/// Each of these has checking code in the MachineVerifier, and passes can
112/// require that a property be set.
113class MachineFunctionProperties {
114 // Possible TODO: Allow targets to extend this (perhaps by allowing the
115 // constructor to specify the size of the bit vector)
116 // Possible TODO: Allow requiring the negative (e.g. VRegsAllocated could be
117 // stated as the negative of "has vregs"
118
119public:
120 // The properties are stated in "positive" form; i.e. a pass could require
121 // that the property hold, but not that it does not hold.
122
123 // Property descriptions:
124 // IsSSA: True when the machine function is in SSA form and virtual registers
125 // have a single def.
126 // NoPHIs: The machine function does not contain any PHI instruction.
127 // TracksLiveness: True when tracking register liveness accurately.
128 // While this property is set, register liveness information in basic block
129 // live-in lists and machine instruction operands (e.g. kill flags, implicit
130 // defs) is accurate. This means it can be used to change the code in ways
131 // that affect the values in registers, for example by the register
132 // scavenger.
133 // When this property is clear, liveness is no longer reliable.
134 // NoVRegs: The machine function does not use any virtual registers.
135 // Legalized: In GlobalISel: the MachineLegalizer ran and all pre-isel generic
136 // instructions have been legalized; i.e., all instructions are now one of:
137 // - generic and always legal (e.g., COPY)
138 // - target-specific
139 // - legal pre-isel generic instructions.
140 // RegBankSelected: In GlobalISel: the RegBankSelect pass ran and all generic
141 // virtual registers have been assigned to a register bank.
142 // Selected: In GlobalISel: the InstructionSelect pass ran and all pre-isel
143 // generic instructions have been eliminated; i.e., all instructions are now
144 // target-specific or non-pre-isel generic instructions (e.g., COPY).
145 // Since only pre-isel generic instructions can have generic virtual register
146 // operands, this also means that all generic virtual registers have been
147 // constrained to virtual registers (assigned to register classes) and that
148 // all sizes attached to them have been eliminated.
149 enum class Property : unsigned {
150 IsSSA,
151 NoPHIs,
152 TracksLiveness,
153 NoVRegs,
154 FailedISel,
155 Legalized,
156 RegBankSelected,
157 Selected,
158 LastProperty = Selected,
159 };
160
161 bool hasProperty(Property P) const {
162 return Properties[static_cast<unsigned>(P)];
163 }
164
165 MachineFunctionProperties &set(Property P) {
166 Properties.set(static_cast<unsigned>(P));
167 return *this;
168 }
169
170 MachineFunctionProperties &reset(Property P) {
171 Properties.reset(static_cast<unsigned>(P));
172 return *this;
173 }
174
175 /// Reset all the properties.
176 MachineFunctionProperties &reset() {
177 Properties.reset();
178 return *this;
179 }
180
181 MachineFunctionProperties &set(const MachineFunctionProperties &MFP) {
182 Properties |= MFP.Properties;
183 return *this;
184 }
185
186 MachineFunctionProperties &reset(const MachineFunctionProperties &MFP) {
187 Properties.reset(MFP.Properties);
188 return *this;
189 }
190
191 // Returns true if all properties set in V (i.e. required by a pass) are set
192 // in this.
193 bool verifyRequiredProperties(const MachineFunctionProperties &V) const {
194 return !V.Properties.test(Properties);
195 }
196
197 /// Print the MachineFunctionProperties in human-readable form.
198 void print(raw_ostream &OS) const;
199
200private:
201 BitVector Properties =
202 BitVector(static_cast<unsigned>(Property::LastProperty)+1);
203};
204
205struct SEHHandler {
206 /// Filter or finally function. Null indicates a catch-all.
207 const Function *FilterOrFinally;
208
209 /// Address of block to recover at. Null for a finally handler.
210 const BlockAddress *RecoverBA;
211};
212
213/// This structure is used to retain landing pad info for the current function.
214struct LandingPadInfo {
215 MachineBasicBlock *LandingPadBlock; // Landing pad block.
216 SmallVector<MCSymbol *, 1> BeginLabels; // Labels prior to invoke.
217 SmallVector<MCSymbol *, 1> EndLabels; // Labels after invoke.
218 SmallVector<SEHHandler, 1> SEHHandlers; // SEH handlers active at this lpad.
219 MCSymbol *LandingPadLabel = nullptr; // Label at beginning of landing pad.
220 std::vector<int> TypeIds; // List of type ids (filters negative).
221
222 explicit LandingPadInfo(MachineBasicBlock *MBB)
223 : LandingPadBlock(MBB) {}
224};
225
226class MachineFunction {
227 const Function &F;
228 const TargetMachine &Target;
229 const TargetSubtargetInfo *STI;
230 MCContext &Ctx;
231 MachineModuleInfo &MMI;
232
233 // RegInfo - Information about each register in use in the function.
234 MachineRegisterInfo *RegInfo;
235
236 // Used to keep track of target-specific per-machine function information for
237 // the target implementation.
238 MachineFunctionInfo *MFInfo;
239
240 // Keep track of objects allocated on the stack.
241 MachineFrameInfo *FrameInfo;
242
243 // Keep track of constants which are spilled to memory
244 MachineConstantPool *ConstantPool;
245
246 // Keep track of jump tables for switch instructions
247 MachineJumpTableInfo *JumpTableInfo;
248
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100249 // Keeps track of Wasm exception handling related data. This will be null for
250 // functions that aren't using a wasm EH personality.
251 WasmEHFuncInfo *WasmEHInfo = nullptr;
252
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100253 // Keeps track of Windows exception handling related data. This will be null
254 // for functions that aren't using a funclet-based EH personality.
255 WinEHFuncInfo *WinEHInfo = nullptr;
256
257 // Function-level unique numbering for MachineBasicBlocks. When a
258 // MachineBasicBlock is inserted into a MachineFunction is it automatically
259 // numbered and this vector keeps track of the mapping from ID's to MBB's.
260 std::vector<MachineBasicBlock*> MBBNumbering;
261
262 // Pool-allocate MachineFunction-lifetime and IR objects.
263 BumpPtrAllocator Allocator;
264
265 // Allocation management for instructions in function.
266 Recycler<MachineInstr> InstructionRecycler;
267
268 // Allocation management for operand arrays on instructions.
269 ArrayRecycler<MachineOperand> OperandRecycler;
270
271 // Allocation management for basic blocks in function.
272 Recycler<MachineBasicBlock> BasicBlockRecycler;
273
274 // List of machine basic blocks in function
275 using BasicBlockListType = ilist<MachineBasicBlock>;
276 BasicBlockListType BasicBlocks;
277
278 /// FunctionNumber - This provides a unique ID for each function emitted in
279 /// this translation unit.
280 ///
281 unsigned FunctionNumber;
282
283 /// Alignment - The alignment of the function.
284 unsigned Alignment;
285
286 /// ExposesReturnsTwice - True if the function calls setjmp or related
287 /// functions with attribute "returns twice", but doesn't have
288 /// the attribute itself.
289 /// This is used to limit optimizations which cannot reason
290 /// about the control flow of such functions.
291 bool ExposesReturnsTwice = false;
292
293 /// True if the function includes any inline assembly.
294 bool HasInlineAsm = false;
295
296 /// True if any WinCFI instruction have been emitted in this function.
Andrew Scull0372a572018-11-16 15:47:06 +0000297 bool HasWinCFI = false;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100298
299 /// Current high-level properties of the IR of the function (e.g. is in SSA
300 /// form or whether registers have been allocated)
301 MachineFunctionProperties Properties;
302
303 // Allocation management for pseudo source values.
304 std::unique_ptr<PseudoSourceValueManager> PSVManager;
305
306 /// List of moves done by a function's prolog. Used to construct frame maps
307 /// by debug and exception handling consumers.
308 std::vector<MCCFIInstruction> FrameInstructions;
309
310 /// \name Exception Handling
311 /// \{
312
313 /// List of LandingPadInfo describing the landing pad information.
314 std::vector<LandingPadInfo> LandingPads;
315
316 /// Map a landing pad's EH symbol to the call site indexes.
317 DenseMap<MCSymbol*, SmallVector<unsigned, 4>> LPadToCallSiteMap;
318
319 /// Map of invoke call site index values to associated begin EH_LABEL.
320 DenseMap<MCSymbol*, unsigned> CallSiteMap;
321
322 /// CodeView label annotations.
323 std::vector<std::pair<MCSymbol *, MDNode *>> CodeViewAnnotations;
324
325 bool CallsEHReturn = false;
326 bool CallsUnwindInit = false;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100327 bool HasEHScopes = false;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100328 bool HasEHFunclets = false;
329
330 /// List of C++ TypeInfo used.
331 std::vector<const GlobalValue *> TypeInfos;
332
333 /// List of typeids encoding filters used.
334 std::vector<unsigned> FilterIds;
335
336 /// List of the indices in FilterIds corresponding to filter terminators.
337 std::vector<unsigned> FilterEnds;
338
339 EHPersonality PersonalityTypeCache = EHPersonality::Unknown;
340
341 /// \}
342
343 /// Clear all the members of this MachineFunction, but the ones used
344 /// to initialize again the MachineFunction.
345 /// More specifically, this deallocates all the dynamically allocated
346 /// objects and get rid of all the XXXInfo data structure, but keep
347 /// unchanged the references to Fn, Target, MMI, and FunctionNumber.
348 void clear();
349 /// Allocate and initialize the different members.
350 /// In particular, the XXXInfo data structure.
351 /// \pre Fn, Target, MMI, and FunctionNumber are properly set.
352 void init();
353
354public:
355 struct VariableDbgInfo {
356 const DILocalVariable *Var;
357 const DIExpression *Expr;
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100358 // The Slot can be negative for fixed stack objects.
359 int Slot;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100360 const DILocation *Loc;
361
362 VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100363 int Slot, const DILocation *Loc)
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100364 : Var(Var), Expr(Expr), Slot(Slot), Loc(Loc) {}
365 };
Andrew Scull0372a572018-11-16 15:47:06 +0000366
367 class Delegate {
368 virtual void anchor();
369
370 public:
371 virtual ~Delegate() = default;
372 virtual void MF_HandleInsertion(const MachineInstr &MI) = 0;
373 virtual void MF_HandleRemoval(const MachineInstr &MI) = 0;
374 };
375
376private:
377 Delegate *TheDelegate = nullptr;
378
379 // Callbacks for insertion and removal.
380 void handleInsertion(const MachineInstr &MI);
381 void handleRemoval(const MachineInstr &MI);
382 friend struct ilist_traits<MachineInstr>;
383
384public:
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100385 using VariableDbgInfoMapTy = SmallVector<VariableDbgInfo, 4>;
386 VariableDbgInfoMapTy VariableDbgInfos;
387
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100388 MachineFunction(const Function &F, const TargetMachine &Target,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100389 const TargetSubtargetInfo &STI, unsigned FunctionNum,
390 MachineModuleInfo &MMI);
391 MachineFunction(const MachineFunction &) = delete;
392 MachineFunction &operator=(const MachineFunction &) = delete;
393 ~MachineFunction();
394
395 /// Reset the instance as if it was just created.
396 void reset() {
397 clear();
398 init();
399 }
400
Andrew Scull0372a572018-11-16 15:47:06 +0000401 /// Reset the currently registered delegate - otherwise assert.
402 void resetDelegate(Delegate *delegate) {
403 assert(TheDelegate == delegate &&
404 "Only the current delegate can perform reset!");
405 TheDelegate = nullptr;
406 }
407
408 /// Set the delegate. resetDelegate must be called before attempting
409 /// to set.
410 void setDelegate(Delegate *delegate) {
411 assert(delegate && !TheDelegate &&
412 "Attempted to set delegate to null, or to change it without "
413 "first resetting it!");
414
415 TheDelegate = delegate;
416 }
417
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100418 MachineModuleInfo &getMMI() const { return MMI; }
419 MCContext &getContext() const { return Ctx; }
420
421 PseudoSourceValueManager &getPSVManager() const { return *PSVManager; }
422
423 /// Return the DataLayout attached to the Module associated to this MF.
424 const DataLayout &getDataLayout() const;
425
426 /// Return the LLVM function that this machine code represents
427 const Function &getFunction() const { return F; }
428
429 /// getName - Return the name of the corresponding LLVM function.
430 StringRef getName() const;
431
432 /// getFunctionNumber - Return a unique ID for the current function.
433 unsigned getFunctionNumber() const { return FunctionNumber; }
434
435 /// getTarget - Return the target machine this machine code is compiled with
436 const TargetMachine &getTarget() const { return Target; }
437
438 /// getSubtarget - Return the subtarget for which this machine code is being
439 /// compiled.
440 const TargetSubtargetInfo &getSubtarget() const { return *STI; }
441 void setSubtarget(const TargetSubtargetInfo *ST) { STI = ST; }
442
443 /// getSubtarget - This method returns a pointer to the specified type of
444 /// TargetSubtargetInfo. In debug builds, it verifies that the object being
445 /// returned is of the correct type.
446 template<typename STC> const STC &getSubtarget() const {
447 return *static_cast<const STC *>(STI);
448 }
449
450 /// getRegInfo - Return information about the registers currently in use.
451 MachineRegisterInfo &getRegInfo() { return *RegInfo; }
452 const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
453
454 /// getFrameInfo - Return the frame info object for the current function.
455 /// This object contains information about objects allocated on the stack
456 /// frame of the current function in an abstract way.
457 MachineFrameInfo &getFrameInfo() { return *FrameInfo; }
458 const MachineFrameInfo &getFrameInfo() const { return *FrameInfo; }
459
460 /// getJumpTableInfo - Return the jump table info object for the current
461 /// function. This object contains information about jump tables in the
462 /// current function. If the current function has no jump tables, this will
463 /// return null.
464 const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
465 MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
466
467 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
468 /// does already exist, allocate one.
469 MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
470
471 /// getConstantPool - Return the constant pool object for the current
472 /// function.
473 MachineConstantPool *getConstantPool() { return ConstantPool; }
474 const MachineConstantPool *getConstantPool() const { return ConstantPool; }
475
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100476 /// getWasmEHFuncInfo - Return information about how the current function uses
477 /// Wasm exception handling. Returns null for functions that don't use wasm
478 /// exception handling.
479 const WasmEHFuncInfo *getWasmEHFuncInfo() const { return WasmEHInfo; }
480 WasmEHFuncInfo *getWasmEHFuncInfo() { return WasmEHInfo; }
481
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100482 /// getWinEHFuncInfo - Return information about how the current function uses
483 /// Windows exception handling. Returns null for functions that don't use
484 /// funclets for exception handling.
485 const WinEHFuncInfo *getWinEHFuncInfo() const { return WinEHInfo; }
486 WinEHFuncInfo *getWinEHFuncInfo() { return WinEHInfo; }
487
488 /// getAlignment - Return the alignment (log2, not bytes) of the function.
489 unsigned getAlignment() const { return Alignment; }
490
491 /// setAlignment - Set the alignment (log2, not bytes) of the function.
492 void setAlignment(unsigned A) { Alignment = A; }
493
494 /// ensureAlignment - Make sure the function is at least 1 << A bytes aligned.
495 void ensureAlignment(unsigned A) {
496 if (Alignment < A) Alignment = A;
497 }
498
499 /// exposesReturnsTwice - Returns true if the function calls setjmp or
500 /// any other similar functions with attribute "returns twice" without
501 /// having the attribute itself.
502 bool exposesReturnsTwice() const {
503 return ExposesReturnsTwice;
504 }
505
506 /// setCallsSetJmp - Set a flag that indicates if there's a call to
507 /// a "returns twice" function.
508 void setExposesReturnsTwice(bool B) {
509 ExposesReturnsTwice = B;
510 }
511
512 /// Returns true if the function contains any inline assembly.
513 bool hasInlineAsm() const {
514 return HasInlineAsm;
515 }
516
517 /// Set a flag that indicates that the function contains inline assembly.
518 void setHasInlineAsm(bool B) {
519 HasInlineAsm = B;
520 }
521
522 bool hasWinCFI() const {
Andrew Scull0372a572018-11-16 15:47:06 +0000523 return HasWinCFI;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100524 }
525 void setHasWinCFI(bool v) { HasWinCFI = v; }
526
527 /// Get the function properties
528 const MachineFunctionProperties &getProperties() const { return Properties; }
529 MachineFunctionProperties &getProperties() { return Properties; }
530
531 /// getInfo - Keep track of various per-function pieces of information for
532 /// backends that would like to do so.
533 ///
534 template<typename Ty>
535 Ty *getInfo() {
536 if (!MFInfo)
537 MFInfo = Ty::template create<Ty>(Allocator, *this);
538 return static_cast<Ty*>(MFInfo);
539 }
540
541 template<typename Ty>
542 const Ty *getInfo() const {
543 return const_cast<MachineFunction*>(this)->getInfo<Ty>();
544 }
545
546 /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
547 /// are inserted into the machine function. The block number for a machine
548 /// basic block can be found by using the MBB::getNumber method, this method
549 /// provides the inverse mapping.
550 MachineBasicBlock *getBlockNumbered(unsigned N) const {
551 assert(N < MBBNumbering.size() && "Illegal block number");
552 assert(MBBNumbering[N] && "Block was removed from the machine function!");
553 return MBBNumbering[N];
554 }
555
556 /// Should we be emitting segmented stack stuff for the function
557 bool shouldSplitStack() const;
558
559 /// getNumBlockIDs - Return the number of MBB ID's allocated.
560 unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
561
562 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
563 /// recomputes them. This guarantees that the MBB numbers are sequential,
564 /// dense, and match the ordering of the blocks within the function. If a
565 /// specific MachineBasicBlock is specified, only that block and those after
566 /// it are renumbered.
567 void RenumberBlocks(MachineBasicBlock *MBBFrom = nullptr);
568
569 /// print - Print out the MachineFunction in a format suitable for debugging
570 /// to the specified stream.
571 void print(raw_ostream &OS, const SlotIndexes* = nullptr) const;
572
573 /// viewCFG - This function is meant for use from the debugger. You can just
574 /// say 'call F->viewCFG()' and a ghostview window should pop up from the
575 /// program, displaying the CFG of the current function with the code for each
576 /// basic block inside. This depends on there being a 'dot' and 'gv' program
577 /// in your path.
578 void viewCFG() const;
579
580 /// viewCFGOnly - This function is meant for use from the debugger. It works
581 /// just like viewCFG, but it does not include the contents of basic blocks
582 /// into the nodes, just the label. If you are only interested in the CFG
583 /// this can make the graph smaller.
584 ///
585 void viewCFGOnly() const;
586
587 /// dump - Print the current MachineFunction to cerr, useful for debugger use.
588 void dump() const;
589
590 /// Run the current MachineFunction through the machine code verifier, useful
591 /// for debugger use.
592 /// \returns true if no problems were found.
593 bool verify(Pass *p = nullptr, const char *Banner = nullptr,
594 bool AbortOnError = true) const;
595
596 // Provide accessors for the MachineBasicBlock list...
597 using iterator = BasicBlockListType::iterator;
598 using const_iterator = BasicBlockListType::const_iterator;
599 using const_reverse_iterator = BasicBlockListType::const_reverse_iterator;
600 using reverse_iterator = BasicBlockListType::reverse_iterator;
601
602 /// Support for MachineBasicBlock::getNextNode().
603 static BasicBlockListType MachineFunction::*
604 getSublistAccess(MachineBasicBlock *) {
605 return &MachineFunction::BasicBlocks;
606 }
607
608 /// addLiveIn - Add the specified physical register as a live-in value and
609 /// create a corresponding virtual register for it.
610 unsigned addLiveIn(unsigned PReg, const TargetRegisterClass *RC);
611
612 //===--------------------------------------------------------------------===//
613 // BasicBlock accessor functions.
614 //
615 iterator begin() { return BasicBlocks.begin(); }
616 const_iterator begin() const { return BasicBlocks.begin(); }
617 iterator end () { return BasicBlocks.end(); }
618 const_iterator end () const { return BasicBlocks.end(); }
619
620 reverse_iterator rbegin() { return BasicBlocks.rbegin(); }
621 const_reverse_iterator rbegin() const { return BasicBlocks.rbegin(); }
622 reverse_iterator rend () { return BasicBlocks.rend(); }
623 const_reverse_iterator rend () const { return BasicBlocks.rend(); }
624
625 unsigned size() const { return (unsigned)BasicBlocks.size();}
626 bool empty() const { return BasicBlocks.empty(); }
627 const MachineBasicBlock &front() const { return BasicBlocks.front(); }
628 MachineBasicBlock &front() { return BasicBlocks.front(); }
629 const MachineBasicBlock & back() const { return BasicBlocks.back(); }
630 MachineBasicBlock & back() { return BasicBlocks.back(); }
631
632 void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
633 void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
634 void insert(iterator MBBI, MachineBasicBlock *MBB) {
635 BasicBlocks.insert(MBBI, MBB);
636 }
637 void splice(iterator InsertPt, iterator MBBI) {
638 BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
639 }
640 void splice(iterator InsertPt, MachineBasicBlock *MBB) {
641 BasicBlocks.splice(InsertPt, BasicBlocks, MBB);
642 }
643 void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
644 BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
645 }
646
647 void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
648 void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
649 void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
650 void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
651
652 template <typename Comp>
653 void sort(Comp comp) {
654 BasicBlocks.sort(comp);
655 }
656
Andrew Scull0372a572018-11-16 15:47:06 +0000657 /// Return the number of \p MachineInstrs in this \p MachineFunction.
658 unsigned getInstructionCount() const {
659 unsigned InstrCount = 0;
660 for (const MachineBasicBlock &MBB : BasicBlocks)
661 InstrCount += MBB.size();
662 return InstrCount;
663 }
664
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100665 //===--------------------------------------------------------------------===//
666 // Internal functions used to automatically number MachineBasicBlocks
667
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100668 /// Adds the MBB to the internal numbering. Returns the unique number
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100669 /// assigned to the MBB.
670 unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
671 MBBNumbering.push_back(MBB);
672 return (unsigned)MBBNumbering.size()-1;
673 }
674
675 /// removeFromMBBNumbering - Remove the specific machine basic block from our
676 /// tracker, this is only really to be used by the MachineBasicBlock
677 /// implementation.
678 void removeFromMBBNumbering(unsigned N) {
679 assert(N < MBBNumbering.size() && "Illegal basic block #");
680 MBBNumbering[N] = nullptr;
681 }
682
683 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
684 /// of `new MachineInstr'.
685 MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID, const DebugLoc &DL,
686 bool NoImp = false);
687
688 /// Create a new MachineInstr which is a copy of \p Orig, identical in all
689 /// ways except the instruction has no parent, prev, or next. Bundling flags
690 /// are reset.
691 ///
692 /// Note: Clones a single instruction, not whole instruction bundles.
693 /// Does not perform target specific adjustments; consider using
694 /// TargetInstrInfo::duplicate() instead.
695 MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
696
697 /// Clones instruction or the whole instruction bundle \p Orig and insert
698 /// into \p MBB before \p InsertBefore.
699 ///
700 /// Note: Does not perform target specific adjustments; consider using
701 /// TargetInstrInfo::duplicate() intead.
702 MachineInstr &CloneMachineInstrBundle(MachineBasicBlock &MBB,
703 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig);
704
705 /// DeleteMachineInstr - Delete the given MachineInstr.
706 void DeleteMachineInstr(MachineInstr *MI);
707
708 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
709 /// instead of `new MachineBasicBlock'.
710 MachineBasicBlock *CreateMachineBasicBlock(const BasicBlock *bb = nullptr);
711
712 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
713 void DeleteMachineBasicBlock(MachineBasicBlock *MBB);
714
715 /// getMachineMemOperand - Allocate a new MachineMemOperand.
716 /// MachineMemOperands are owned by the MachineFunction and need not be
717 /// explicitly deallocated.
718 MachineMemOperand *getMachineMemOperand(
719 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
720 unsigned base_alignment, const AAMDNodes &AAInfo = AAMDNodes(),
721 const MDNode *Ranges = nullptr,
722 SyncScope::ID SSID = SyncScope::System,
723 AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
724 AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
725
726 /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
727 /// an existing one, adjusting by an offset and using the given size.
728 /// MachineMemOperands are owned by the MachineFunction and need not be
729 /// explicitly deallocated.
730 MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
731 int64_t Offset, uint64_t Size);
732
733 /// Allocate a new MachineMemOperand by copying an existing one,
734 /// replacing only AliasAnalysis information. MachineMemOperands are owned
735 /// by the MachineFunction and need not be explicitly deallocated.
736 MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
737 const AAMDNodes &AAInfo);
738
739 using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
740
741 /// Allocate an array of MachineOperands. This is only intended for use by
742 /// internal MachineInstr functions.
743 MachineOperand *allocateOperandArray(OperandCapacity Cap) {
744 return OperandRecycler.allocate(Cap, Allocator);
745 }
746
747 /// Dellocate an array of MachineOperands and recycle the memory. This is
748 /// only intended for use by internal MachineInstr functions.
749 /// Cap must be the same capacity that was used to allocate the array.
750 void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) {
751 OperandRecycler.deallocate(Cap, Array);
752 }
753
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100754 /// Allocate and initialize a register mask with @p NumRegister bits.
755 uint32_t *allocateRegMask();
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100756
Andrew Scull0372a572018-11-16 15:47:06 +0000757 /// Allocate and construct an extra info structure for a `MachineInstr`.
758 ///
759 /// This is allocated on the function's allocator and so lives the life of
760 /// the function.
761 MachineInstr::ExtraInfo *
762 createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
763 MCSymbol *PreInstrSymbol = nullptr,
764 MCSymbol *PostInstrSymbol = nullptr);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100765
766 /// Allocate a string and populate it with the given external symbol name.
767 const char *createExternalSymbolName(StringRef Name);
768
769 //===--------------------------------------------------------------------===//
770 // Label Manipulation.
771
772 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
773 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
774 /// normal 'L' label is returned.
775 MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
776 bool isLinkerPrivate = false) const;
777
778 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
779 /// base.
780 MCSymbol *getPICBaseSymbol() const;
781
782 /// Returns a reference to a list of cfi instructions in the function's
783 /// prologue. Used to construct frame maps for debug and exception handling
784 /// comsumers.
785 const std::vector<MCCFIInstruction> &getFrameInstructions() const {
786 return FrameInstructions;
787 }
788
789 LLVM_NODISCARD unsigned addFrameInst(const MCCFIInstruction &Inst) {
790 FrameInstructions.push_back(Inst);
791 return FrameInstructions.size() - 1;
792 }
793
794 /// \name Exception Handling
795 /// \{
796
797 bool callsEHReturn() const { return CallsEHReturn; }
798 void setCallsEHReturn(bool b) { CallsEHReturn = b; }
799
800 bool callsUnwindInit() const { return CallsUnwindInit; }
801 void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
802
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100803 bool hasEHScopes() const { return HasEHScopes; }
804 void setHasEHScopes(bool V) { HasEHScopes = V; }
805
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100806 bool hasEHFunclets() const { return HasEHFunclets; }
807 void setHasEHFunclets(bool V) { HasEHFunclets = V; }
808
809 /// Find or create an LandingPadInfo for the specified MachineBasicBlock.
810 LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
811
812 /// Remap landing pad labels and remove any deleted landing pads.
813 void tidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap = nullptr);
814
815 /// Return a reference to the landing pad info for the current function.
816 const std::vector<LandingPadInfo> &getLandingPads() const {
817 return LandingPads;
818 }
819
820 /// Provide the begin and end labels of an invoke style call and associate it
821 /// with a try landing pad block.
822 void addInvoke(MachineBasicBlock *LandingPad,
823 MCSymbol *BeginLabel, MCSymbol *EndLabel);
824
Andrew Scull0372a572018-11-16 15:47:06 +0000825 /// Add a new panding pad, and extract the exception handling information from
826 /// the landingpad instruction. Returns the label ID for the landing pad
827 /// entry.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100828 MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
829
830 /// Provide the catch typeinfo for a landing pad.
831 void addCatchTypeInfo(MachineBasicBlock *LandingPad,
832 ArrayRef<const GlobalValue *> TyInfo);
833
834 /// Provide the filter typeinfo for a landing pad.
835 void addFilterTypeInfo(MachineBasicBlock *LandingPad,
836 ArrayRef<const GlobalValue *> TyInfo);
837
838 /// Add a cleanup action for a landing pad.
839 void addCleanup(MachineBasicBlock *LandingPad);
840
841 void addSEHCatchHandler(MachineBasicBlock *LandingPad, const Function *Filter,
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100842 const BlockAddress *RecoverBA);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100843
844 void addSEHCleanupHandler(MachineBasicBlock *LandingPad,
845 const Function *Cleanup);
846
847 /// Return the type id for the specified typeinfo. This is function wide.
848 unsigned getTypeIDFor(const GlobalValue *TI);
849
850 /// Return the id of the filter encoded by TyIds. This is function wide.
851 int getFilterIDFor(std::vector<unsigned> &TyIds);
852
853 /// Map the landing pad's EH symbol to the call site indexes.
854 void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
855
856 /// Get the call site indexes for a landing pad EH symbol.
857 SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
858 assert(hasCallSiteLandingPad(Sym) &&
859 "missing call site number for landing pad!");
860 return LPadToCallSiteMap[Sym];
861 }
862
863 /// Return true if the landing pad Eh symbol has an associated call site.
864 bool hasCallSiteLandingPad(MCSymbol *Sym) {
865 return !LPadToCallSiteMap[Sym].empty();
866 }
867
868 /// Map the begin label for a call site.
869 void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
870 CallSiteMap[BeginLabel] = Site;
871 }
872
873 /// Get the call site number for a begin label.
874 unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) const {
875 assert(hasCallSiteBeginLabel(BeginLabel) &&
876 "Missing call site number for EH_LABEL!");
877 return CallSiteMap.lookup(BeginLabel);
878 }
879
880 /// Return true if the begin label has a call site number associated with it.
881 bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) const {
882 return CallSiteMap.count(BeginLabel);
883 }
884
885 /// Record annotations associated with a particular label.
886 void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD) {
887 CodeViewAnnotations.push_back({Label, MD});
888 }
889
890 ArrayRef<std::pair<MCSymbol *, MDNode *>> getCodeViewAnnotations() const {
891 return CodeViewAnnotations;
892 }
893
894 /// Return a reference to the C++ typeinfo for the current function.
895 const std::vector<const GlobalValue *> &getTypeInfos() const {
896 return TypeInfos;
897 }
898
899 /// Return a reference to the typeids encoding filters used in the current
900 /// function.
901 const std::vector<unsigned> &getFilterIds() const {
902 return FilterIds;
903 }
904
905 /// \}
906
907 /// Collect information used to emit debugging information of a variable.
908 void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
Andrew Scullcdfcccc2018-10-05 20:58:37 +0100909 int Slot, const DILocation *Loc) {
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100910 VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
911 }
912
913 VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
914 const VariableDbgInfoMapTy &getVariableDbgInfo() const {
915 return VariableDbgInfos;
916 }
917};
918
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100919//===--------------------------------------------------------------------===//
920// GraphTraits specializations for function basic block graphs (CFGs)
921//===--------------------------------------------------------------------===//
922
923// Provide specializations of GraphTraits to be able to treat a
924// machine function as a graph of machine basic blocks... these are
925// the same as the machine basic block iterators, except that the root
926// node is implicitly the first node of the function.
927//
928template <> struct GraphTraits<MachineFunction*> :
929 public GraphTraits<MachineBasicBlock*> {
930 static NodeRef getEntryNode(MachineFunction *F) { return &F->front(); }
931
932 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
933 using nodes_iterator = pointer_iterator<MachineFunction::iterator>;
934
935 static nodes_iterator nodes_begin(MachineFunction *F) {
936 return nodes_iterator(F->begin());
937 }
938
939 static nodes_iterator nodes_end(MachineFunction *F) {
940 return nodes_iterator(F->end());
941 }
942
943 static unsigned size (MachineFunction *F) { return F->size(); }
944};
945template <> struct GraphTraits<const MachineFunction*> :
946 public GraphTraits<const MachineBasicBlock*> {
947 static NodeRef getEntryNode(const MachineFunction *F) { return &F->front(); }
948
949 // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
950 using nodes_iterator = pointer_iterator<MachineFunction::const_iterator>;
951
952 static nodes_iterator nodes_begin(const MachineFunction *F) {
953 return nodes_iterator(F->begin());
954 }
955
956 static nodes_iterator nodes_end (const MachineFunction *F) {
957 return nodes_iterator(F->end());
958 }
959
960 static unsigned size (const MachineFunction *F) {
961 return F->size();
962 }
963};
964
965// Provide specializations of GraphTraits to be able to treat a function as a
966// graph of basic blocks... and to walk it in inverse order. Inverse order for
967// a function is considered to be when traversing the predecessor edges of a BB
968// instead of the successor edges.
969//
970template <> struct GraphTraits<Inverse<MachineFunction*>> :
971 public GraphTraits<Inverse<MachineBasicBlock*>> {
972 static NodeRef getEntryNode(Inverse<MachineFunction *> G) {
973 return &G.Graph->front();
974 }
975};
976template <> struct GraphTraits<Inverse<const MachineFunction*>> :
977 public GraphTraits<Inverse<const MachineBasicBlock*>> {
978 static NodeRef getEntryNode(Inverse<const MachineFunction *> G) {
979 return &G.Graph->front();
980 }
981};
982
983} // end namespace llvm
984
985#endif // LLVM_CODEGEN_MACHINEFUNCTION_H