LLVM  6.0.0svn
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/DebugInfo.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Value.h"
24 #include "llvm/IR/ValueHandle.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Casting.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <memory>
35 #include <utility>
36 #include <vector>
37 
38 using namespace llvm;
39 using namespace llvm::dwarf;
40 
41 // Handle the Pass registration stuff necessary to use DataLayout's.
42 INITIALIZE_PASS(MachineModuleInfo, "machinemoduleinfo",
43  "Machine Module Information", false, false)
45 
46 // Out of line virtual method.
48 
49 namespace llvm {
50 
52  MMIAddrLabelMap *Map = nullptr;
53 
54 public:
55  MMIAddrLabelMapCallbackPtr() = default;
57 
58  void setPtr(BasicBlock *BB) {
60  }
61 
62  void setMap(MMIAddrLabelMap *map) { Map = map; }
63 
64  void deleted() override;
65  void allUsesReplacedWith(Value *V2) override;
66 };
67 
70  struct AddrLabelSymEntry {
71  /// The symbols for the label.
73 
74  Function *Fn; // The containing function of the BasicBlock.
75  unsigned Index; // The index in BBCallbacks for the BasicBlock.
76  };
77 
78  DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
79 
80  /// Callbacks for the BasicBlock's that we have entries for. We use this so
81  /// we get notified if a block is deleted or RAUWd.
82  std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
83 
84  /// This is a per-function list of symbols whose corresponding BasicBlock got
85  /// deleted. These symbols need to be emitted at some point in the file, so
86  /// AsmPrinter emits them after the function body.
87  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>
88  DeletedAddrLabelsNeedingEmission;
89 
90 public:
91  MMIAddrLabelMap(MCContext &context) : Context(context) {}
92 
94  assert(DeletedAddrLabelsNeedingEmission.empty() &&
95  "Some labels for deleted blocks never got emitted");
96  }
97 
98  ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
99 
100  void takeDeletedSymbolsForFunction(Function *F,
101  std::vector<MCSymbol*> &Result);
102 
103  void UpdateForDeletedBlock(BasicBlock *BB);
104  void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
105 };
106 
107 } // end namespace llvm
108 
110  assert(BB->hasAddressTaken() &&
111  "Shouldn't get label for block without address taken");
112  AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
113 
114  // If we already had an entry for this block, just return it.
115  if (!Entry.Symbols.empty()) {
116  assert(BB->getParent() == Entry.Fn && "Parent changed");
117  return Entry.Symbols;
118  }
119 
120  // Otherwise, this is a new entry, create a new symbol for it and add an
121  // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
122  BBCallbacks.emplace_back(BB);
123  BBCallbacks.back().setMap(this);
124  Entry.Index = BBCallbacks.size() - 1;
125  Entry.Fn = BB->getParent();
126  Entry.Symbols.push_back(Context.createTempSymbol());
127  return Entry.Symbols;
128 }
129 
130 /// If we have any deleted symbols for F, return them.
132 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
133  DenseMap<AssertingVH<Function>, std::vector<MCSymbol*>>::iterator I =
134  DeletedAddrLabelsNeedingEmission.find(F);
135 
136  // If there are no entries for the function, just return.
137  if (I == DeletedAddrLabelsNeedingEmission.end()) return;
138 
139  // Otherwise, take the list.
140  std::swap(Result, I->second);
141  DeletedAddrLabelsNeedingEmission.erase(I);
142 }
143 
145  // If the block got deleted, there is no need for the symbol. If the symbol
146  // was already emitted, we can just forget about it, otherwise we need to
147  // queue it up for later emission when the function is output.
148  AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
149  AddrLabelSymbols.erase(BB);
150  assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
151  BBCallbacks[Entry.Index] = nullptr; // Clear the callback.
152 
153  assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
154  "Block/parent mismatch");
155 
156  for (MCSymbol *Sym : Entry.Symbols) {
157  if (Sym->isDefined())
158  return;
159 
160  // If the block is not yet defined, we need to emit it at the end of the
161  // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list
162  // for the containing Function. Since the block is being deleted, its
163  // parent may already be removed, we have to get the function from 'Entry'.
164  DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
165  }
166 }
167 
169  // Get the entry for the RAUW'd block and remove it from our map.
170  AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
171  AddrLabelSymbols.erase(Old);
172  assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
173 
174  AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
175 
176  // If New is not address taken, just move our symbol over to it.
177  if (NewEntry.Symbols.empty()) {
178  BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback.
179  NewEntry = std::move(OldEntry); // Set New's entry.
180  return;
181  }
182 
183  BBCallbacks[OldEntry.Index] = nullptr; // Update the callback.
184 
185  // Otherwise, we need to add the old symbols to the new block's set.
186  NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
187  OldEntry.Symbols.end());
188 }
189 
191  Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
192 }
193 
195  Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
196 }
197 
199  : ImmutablePass(ID), TM(*TM),
200  Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(),
201  TM->getObjFileLowering(), nullptr, false) {
203 }
204 
206 
208  ObjFileMMI = nullptr;
209  CurCallSite = 0;
210  DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false;
211  AddrLabelSymbols = nullptr;
212  TheModule = &M;
213  return false;
214 }
215 
217  Personalities.clear();
218 
219  delete AddrLabelSymbols;
220  AddrLabelSymbols = nullptr;
221 
222  Context.reset();
223 
224  delete ObjFileMMI;
225  ObjFileMMI = nullptr;
226 
227  return false;
228 }
229 
230 //===- Address of Block Management ----------------------------------------===//
231 
234  // Lazily create AddrLabelSymbols.
235  if (!AddrLabelSymbols)
236  AddrLabelSymbols = new MMIAddrLabelMap(Context);
237  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
238 }
239 
242  std::vector<MCSymbol*> &Result) {
243  // If no blocks have had their addresses taken, we're done.
244  if (!AddrLabelSymbols) return;
245  return AddrLabelSymbols->
246  takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
247 }
248 
249 /// \name Exception Handling
250 /// \{
251 
252 void MachineModuleInfo::addPersonality(const Function *Personality) {
253  for (unsigned i = 0; i < Personalities.size(); ++i)
254  if (Personalities[i] == Personality)
255  return;
256  Personalities.push_back(Personality);
257 }
258 
259 /// \}
260 
263  auto I = MachineFunctions.find(&F);
264  return I != MachineFunctions.end() ? I->second.get() : nullptr;
265 }
266 
269  // Shortcut for the common case where a sequence of MachineFunctionPasses
270  // all query for the same Function.
271  if (LastRequest == &F)
272  return *LastResult;
273 
274  auto I = MachineFunctions.insert(
275  std::make_pair(&F, std::unique_ptr<MachineFunction>()));
276  MachineFunction *MF;
277  if (I.second) {
278  // No pre-existing machine function, create a new one.
279  MF = new MachineFunction(&F, TM, NextFnNum++, *this);
280  // Update the set entry.
281  I.first->second.reset(MF);
282  } else {
283  MF = I.first->second.get();
284  }
285 
286  LastRequest = &F;
287  LastResult = MF;
288  return *MF;
289 }
290 
292  MachineFunctions.erase(&F);
293  LastRequest = nullptr;
294  LastResult = nullptr;
295 }
296 
297 namespace {
298 
299 /// This pass frees the MachineFunction object associated with a Function.
300 class FreeMachineFunction : public FunctionPass {
301 public:
302  static char ID;
303 
304  FreeMachineFunction() : FunctionPass(ID) {}
305 
306  void getAnalysisUsage(AnalysisUsage &AU) const override {
309  }
310 
311  bool runOnFunction(Function &F) override {
312  MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>();
314  return true;
315  }
316 
317  StringRef getPassName() const override {
318  return "Free MachineFunction";
319  }
320 };
321 
322 } // end anonymous namespace
323 
325 
327  return new FreeMachineFunction();
328 }
329 
330 //===- MMI building helpers -----------------------------------------------===//
331 
333  MachineModuleInfo &MMI) {
334  FunctionType *FT =
335  cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
336  if (FT->isVarArg() && !MMI.usesVAFloatArgument()) {
337  for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
338  Type *T = I.getArgOperand(i)->getType();
339  for (auto i : post_order(T)) {
340  if (i->isFloatingPointTy()) {
341  MMI.setUsesVAFloatArgument(true);
342  return;
343  }
344  }
345  }
346  }
347 }
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
Compute iterated dominance frontiers using a linear time algorithm.
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:63
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:82
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:74
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.
void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New)
AnalysisUsage & addRequired()
~MachineModuleInfo() override
unsigned getNumArgOperands() const
Return the number of call arguments.
MachineModuleInfo(const TargetMachine *TM=nullptr)
MMIAddrLabelMap(MCContext &context)
Context object for machine code objects.
Definition: MCContext.h:59
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:91
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.
const Value * getCalledValue() const
Get a pointer to the function that is invoked by this instruction.
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
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.
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
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:376
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)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
bool doInitialization(Module &) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
#define I(x, y, z)
Definition: MD5.cpp:58
bool isDefined(bool SetUsed=true) const
isDefined - Check if this symbol is defined (i.e., it has an address).
Definition: MCSymbol.h:249
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)
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:57
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:330
This class contains meta information specific to a module.