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 10 #include "llvm/CodeGen/MachineModuleInfo.h" 11 #include "llvm/ADT/PointerUnion.h" 12 #include "llvm/ADT/PostOrderIterator.h" 13 #include "llvm/ADT/TinyPtrVector.h" 14 #include "llvm/Analysis/EHPersonalities.h" 15 #include "llvm/Analysis/ValueTracking.h" 16 #include "llvm/CodeGen/MachineFunction.h" 17 #include "llvm/CodeGen/MachineFunctionInitializer.h" 18 #include "llvm/CodeGen/MachineFunctionPass.h" 19 #include "llvm/CodeGen/Passes.h" 20 #include "llvm/IR/Constants.h" 21 #include "llvm/IR/DerivedTypes.h" 22 #include "llvm/IR/GlobalVariable.h" 23 #include "llvm/IR/Instructions.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/MC/MCObjectFileInfo.h" 26 #include "llvm/MC/MCSymbol.h" 27 #include "llvm/Support/Dwarf.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Target/TargetLoweringObjectFile.h" 30 #include "llvm/Target/TargetMachine.h" 31 using namespace llvm; 32 using namespace llvm::dwarf; 33 34 // Handle the Pass registration stuff necessary to use DataLayout's. 35 INITIALIZE_TM_PASS(MachineModuleInfo, "machinemoduleinfo", 36 "Machine Module Information", false, false) 37 char MachineModuleInfo::ID = 0; 38 39 // Out of line virtual method. 40 MachineModuleInfoImpl::~MachineModuleInfoImpl() {} 41 42 namespace llvm { 43 class MMIAddrLabelMapCallbackPtr final : CallbackVH { 44 MMIAddrLabelMap *Map; 45 public: 46 MMIAddrLabelMapCallbackPtr() : Map(nullptr) {} 47 MMIAddrLabelMapCallbackPtr(Value *V) : CallbackVH(V), Map(nullptr) {} 48 49 void setPtr(BasicBlock *BB) { 50 ValueHandleBase::operator=(BB); 51 } 52 53 void setMap(MMIAddrLabelMap *map) { Map = map; } 54 55 void deleted() override; 56 void allUsesReplacedWith(Value *V2) override; 57 }; 58 59 class MMIAddrLabelMap { 60 MCContext &Context; 61 struct AddrLabelSymEntry { 62 /// The symbols for the label. 63 TinyPtrVector<MCSymbol *> Symbols; 64 65 Function *Fn; // The containing function of the BasicBlock. 66 unsigned Index; // The index in BBCallbacks for the BasicBlock. 67 }; 68 69 DenseMap<AssertingVH<BasicBlock>, AddrLabelSymEntry> AddrLabelSymbols; 70 71 /// Callbacks for the BasicBlock's that we have entries for. We use this so 72 /// we get notified if a block is deleted or RAUWd. 73 std::vector<MMIAddrLabelMapCallbackPtr> BBCallbacks; 74 75 /// This is a per-function list of symbols whose corresponding BasicBlock got 76 /// deleted. These symbols need to be emitted at some point in the file, so 77 /// AsmPrinter emits them after the function body. 78 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> > 79 DeletedAddrLabelsNeedingEmission; 80 public: 81 82 MMIAddrLabelMap(MCContext &context) : Context(context) {} 83 ~MMIAddrLabelMap() { 84 assert(DeletedAddrLabelsNeedingEmission.empty() && 85 "Some labels for deleted blocks never got emitted"); 86 } 87 88 ArrayRef<MCSymbol *> getAddrLabelSymbolToEmit(BasicBlock *BB); 89 90 void takeDeletedSymbolsForFunction(Function *F, 91 std::vector<MCSymbol*> &Result); 92 93 void UpdateForDeletedBlock(BasicBlock *BB); 94 void UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New); 95 }; 96 } 97 98 ArrayRef<MCSymbol *> MMIAddrLabelMap::getAddrLabelSymbolToEmit(BasicBlock *BB) { 99 assert(BB->hasAddressTaken() && 100 "Shouldn't get label for block without address taken"); 101 AddrLabelSymEntry &Entry = AddrLabelSymbols[BB]; 102 103 // If we already had an entry for this block, just return it. 104 if (!Entry.Symbols.empty()) { 105 assert(BB->getParent() == Entry.Fn && "Parent changed"); 106 return Entry.Symbols; 107 } 108 109 // Otherwise, this is a new entry, create a new symbol for it and add an 110 // entry to BBCallbacks so we can be notified if the BB is deleted or RAUWd. 111 BBCallbacks.emplace_back(BB); 112 BBCallbacks.back().setMap(this); 113 Entry.Index = BBCallbacks.size() - 1; 114 Entry.Fn = BB->getParent(); 115 Entry.Symbols.push_back(Context.createTempSymbol()); 116 return Entry.Symbols; 117 } 118 119 /// If we have any deleted symbols for F, return them. 120 void MMIAddrLabelMap:: 121 takeDeletedSymbolsForFunction(Function *F, std::vector<MCSymbol*> &Result) { 122 DenseMap<AssertingVH<Function>, std::vector<MCSymbol*> >::iterator I = 123 DeletedAddrLabelsNeedingEmission.find(F); 124 125 // If there are no entries for the function, just return. 126 if (I == DeletedAddrLabelsNeedingEmission.end()) return; 127 128 // Otherwise, take the list. 129 std::swap(Result, I->second); 130 DeletedAddrLabelsNeedingEmission.erase(I); 131 } 132 133 134 void MMIAddrLabelMap::UpdateForDeletedBlock(BasicBlock *BB) { 135 // If the block got deleted, there is no need for the symbol. If the symbol 136 // was already emitted, we can just forget about it, otherwise we need to 137 // queue it up for later emission when the function is output. 138 AddrLabelSymEntry Entry = std::move(AddrLabelSymbols[BB]); 139 AddrLabelSymbols.erase(BB); 140 assert(!Entry.Symbols.empty() && "Didn't have a symbol, why a callback?"); 141 BBCallbacks[Entry.Index] = nullptr; // Clear the callback. 142 143 assert((BB->getParent() == nullptr || BB->getParent() == Entry.Fn) && 144 "Block/parent mismatch"); 145 146 for (MCSymbol *Sym : Entry.Symbols) { 147 if (Sym->isDefined()) 148 return; 149 150 // If the block is not yet defined, we need to emit it at the end of the 151 // function. Add the symbol to the DeletedAddrLabelsNeedingEmission list 152 // for the containing Function. Since the block is being deleted, its 153 // parent may already be removed, we have to get the function from 'Entry'. 154 DeletedAddrLabelsNeedingEmission[Entry.Fn].push_back(Sym); 155 } 156 } 157 158 void MMIAddrLabelMap::UpdateForRAUWBlock(BasicBlock *Old, BasicBlock *New) { 159 // Get the entry for the RAUW'd block and remove it from our map. 160 AddrLabelSymEntry OldEntry = std::move(AddrLabelSymbols[Old]); 161 AddrLabelSymbols.erase(Old); 162 assert(!OldEntry.Symbols.empty() && "Didn't have a symbol, why a callback?"); 163 164 AddrLabelSymEntry &NewEntry = AddrLabelSymbols[New]; 165 166 // If New is not address taken, just move our symbol over to it. 167 if (NewEntry.Symbols.empty()) { 168 BBCallbacks[OldEntry.Index].setPtr(New); // Update the callback. 169 NewEntry = std::move(OldEntry); // Set New's entry. 170 return; 171 } 172 173 BBCallbacks[OldEntry.Index] = nullptr; // Update the callback. 174 175 // Otherwise, we need to add the old symbols to the new block's set. 176 NewEntry.Symbols.insert(NewEntry.Symbols.end(), OldEntry.Symbols.begin(), 177 OldEntry.Symbols.end()); 178 } 179 180 181 void MMIAddrLabelMapCallbackPtr::deleted() { 182 Map->UpdateForDeletedBlock(cast<BasicBlock>(getValPtr())); 183 } 184 185 void MMIAddrLabelMapCallbackPtr::allUsesReplacedWith(Value *V2) { 186 Map->UpdateForRAUWBlock(cast<BasicBlock>(getValPtr()), cast<BasicBlock>(V2)); 187 } 188 189 190 //===----------------------------------------------------------------------===// 191 192 MachineModuleInfo::MachineModuleInfo(const TargetMachine *TM) 193 : ImmutablePass(ID), TM(*TM), 194 Context(TM->getMCAsmInfo(), TM->getMCRegisterInfo(), 195 TM->getObjFileLowering(), nullptr, false) { 196 initializeMachineModuleInfoPass(*PassRegistry::getPassRegistry()); 197 } 198 199 MachineModuleInfo::~MachineModuleInfo() { 200 } 201 202 bool MachineModuleInfo::doInitialization(Module &M) { 203 204 ObjFileMMI = nullptr; 205 CurCallSite = 0; 206 CallsEHReturn = false; 207 CallsUnwindInit = false; 208 HasEHFunclets = false; 209 DbgInfoAvailable = UsesVAFloatArgument = UsesMorestackAddr = false; 210 PersonalityTypeCache = EHPersonality::Unknown; 211 AddrLabelSymbols = nullptr; 212 TheModule = &M; 213 214 return false; 215 } 216 217 bool MachineModuleInfo::doFinalization(Module &M) { 218 219 Personalities.clear(); 220 221 delete AddrLabelSymbols; 222 AddrLabelSymbols = nullptr; 223 224 Context.reset(); 225 226 delete ObjFileMMI; 227 ObjFileMMI = nullptr; 228 229 return false; 230 } 231 232 void MachineModuleInfo::EndFunction() { 233 // Clean up exception info. 234 LandingPads.clear(); 235 PersonalityTypeCache = EHPersonality::Unknown; 236 CallSiteMap.clear(); 237 TypeInfos.clear(); 238 FilterIds.clear(); 239 FilterEnds.clear(); 240 CallsEHReturn = false; 241 CallsUnwindInit = false; 242 HasEHFunclets = false; 243 VariableDbgInfos.clear(); 244 } 245 246 //===- Address of Block Management ----------------------------------------===// 247 248 ArrayRef<MCSymbol *> 249 MachineModuleInfo::getAddrLabelSymbolToEmit(const BasicBlock *BB) { 250 // Lazily create AddrLabelSymbols. 251 if (!AddrLabelSymbols) 252 AddrLabelSymbols = new MMIAddrLabelMap(Context); 253 return AddrLabelSymbols->getAddrLabelSymbolToEmit(const_cast<BasicBlock*>(BB)); 254 } 255 256 void MachineModuleInfo:: 257 takeDeletedSymbolsForFunction(const Function *F, 258 std::vector<MCSymbol*> &Result) { 259 // If no blocks have had their addresses taken, we're done. 260 if (!AddrLabelSymbols) return; 261 return AddrLabelSymbols-> 262 takeDeletedSymbolsForFunction(const_cast<Function*>(F), Result); 263 } 264 265 //===- EH -----------------------------------------------------------------===// 266 267 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo 268 (MachineBasicBlock *LandingPad) { 269 unsigned N = LandingPads.size(); 270 for (unsigned i = 0; i < N; ++i) { 271 LandingPadInfo &LP = LandingPads[i]; 272 if (LP.LandingPadBlock == LandingPad) 273 return LP; 274 } 275 276 LandingPads.push_back(LandingPadInfo(LandingPad)); 277 return LandingPads[N]; 278 } 279 280 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad, 281 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 282 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 283 LP.BeginLabels.push_back(BeginLabel); 284 LP.EndLabels.push_back(EndLabel); 285 } 286 287 MCSymbol *MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) { 288 MCSymbol *LandingPadLabel = Context.createTempSymbol(); 289 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 290 LP.LandingPadLabel = LandingPadLabel; 291 return LandingPadLabel; 292 } 293 294 void MachineModuleInfo::addPersonality(const Function *Personality) { 295 for (unsigned i = 0; i < Personalities.size(); ++i) 296 if (Personalities[i] == Personality) 297 return; 298 Personalities.push_back(Personality); 299 } 300 301 void MachineModuleInfo:: 302 addCatchTypeInfo(MachineBasicBlock *LandingPad, 303 ArrayRef<const GlobalValue *> TyInfo) { 304 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 305 for (unsigned N = TyInfo.size(); N; --N) 306 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 307 } 308 309 void MachineModuleInfo:: 310 addFilterTypeInfo(MachineBasicBlock *LandingPad, 311 ArrayRef<const GlobalValue *> TyInfo) { 312 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 313 std::vector<unsigned> IdsInFilter(TyInfo.size()); 314 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 315 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 316 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 317 } 318 319 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) { 320 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 321 LP.TypeIds.push_back(0); 322 } 323 324 void MachineModuleInfo::addSEHCatchHandler(MachineBasicBlock *LandingPad, 325 const Function *Filter, 326 const BlockAddress *RecoverBA) { 327 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 328 SEHHandler Handler; 329 Handler.FilterOrFinally = Filter; 330 Handler.RecoverBA = RecoverBA; 331 LP.SEHHandlers.push_back(Handler); 332 } 333 334 void MachineModuleInfo::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 335 const Function *Cleanup) { 336 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 337 SEHHandler Handler; 338 Handler.FilterOrFinally = Cleanup; 339 Handler.RecoverBA = nullptr; 340 LP.SEHHandlers.push_back(Handler); 341 } 342 343 void MachineModuleInfo::TidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) { 344 for (unsigned i = 0; i != LandingPads.size(); ) { 345 LandingPadInfo &LandingPad = LandingPads[i]; 346 if (LandingPad.LandingPadLabel && 347 !LandingPad.LandingPadLabel->isDefined() && 348 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 349 LandingPad.LandingPadLabel = nullptr; 350 351 // Special case: we *should* emit LPs with null LP MBB. This indicates 352 // "nounwind" case. 353 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 354 LandingPads.erase(LandingPads.begin() + i); 355 continue; 356 } 357 358 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 359 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 360 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 361 if ((BeginLabel->isDefined() || 362 (LPMap && (*LPMap)[BeginLabel] != 0)) && 363 (EndLabel->isDefined() || 364 (LPMap && (*LPMap)[EndLabel] != 0))) continue; 365 366 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 367 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 368 --j; 369 --e; 370 } 371 372 // Remove landing pads with no try-ranges. 373 if (LandingPads[i].BeginLabels.empty()) { 374 LandingPads.erase(LandingPads.begin() + i); 375 continue; 376 } 377 378 // If there is no landing pad, ensure that the list of typeids is empty. 379 // If the only typeid is a cleanup, this is the same as having no typeids. 380 if (!LandingPad.LandingPadBlock || 381 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 382 LandingPad.TypeIds.clear(); 383 ++i; 384 } 385 } 386 387 void MachineModuleInfo::setCallSiteLandingPad(MCSymbol *Sym, 388 ArrayRef<unsigned> Sites) { 389 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 390 } 391 392 unsigned MachineModuleInfo::getTypeIDFor(const GlobalValue *TI) { 393 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 394 if (TypeInfos[i] == TI) return i + 1; 395 396 TypeInfos.push_back(TI); 397 return TypeInfos.size(); 398 } 399 400 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) { 401 // If the new filter coincides with the tail of an existing filter, then 402 // re-use the existing filter. Folding filters more than this requires 403 // re-ordering filters and/or their elements - probably not worth it. 404 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 405 E = FilterEnds.end(); I != E; ++I) { 406 unsigned i = *I, j = TyIds.size(); 407 408 while (i && j) 409 if (FilterIds[--i] != TyIds[--j]) 410 goto try_next; 411 412 if (!j) 413 // The new filter coincides with range [i, end) of the existing filter. 414 return -(1 + i); 415 416 try_next:; 417 } 418 419 // Add the new filter. 420 int FilterID = -(1 + FilterIds.size()); 421 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 422 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 423 FilterEnds.push_back(FilterIds.size()); 424 FilterIds.push_back(0); // terminator 425 return FilterID; 426 } 427 428 MachineFunction &MachineModuleInfo::getMachineFunction(const Function &F) { 429 // Shortcut for the common case where a sequence of MachineFunctionPasses 430 // all query for the same Function. 431 if (LastRequest == &F) 432 return *LastResult; 433 434 auto I = MachineFunctions.insert( 435 std::make_pair(&F, std::unique_ptr<MachineFunction>())); 436 MachineFunction *MF; 437 if (I.second) { 438 // No pre-existing machine function, create a new one. 439 MF = new MachineFunction(&F, TM, NextFnNum++, *this); 440 // Update the set entry. 441 I.first->second.reset(MF); 442 443 if (MFInitializer) 444 if (MFInitializer->initializeMachineFunction(*MF)) 445 report_fatal_error("Unable to initialize machine function"); 446 } else { 447 MF = I.first->second.get(); 448 } 449 450 LastRequest = &F; 451 LastResult = MF; 452 return *MF; 453 } 454 455 void MachineModuleInfo::deleteMachineFunctionFor(Function &F) { 456 MachineFunctions.erase(&F); 457 LastRequest = nullptr; 458 LastResult = nullptr; 459 } 460 461 namespace { 462 /// This pass frees the MachineFunction object associated with a Function. 463 class FreeMachineFunction : public FunctionPass { 464 public: 465 static char ID; 466 FreeMachineFunction() : FunctionPass(ID) {} 467 468 void getAnalysisUsage(AnalysisUsage &AU) const override { 469 AU.addRequired<MachineModuleInfo>(); 470 AU.addPreserved<MachineModuleInfo>(); 471 } 472 473 bool runOnFunction(Function &F) override { 474 MachineModuleInfo &MMI = getAnalysis<MachineModuleInfo>(); 475 MMI.deleteMachineFunctionFor(F); 476 return true; 477 } 478 }; 479 char FreeMachineFunction::ID; 480 } // end anonymous namespace 481 482 namespace llvm { 483 FunctionPass *createFreeMachineFunctionPass() { 484 return new FreeMachineFunction(); 485 } 486 } // end namespace llvm 487 488 //===- MMI building helpers -----------------------------------------------===// 489 490 void llvm::computeUsesVAFloatArgument(const CallInst &I, 491 MachineModuleInfo &MMI) { 492 FunctionType *FT = 493 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0)); 494 if (FT->isVarArg() && !MMI.usesVAFloatArgument()) { 495 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) { 496 Type *T = I.getArgOperand(i)->getType(); 497 for (auto i : post_order(T)) { 498 if (i->isFloatingPointTy()) { 499 MMI.setUsesVAFloatArgument(true); 500 return; 501 } 502 } 503 } 504 } 505 } 506 507 void llvm::addLandingPadInfo(const LandingPadInst &I, MachineModuleInfo &MMI, 508 MachineBasicBlock &MBB) { 509 if (const auto *PF = dyn_cast<Function>( 510 I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts())) 511 MMI.addPersonality(PF); 512 513 if (I.isCleanup()) 514 MMI.addCleanup(&MBB); 515 516 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct, 517 // but we need to do it this way because of how the DWARF EH emitter 518 // processes the clauses. 519 for (unsigned i = I.getNumClauses(); i != 0; --i) { 520 Value *Val = I.getClause(i - 1); 521 if (I.isCatch(i - 1)) { 522 MMI.addCatchTypeInfo(&MBB, 523 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 524 } else { 525 // Add filters in a list. 526 Constant *CVal = cast<Constant>(Val); 527 SmallVector<const GlobalValue *, 4> FilterList; 528 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end(); 529 II != IE; ++II) 530 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts())); 531 532 MMI.addFilterTypeInfo(&MBB, FilterList); 533 } 534 } 535 } 536