LLVM  mainline
MachineModuleInfo.cpp
Go to the documentation of this file.
00001 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/CodeGen/MachineModuleInfo.h"
00011 #include "llvm/ADT/PointerUnion.h"
00012 #include "llvm/ADT/TinyPtrVector.h"
00013 #include "llvm/Analysis/EHPersonalities.h"
00014 #include "llvm/Analysis/ValueTracking.h"
00015 #include "llvm/CodeGen/MachineFunction.h"
00016 #include "llvm/CodeGen/MachineFunctionPass.h"
00017 #include "llvm/CodeGen/Passes.h"
00018 #include "llvm/IR/Constants.h"
00019 #include "llvm/IR/DerivedTypes.h"
00020 #include "llvm/IR/GlobalVariable.h"
00021 #include "llvm/IR/Module.h"
00022 #include "llvm/MC/MCObjectFileInfo.h"
00023 #include "llvm/MC/MCSymbol.h"
00024 #include "llvm/Support/Dwarf.h"
00025 #include "llvm/Support/ErrorHandling.h"
00026 using namespace llvm;
00027 using namespace llvm::dwarf;
00028 
00029 // Handle the Pass registration stuff necessary to use DataLayout's.
00030 INITIALIZE_PASS(MachineModuleInfo, "machinemoduleinfo",
00031                 "Machine Module Information", false, false)
00032 char MachineModuleInfo::ID = 0;
00033 
00034 // Out of line virtual method.
00035 MachineModuleInfoImpl::~MachineModuleInfoImpl() {}
00036 
00037 namespace llvm {
00038 class MMIAddrLabelMapCallbackPtr final : CallbackVH {
00039   MMIAddrLabelMap *Map;
00040 public:
00041   MMIAddrLabelMapCallbackPtr() : Map(nullptr) {}
00042   MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {}
00043 
00044   void setPtr(BasicBlock *BB) {
00045     ValueHandleBase::operator=(BB);
00046   }
00047 
00048   void setMap(MMIAddrLabelMap *map) { Map = map; }
00049 
00050   void deleted() override;
00051   void allUsesReplacedWith(Value *V2) override;
00052 };
00053 
00054 class MMIAddrLabelMap {
00055   MCContext &Context;
00056   struct AddrLabelSymEntry {
00057     /// Symbols - The symbols for the label.
00058     TinyPtrVector<MCSymbol *> Symbols;
00059 
00060     Function *Fn;   // The containing function of the BasicBlock.
00061     unsigned Index; // The index in BBCallbacks for the BasicBlock.
00062   };
00063 
00064   DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols;
00065 
00066   /// BBCallbacks - Callbacks for the BasicBlock's that we have entries for.  We
00067   /// use this so we get notified if a block is deleted or RAUWd.
00068   std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks;
00069 
00070   /// DeletedAddrLabelsNeedingEmission - This is a per-function list of symbols
00071   /// whose corresponding BasicBlock got deleted.  These symbols need to be
00072   /// emitted at some point in the file, so AsmPrinter emits them after the
00073   /// function body.
00074   DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >
00075     DeletedAddrLabelsNeedingEmission;
00076 public:
00077 
00078   MMIAddrLabelMap(MCContext &context) : Context(context) {}
00079   ~MMIAddrLabelMap() {
00080     assert(DeletedAddrLabelsNeedingEmission.empty() &&
00081            "Some labels for deleted blocks never got emitted");
00082   }
00083 
00084   ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB);
00085 
00086   void takeDeletedSymbolsForFunction(Function *F,
00087                                      std::vector<MCSymbol*> &Result);
00088 
00089   void UpdateForDeletedBlock(BasicBlock *BB);
00090   void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New);
00091 };
00092 }
00093 
00094 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) {
00095   assert(BB->hasAddressTaken() &&
00096          "Shouldn't get label for block without address taken");
00097   AddrLabelSymEntry &Entry = AddrLabelSymbols[BB];
00098 
00099   // If we already had an entry for this block, just return it.
00100   if (!Entry.Symbols.empty()) {
00101     assert(BB->getParent() == Entry.Fn && "Parent changed");
00102     return Entry.Symbols;
00103   }
00104 
00105   // Otherwise, this is a new entry, create a new symbol for it and add an
00106   // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd.
00107   BBCallbacks.emplace_back(BB);
00108   BBCallbacks.back().setMap(this);
00109   Entry.Index = BBCallbacks.size() - 1;
00110   Entry.Fn = BB->getParent();
00111   Entry.Symbols.push_back(Context.createTempSymbol());
00112   return Entry.Symbols;
00113 }
00114 
00115 /// takeDeletedSymbolsForFunction - If we have any deleted symbols for F, return
00116 /// them.
00117 void MMIAddrLabelMap::
00118 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) {
00119   DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I =
00120     DeletedAddrLabelsNeedingEmission.find(F);
00121 
00122   // If there are no entries for the function, just return.
00123   if (I == DeletedAddrLabelsNeedingEmission.end()) return;
00124 
00125   // Otherwise, take the list.
00126   std::swap(Result, I->second);
00127   DeletedAddrLabelsNeedingEmission.erase(I);
00128 }
00129 
00130 
00131 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) {
00132   // If the block got deleted, there is no need for the symbol.  If the symbol
00133   // was already emitted, we can just forget about it, otherwise we need to
00134   // queue it up for later emission when the function is output.
00135   AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]);
00136   AddrLabelSymbols.erase(BB);
00137   assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?");
00138   BBCallbacks[Entry.Index] = nullptr;  // Clear the callback.
00139 
00140   assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) &&
00141          "Block/parent mismatch");
00142 
00143   for (MCSymbol *Sym : Entry.Symbols) {
00144     if (Sym->isDefined())
00145       return;
00146 
00147     // If the block is not yet defined, we need to emit it at the end of the
00148     // function.  Add the symbol to the DeletedAddrLabelsNeedingEmission list
00149     // for the containing Function.  Since the block is being deleted, its
00150     // parent may already be removed, we have to get the function from 'Entry'.
00151     DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym);
00152   }
00153 }
00154 
00155 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) {
00156   // Get the entry for the RAUW'd block and remove it from our map.
00157   AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]);
00158   AddrLabelSymbols.erase(Old);
00159   assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?");
00160 
00161   AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New];
00162 
00163   // If New is not address taken, just move our symbol over to it.
00164   if (NewEntry.Symbols.empty()) {
00165     BBCallbacks[OldEntry.Index].setPtr(New);    // Update the callback.
00166     NewEntry = std::move(OldEntry);             // Set New's entry.
00167     return;
00168   }
00169 
00170   BBCallbacks[OldEntry.Index] = nullptr;    // Update the callback.
00171 
00172   // Otherwise, we need to add the old symbols to the new block's set.
00173   NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(),
00174                           OldEntry.Symbols.end());
00175 }
00176 
00177 
00178 void MMIAddrLabelMapCallbackPtr::deleted() {
00179   Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr()));
00180 }
00181 
00182 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) {
00183   Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2));
00184 }
00185 
00186 
00187 //===----------------------------------------------------------------------===//
00188 
00189 MachineModuleInfo::MachineModuleInfo(const MCAsmInfo &MAI,
00190                                      const MCRegisterInfo &MRI,
00191                                      const MCObjectFileInfo *MOFI)
00192   : ImmutablePass(ID), Context(&MAI, &MRI, MOFI, nullptr, false) {
00193   initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry());
00194 }
00195 
00196 MachineModuleInfo::MachineModuleInfo()
00197   : ImmutablePass(ID), Context(nullptr, nullptr, nullptr) {
00198   llvm_unreachable("This MachineModuleInfo constructor should never be called, "
00199                    "MMI should always be explicitly constructed by "
00200                    "LLVMTargetMachine");
00201 }
00202 
00203 MachineModuleInfo::~MachineModuleInfo() {
00204 }
00205 
00206 bool MachineModuleInfo::doInitialization(Module &M) {
00207 
00208   ObjFileMMI = nullptr;
00209   CurCallSite = 0;
00210   CallsEHReturn = false;
00211   CallsUnwindInit = false;
00212   HasEHFunclets = false;
00213   DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false;
00214   PersonalityTypeCache = EHPersonality::Unknown;
00215   AddrLabelSymbols = nullptr;
00216   TheModule = nullptr;
00217 
00218   return false;
00219 }
00220 
00221 bool MachineModuleInfo::doFinalization(Module &M) {
00222 
00223   Personalities.clear();
00224 
00225   delete AddrLabelSymbols;
00226   AddrLabelSymbols = nullptr;
00227 
00228   Context.reset();
00229 
00230   delete ObjFileMMI;
00231   ObjFileMMI = nullptr;
00232 
00233   return false;
00234 }
00235 
00236 /// EndFunction - Discard function meta information.
00237 ///
00238 void MachineModuleInfo::EndFunction() {
00239   // Clean up frame info.
00240   FrameInstructions.clear();
00241 
00242   // Clean up exception info.
00243   LandingPads.clear();
00244   PersonalityTypeCache = EHPersonality::Unknown;
00245   CallSiteMap.clear();
00246   TypeInfos.clear();
00247   FilterIds.clear();
00248   FilterEnds.clear();
00249   CallsEHReturn = false;
00250   CallsUnwindInit = false;
00251   HasEHFunclets = false;
00252   VariableDbgInfos.clear();
00253 }
00254 
00255 //===- Address of Block Management ----------------------------------------===//
00256 
00257 /// getAddrLabelSymbolToEmit - Return the symbol to be used for the specified
00258 /// basic block when its address is taken.  If other blocks were RAUW'd to
00259 /// this one, we may have to emit them as well, return the whole set.
00260 ArrayRef<MCSymbol *>
00261 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) {
00262   // Lazily create AddrLabelSymbols.
00263   if (!AddrLabelSymbols)
00264     AddrLabelSymbols = new MMIAddrLabelMap(Context);
00265  return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB));
00266 }
00267 
00268 
00269 /// takeDeletedSymbolsForFunction - If the specified function has had any
00270 /// references to address-taken blocks generated, but the block got deleted,
00271 /// return the symbol now so we can emit it.  This prevents emitting a
00272 /// reference to a symbol that has no definition.
00273 void MachineModuleInfo::
00274 takeDeletedSymbolsForFunction(const Function *F,
00275                               std::vector<MCSymbol*> &Result) {
00276   // If no blocks have had their addresses taken, we're done.
00277   if (!AddrLabelSymbols) return;
00278   return AddrLabelSymbols->
00279      takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result);
00280 }
00281 
00282 //===- EH -----------------------------------------------------------------===//
00283 
00284 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
00285 /// specified MachineBasicBlock.
00286 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
00287     (MachineBasicBlock *LandingPad) {
00288   unsigned N = LandingPads.size();
00289   for (unsigned i = 0; i < N; ++i) {
00290     LandingPadInfo &LP = LandingPads[i];
00291     if (LP.LandingPadBlock == LandingPad)
00292       return LP;
00293   }
00294 
00295   LandingPads.push_back(LandingPadInfo(LandingPad));
00296   return LandingPads[N];
00297 }
00298 
00299 /// addInvoke - Provide the begin and end labels of an invoke style call and
00300 /// associate it with a try landing pad block.
00301 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
00302                                   MCSymbol *BeginLabel, MCSymbol *EndLabel) {
00303   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
00304   LP.BeginLabels.push_back(BeginLabel);
00305   LP.EndLabels.push_back(EndLabel);
00306 }
00307 
00308 /// addLandingPad - Provide the label of a try LandingPad block.
00309 ///
00310 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
00311   MCSymbol *LandingPadLabel = Context.createTempSymbol();
00312   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
00313   LP.LandingPadLabel = LandingPadLabel;
00314   return LandingPadLabel;
00315 }
00316 
00317 void MachineModuleInfo::addPersonality(const Function *Personality) {
00318   for (unsigned i = 0; i < Personalities.size(); ++i)
00319     if (Personalities[i] == Personality)
00320       return;
00321   Personalities.push_back(Personality);
00322 }
00323 
00324 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
00325 ///
00326 void MachineModuleInfo::
00327 addCatchTypeInfo(MachineBasicBlock *LandingPad,
00328                  ArrayRef<const GlobalValue *> TyInfo) {
00329   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
00330   for (unsigned N = TyInfo.size(); N; --N)
00331     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
00332 }
00333 
00334 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
00335 ///
00336 void MachineModuleInfo::
00337 addFilterTypeInfo(MachineBasicBlock *LandingPad,
00338                   ArrayRef<const GlobalValue *> TyInfo) {
00339   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
00340   std::vector<unsigned> IdsInFilter(TyInfo.size());
00341   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
00342     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
00343   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
00344 }
00345 
00346 /// addCleanup - Add a cleanup action for a landing pad.
00347 ///
00348 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
00349   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
00350   LP.TypeIds.push_back(0);
00351 }
00352 
00353 void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad,
00354                                            const Function *Filter,
00355                                            const BlockAddress *RecoverBA) {
00356   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
00357   SEHHandler Handler;
00358   Handler.FilterOrFinally = Filter;
00359   Handler.RecoverBA = RecoverBA;
00360   LP.SEHHandlers.push_back(Handler);
00361 }
00362 
00363 void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
00364                                              const Function *Cleanup) {
00365   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
00366   SEHHandler Handler;
00367   Handler.FilterOrFinally = Cleanup;
00368   Handler.RecoverBA = nullptr;
00369   LP.SEHHandlers.push_back(Handler);
00370 }
00371 
00372 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
00373 /// pads.
00374 void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
00375   for (unsigned i = 0; i != LandingPads.size(); ) {
00376     LandingPadInfo &LandingPad = LandingPads[i];
00377     if (LandingPad.LandingPadLabel &&
00378         !LandingPad.LandingPadLabel->isDefined() &&
00379         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
00380       LandingPad.LandingPadLabel = nullptr;
00381 
00382     // Special case: we *should* emit LPs with null LP MBB. This indicates
00383     // "nounwind" case.
00384     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
00385       LandingPads.erase(LandingPads.begin() + i);
00386       continue;
00387     }
00388 
00389     for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
00390       MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
00391       MCSymbol *EndLabel = LandingPad.EndLabels[j];
00392       if ((BeginLabel->isDefined() ||
00393            (LPMap && (*LPMap)[BeginLabel] != 0)) &&
00394           (EndLabel->isDefined() ||
00395            (LPMap && (*LPMap)[EndLabel] != 0))) continue;
00396 
00397       LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
00398       LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
00399       --j, --e;
00400     }
00401 
00402     // Remove landing pads with no try-ranges.
00403     if (LandingPads[i].BeginLabels.empty()) {
00404       LandingPads.erase(LandingPads.begin() + i);
00405       continue;
00406     }
00407 
00408     // If there is no landing pad, ensure that the list of typeids is empty.
00409     // If the only typeid is a cleanup, this is the same as having no typeids.
00410     if (!LandingPad.LandingPadBlock ||
00411         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
00412       LandingPad.TypeIds.clear();
00413     ++i;
00414   }
00415 }
00416 
00417 /// setCallSiteLandingPad - Map the landing pad's EH symbol to the call site
00418 /// indexes.
00419 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym,
00420                                               ArrayRef<unsigned> Sites) {
00421   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
00422 }
00423 
00424 /// getTypeIDFor - Return the type id for the specified typeinfo.  This is
00425 /// function wide.
00426 unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) {
00427   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
00428     if (TypeInfos[i] == TI) return i + 1;
00429 
00430   TypeInfos.push_back(TI);
00431   return TypeInfos.size();
00432 }
00433 
00434 /// getFilterIDFor - Return the filter id for the specified typeinfos.  This is
00435 /// function wide.
00436 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
00437   // If the new filter coincides with the tail of an existing filter, then
00438   // re-use the existing filter.  Folding filters more than this requires
00439   // re-ordering filters and/or their elements - probably not worth it.
00440   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
00441        E = FilterEnds.end(); I != E; ++I) {
00442     unsigned i = *I, j = TyIds.size();
00443 
00444     while (i && j)
00445       if (FilterIds[--i] != TyIds[--j])
00446         goto try_next;
00447 
00448     if (!j)
00449       // The new filter coincides with range [i, end) of the existing filter.
00450       return -(1 + i);
00451 
00452 try_next:;
00453   }
00454 
00455   // Add the new filter.
00456   int FilterID = -(1 + FilterIds.size());
00457   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
00458   FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
00459   FilterEnds.push_back(FilterIds.size());
00460   FilterIds.push_back(0); // terminator
00461   return FilterID;
00462 }