LLVM  8.0.1
MachineModuleInfo.cpp
Go to the documentation of this file.
1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- 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 
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/TinyPtrVector.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/Value.h"
23 #include "llvm/IR/ValueHandle.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/Casting.h"
31 #include <algorithm>
32 #include <cassert>
33 #include <memory>
34 #include <utility>
35 #include <vector>
36 
37 using namespace llvm;
38 using namespace llvm::dwarf;
39 
40 // Handle the Pass registration stuff necessary to use DataLayout's.
41 INITIALIZE_PASS(MachineModuleInfo, "machinemoduleinfo",
42  "Machine Module Information", false, false)
44 
45 // Out of line virtual method.
47 
48 namespace llvm {
49 
51  MMIAddrLabelMap *Map = nullptr;
52 
53 public:
54  MMIAddrLabelMapCallbackPtr() = default;
56 
57  void setPtr(BasicBlock *BB) {
59  }
60 
61  void setMap(MMIAddrLabelMap *map) { Map = map; }
62 
63  void deleted() override;
64  void allUsesReplacedWith(Value *V2) override;
65 };
66 
69  struct AddrLabelSymEntry {
70  /// The symbols for the label.
72 
73  Function *Fn; // The containing function of the BasicBlock.
74  unsigned Index; // The index in BBCallbacks for the BasicBlock.
75  };
76 
77  DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
78 
79  /// Callbacks for the BasicBlock's that we have entries for. We use this so
80  /// we get notified if a block is deleted or RAUWd.
81  std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
82 
83  /// This is a per-function list of symbols whose corresponding BasicBlock got
84  /// deleted. These symbols need to be emitted at some point in the file, so
85  /// AsmPrinter emits them after the function body.
86  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>
87  DeletedAddrLabelsNeedingEmission;
88 
89 public:
90  MMIAddrLabelMap(MCContext &context) : Context(context) {}
91 
93  assert(DeletedAddrLabelsNeedingEmission.empty() &&
94  "Some labels for deleted blocks never got emitted");
95  }
96 
97  ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
98 
99  void takeDeletedSymbolsForFunction(Function *F,
100  std::vector<MCSymbol*> &Result);
101 
102  void UpdateForDeletedBlock(BasicBlock *BB);
103  void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
104 };
105 
106 } // end namespace llvm
107 
109  assert(BB->hasAddressTaken() &&
110  "Shouldn't get label for block without address taken");
111  AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
112 
113  // If we already had an entry for this block, just return it.
114  if (!Entry.Symbols.empty()) {
115  assert(BB->getParent() == Entry.Fn && "Parent changed");
116  return Entry.Symbols;
117  }
118 
119  // Otherwise, this is a new entry, create a new symbol for it and add an
120  // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
121  BBCallbacks.emplace_back(BB);
122  BBCallbacks.back().setMap(this);
123  Entry.Index = BBCallbacks.size() - 1;
124  Entry.Fn = BB->getParent();
125  Entry.Symbols.push_back(Context.createTempSymbol());
126  return Entry.Symbols;
127 }
128 
129 /// If we have any deleted symbols for F, return them.
131 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
132  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>::iterator I =
133  DeletedAddrLabelsNeedingEmission.find(F);
134 
135  // If there are no entries for the function, just return.
136  if (I == DeletedAddrLabelsNeedingEmission.end()) return;
137 
138  // Otherwise, take the list.
139  std::swap(Result, I->second);
140  DeletedAddrLabelsNeedingEmission.erase(I);
141 }
142 
144  // If the block got deleted, there is no need for the symbol. If the symbol
145  // was already emitted, we can just forget about it, otherwise we need to
146  // queue it up for later emission when the function is output.
147  AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
148  AddrLabelSymbols.erase(BB);
149  assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
150  BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
151 
152  assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
153  "Block/parent mismatch");
154 
155  for (MCSymbol *Sym : Entry.Symbols) {
156  if (Sym->isDefined())
157  return;
158 
159  // If the block is not yet defined, we need to emit it at the end of the
160  // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
161  // for the containing Function. Since the block is being deleted, its
162  // parent may already be removed, we have to get the function from 'Entry'.
163  DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
164  }
165 }
166 
168  // Get the entry for the RAUW'd block and remove it from our map.
169  AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
170  AddrLabelSymbols.erase(Old);
171  assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
172 
173  AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
174 
175  // If New is not address taken, just move our symbol over to it.
176  if (NewEntry.Symbols.empty()) {
177  BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
178  NewEntry = std::move(OldEntry); // Set New's entry.
179  return;
180  }
181 
182  BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
183 
184  // Otherwise, we need to add the old symbols to the new block's set.
185  NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
186  OldEntry.Symbols.end());
187 }
188 
190  Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
191 }
192 
194  Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
195 }
196 
198  : ImmutablePass(ID), TM(*TM),
199  Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
200  TM->getObjFileLowering(), nullptr, false) {
202 }
203 
205 
207  ObjFileMMI = nullptr;
208  CurCallSite = 0;
209  UsesVAFloatArgument = UsesMorestackAddr = false;
210  HasSplitStack = HasNosplitStack = false;
211  AddrLabelSymbols = nullptr;
212  TheModule = &M;
213  DbgInfoAvailable = !empty(M.debug_compile_units());
214  return false;
215 }
216 
218  Personalities.clear();
219 
220  delete AddrLabelSymbols;
221  AddrLabelSymbols = nullptr;
222 
223  Context.reset();
224 
225  delete ObjFileMMI;
226  ObjFileMMI = nullptr;
227 
228  return false;
229 }
230 
231 //===- Address of Block Management ----------------------------------------===//
232 
235  // Lazily create AddrLabelSymbols.
236  if (!AddrLabelSymbols)
237  AddrLabelSymbols = new MMIAddrLabelMap(Context);
238  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
239 }
240 
243  std::vector<MCSymbol*> &Result) {
244  // If no blocks have had their addresses taken, we're done.
245  if (!AddrLabelSymbols) return;
246  return AddrLabelSymbols->
247  takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
248 }
249 
250 /// \name Exception Handling
251 /// \{
252 
253 void MachineModuleInfo::addPersonality(const Function *Personality) {
254  for (unsigned i = 0; i < Personalities.size(); ++i)
255  if (Personalities[i] == Personality)
256  return;
257  Personalities.push_back(Personality);
258 }
259 
260 /// \}
261 
264  auto I = MachineFunctions.find(&F);
265  return I != MachineFunctions.end() ? I->second.get() : nullptr;
266 }
267 
270  // Shortcut for the common case where a sequence of MachineFunctionPasses
271  // all query for the same Function.
272  if (LastRequest == &F)
273  return *LastResult;
274 
275  auto I = MachineFunctions.insert(
276  std::make_pair(&F, std::unique_ptr<MachineFunction>()));
277  MachineFunction *MF;
278  if (I.second) {
279  // No pre-existing machine function, create a new one.
280  const TargetSubtargetInfo &STI = *TM.getSubtargetImpl(F);
281  MF = new MachineFunction(F, TM, STI, NextFnNum++, *this);
282  // Update the set entry.
283  I.first->second.reset(MF);
284  } else {
285  MF = I.first->second.get();
286  }
287 
288  LastRequest = &F;
289  LastResult = MF;
290  return *MF;
291 }
292 
294  MachineFunctions.erase(&F);
295  LastRequest = nullptr;
296  LastResult = nullptr;
297 }
298 
299 namespace {
300 
301 /// This pass frees the MachineFunction object associated with a Function.
302 class FreeMachineFunction : public FunctionPass {
303 public:
304  static char ID;
305 
306  FreeMachineFunction() : FunctionPass(ID) {}
307 
308  void getAnalysisUsage(AnalysisUsage &AU) const override {
311  }
312 
313  bool runOnFunction(Function &F) override {
314  MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
316  return true;
317  }
318 
319  StringRef getPassName() const override {
320  return "Free MachineFunction";
321  }
322 };
323 
324 } // end anonymous namespace
325 
327 
329  return new FreeMachineFunction();
330 }
331 
332 //===- MMI building helpers -----------------------------------------------===//
333 
335  MachineModuleInfo &MMI) {
336  FunctionType *FT =
337  cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
338  if (FT->isVarArg() && !MMI.usesVAFloatArgument()) {
339  for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
340  Type *T = I.getArgOperand(i)->getType();
341  for (auto i : post_order(T)) {
342  if (i->isFloatingPointTy()) {
343  MMI.setUsesVAFloatArgument(true);
344  return;
345  }
346  }
347  }
348  }
349 }
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
bool doFinalization(Module &) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
LLVMContext & Context
This class represents lattice values for constants.
Definition: AllocatorList.h:24
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:42
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
void deleteMachineFunctionFor(Function &F)
Delete the MachineFunction MF and reset the link in the IR Function to Machine Function map...
void reset()
reset - return object to right after construction state to prepare to process a new module ...
Definition: MCContext.cpp:83
This class represents a function call, abstracting a target machine&#39;s calling convention.
F(f)
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:31
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
Definition: Pass.cpp:75
void computeUsesVAFloatArgument(const CallInst &I, MachineModuleInfo &MMI)
Determine if any floating-point values are being passed to this variadic function, and set the MachineModuleInfo&#39;s usesVAFloatArgument flag if so.
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1135
MachineModuleInfo(const LLVMTargetMachine *TM=nullptr)
void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New)
AnalysisUsage & addRequired()
~MachineModuleInfo() override
MMIAddrLabelMap(MCContext &context)
Context object for machine code objects.
Definition: MCContext.h:63
Class to represent function types.
Definition: DerivedTypes.h:103
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: Pass.cpp:92
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
bool isVarArg() const
Definition: DerivedTypes.h:123
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(const BasicBlock *BB)
Return the symbol to be used for the specified basic block when its address is taken.
static bool runOnFunction(Function &F, bool PostInlining)
Value * getCalledValue() const
Definition: InstrTypes.h:1174
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
void takeDeletedSymbolsForFunction(const Function *F, std::vector< MCSymbol *> &Result)
If the specified function has had any references to address-taken blocks generated, but the block got deleted, return the symbol now so we can emit it.
void addPersonality(const Function *Personality)
Provide the personality function for the exception information.
FunctionPass * createFreeMachineFunctionPass()
This pass frees the memory occupied by the MachineFunction.
Represent the analysis usage information of a pass.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
iterator_range< po_iterator< T > > post_order(const T &G)
MachineFunction & getOrCreateMachineFunction(const Function &F)
Returns the MachineFunction constructed for the IR function F.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:34
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:210
void initializeMachineModuleInfoPass(PassRegistry &)
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Definition: BasicBlock.h:392
ImmutablePass class - This class is used to provide information that does not need to be run...
Definition: Pass.h:256
MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr...
Module.h This file contains the declarations for the Module class.
void setMap(MMIAddrLabelMap *map)
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target&#39;s TargetSubtargetInf...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:941
bool isDefined() const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:248
bool doInitialization(Module &) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
TargetSubtargetInfo - Generic base class for all target subtargets.
unsigned getNumArgOperands() const
Definition: InstrTypes.h:1133
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:107
#define I(x, y, z)
Definition: MD5.cpp:58
iterator_range< debug_compile_units_iterator > debug_compile_units() const
Return an iterator for all DICompileUnits listed in this Module&#39;s llvm.dbg.cu named metadata node and...
Definition: Module.h:778
void setUsesVAFloatArgument(bool b)
void allUsesReplacedWith(Value *V2) override
Callback for Value RAUW.
Value * operator=(Value *RHS)
Definition: ValueHandle.h:70
ArrayRef< MCSymbol * > getAddrLabelSymbolToEmit(BasicBlock *BB)
void deleted() override
Callback for Value destruction.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
void UpdateForDeletedBlock(BasicBlock *BB)
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:389
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void takeDeletedSymbolsForFunction(Function *F, std::vector< MCSymbol *> &Result)
If we have any deleted symbols for F, return them.
This class can be derived from and used by targets to hold private target-specific information for ea...
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition: Type.h:333
This class contains meta information specific to a module.