1 //===- MachineFunction.cpp ------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Collect native machine code information for a function. This allows 10 // target-specific information about the generated code to be stored with each 11 // function. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/MachineFunction.h" 16 #include "llvm/ADT/BitVector.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallString.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Analysis/ConstantFolding.h" 25 #include "llvm/Analysis/EHPersonalities.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineConstantPool.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineInstr.h" 30 #include "llvm/CodeGen/MachineJumpTableInfo.h" 31 #include "llvm/CodeGen/MachineMemOperand.h" 32 #include "llvm/CodeGen/MachineModuleInfo.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/PseudoSourceValue.h" 35 #include "llvm/CodeGen/TargetFrameLowering.h" 36 #include "llvm/CodeGen/TargetInstrInfo.h" 37 #include "llvm/CodeGen/TargetLowering.h" 38 #include "llvm/CodeGen/TargetRegisterInfo.h" 39 #include "llvm/CodeGen/TargetSubtargetInfo.h" 40 #include "llvm/CodeGen/WasmEHFuncInfo.h" 41 #include "llvm/CodeGen/WinEHFuncInfo.h" 42 #include "llvm/Config/llvm-config.h" 43 #include "llvm/IR/Attributes.h" 44 #include "llvm/IR/BasicBlock.h" 45 #include "llvm/IR/Constant.h" 46 #include "llvm/IR/DataLayout.h" 47 #include "llvm/IR/DebugInfoMetadata.h" 48 #include "llvm/IR/DerivedTypes.h" 49 #include "llvm/IR/Function.h" 50 #include "llvm/IR/GlobalValue.h" 51 #include "llvm/IR/Instruction.h" 52 #include "llvm/IR/Instructions.h" 53 #include "llvm/IR/Metadata.h" 54 #include "llvm/IR/Module.h" 55 #include "llvm/IR/ModuleSlotTracker.h" 56 #include "llvm/IR/Value.h" 57 #include "llvm/MC/MCContext.h" 58 #include "llvm/MC/MCSymbol.h" 59 #include "llvm/MC/SectionKind.h" 60 #include "llvm/Support/Casting.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/Compiler.h" 63 #include "llvm/Support/DOTGraphTraits.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/GraphWriter.h" 67 #include "llvm/Support/raw_ostream.h" 68 #include "llvm/Target/TargetMachine.h" 69 #include <algorithm> 70 #include <cassert> 71 #include <cstddef> 72 #include <cstdint> 73 #include <iterator> 74 #include <string> 75 #include <type_traits> 76 #include <utility> 77 #include <vector> 78 79 using namespace llvm; 80 81 #define DEBUG_TYPE "codegen" 82 83 static cl::opt<unsigned> AlignAllFunctions( 84 "align-all-functions", 85 cl::desc("Force the alignment of all functions in log2 format (e.g. 4 " 86 "means align on 16B boundaries)."), 87 cl::init(0), cl::Hidden); 88 89 static const char *getPropertyName(MachineFunctionProperties::Property Prop) { 90 using P = MachineFunctionProperties::Property; 91 92 switch(Prop) { 93 case P::FailedISel: return "FailedISel"; 94 case P::IsSSA: return "IsSSA"; 95 case P::Legalized: return "Legalized"; 96 case P::NoPHIs: return "NoPHIs"; 97 case P::NoVRegs: return "NoVRegs"; 98 case P::RegBankSelected: return "RegBankSelected"; 99 case P::Selected: return "Selected"; 100 case P::TracksLiveness: return "TracksLiveness"; 101 case P::TiedOpsRewritten: return "TiedOpsRewritten"; 102 } 103 llvm_unreachable("Invalid machine function property"); 104 } 105 106 // Pin the vtable to this file. 107 void MachineFunction::Delegate::anchor() {} 108 109 void MachineFunctionProperties::print(raw_ostream &OS) const { 110 const char *Separator = ""; 111 for (BitVector::size_type I = 0; I < Properties.size(); ++I) { 112 if (!Properties[I]) 113 continue; 114 OS << Separator << getPropertyName(static_cast<Property>(I)); 115 Separator = ", "; 116 } 117 } 118 119 //===----------------------------------------------------------------------===// 120 // MachineFunction implementation 121 //===----------------------------------------------------------------------===// 122 123 // Out-of-line virtual method. 124 MachineFunctionInfo::~MachineFunctionInfo() = default; 125 126 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 127 MBB->getParent()->DeleteMachineBasicBlock(MBB); 128 } 129 130 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, 131 const Function &F) { 132 if (F.hasFnAttribute(Attribute::StackAlignment)) 133 return F.getFnStackAlignment(); 134 return STI->getFrameLowering()->getStackAlign().value(); 135 } 136 137 MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target, 138 const TargetSubtargetInfo &STI, 139 unsigned FunctionNum, MachineModuleInfo &mmi) 140 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) { 141 FunctionNumber = FunctionNum; 142 init(); 143 } 144 145 void MachineFunction::handleInsertion(MachineInstr &MI) { 146 if (TheDelegate) 147 TheDelegate->MF_HandleInsertion(MI); 148 } 149 150 void MachineFunction::handleRemoval(MachineInstr &MI) { 151 if (TheDelegate) 152 TheDelegate->MF_HandleRemoval(MI); 153 } 154 155 void MachineFunction::init() { 156 // Assume the function starts in SSA form with correct liveness. 157 Properties.set(MachineFunctionProperties::Property::IsSSA); 158 Properties.set(MachineFunctionProperties::Property::TracksLiveness); 159 if (STI->getRegisterInfo()) 160 RegInfo = new (Allocator) MachineRegisterInfo(this); 161 else 162 RegInfo = nullptr; 163 164 MFInfo = nullptr; 165 // We can realign the stack if the target supports it and the user hasn't 166 // explicitly asked us not to. 167 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() && 168 !F.hasFnAttribute("no-realign-stack"); 169 FrameInfo = new (Allocator) MachineFrameInfo( 170 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP, 171 /*ForcedRealign=*/CanRealignSP && 172 F.hasFnAttribute(Attribute::StackAlignment)); 173 174 if (F.hasFnAttribute(Attribute::StackAlignment)) 175 FrameInfo->ensureMaxAlignment(*F.getFnStackAlign()); 176 177 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout()); 178 Alignment = STI->getTargetLowering()->getMinFunctionAlignment(); 179 180 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F. 181 // FIXME: Use Function::hasOptSize(). 182 if (!F.hasFnAttribute(Attribute::OptimizeForSize)) 183 Alignment = std::max(Alignment, 184 STI->getTargetLowering()->getPrefFunctionAlignment()); 185 186 if (AlignAllFunctions) 187 Alignment = Align(1ULL << AlignAllFunctions); 188 189 JumpTableInfo = nullptr; 190 191 if (isFuncletEHPersonality(classifyEHPersonality( 192 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 193 WinEHInfo = new (Allocator) WinEHFuncInfo(); 194 } 195 196 if (isScopedEHPersonality(classifyEHPersonality( 197 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 198 WasmEHInfo = new (Allocator) WasmEHFuncInfo(); 199 } 200 201 assert(Target.isCompatibleDataLayout(getDataLayout()) && 202 "Can't create a MachineFunction using a Module with a " 203 "Target-incompatible DataLayout attached\n"); 204 205 PSVManager = 206 std::make_unique<PseudoSourceValueManager>(*(getSubtarget(). 207 getInstrInfo())); 208 } 209 210 MachineFunction::~MachineFunction() { 211 clear(); 212 } 213 214 void MachineFunction::clear() { 215 Properties.reset(); 216 // Don't call destructors on MachineInstr and MachineOperand. All of their 217 // memory comes from the BumpPtrAllocator which is about to be purged. 218 // 219 // Do call MachineBasicBlock destructors, it contains std::vectors. 220 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I)) 221 I->Insts.clearAndLeakNodesUnsafely(); 222 MBBNumbering.clear(); 223 224 InstructionRecycler.clear(Allocator); 225 OperandRecycler.clear(Allocator); 226 BasicBlockRecycler.clear(Allocator); 227 CodeViewAnnotations.clear(); 228 VariableDbgInfos.clear(); 229 if (RegInfo) { 230 RegInfo->~MachineRegisterInfo(); 231 Allocator.Deallocate(RegInfo); 232 } 233 if (MFInfo) { 234 MFInfo->~MachineFunctionInfo(); 235 Allocator.Deallocate(MFInfo); 236 } 237 238 FrameInfo->~MachineFrameInfo(); 239 Allocator.Deallocate(FrameInfo); 240 241 ConstantPool->~MachineConstantPool(); 242 Allocator.Deallocate(ConstantPool); 243 244 if (JumpTableInfo) { 245 JumpTableInfo->~MachineJumpTableInfo(); 246 Allocator.Deallocate(JumpTableInfo); 247 } 248 249 if (WinEHInfo) { 250 WinEHInfo->~WinEHFuncInfo(); 251 Allocator.Deallocate(WinEHInfo); 252 } 253 254 if (WasmEHInfo) { 255 WasmEHInfo->~WasmEHFuncInfo(); 256 Allocator.Deallocate(WasmEHInfo); 257 } 258 } 259 260 const DataLayout &MachineFunction::getDataLayout() const { 261 return F.getParent()->getDataLayout(); 262 } 263 264 /// Get the JumpTableInfo for this function. 265 /// If it does not already exist, allocate one. 266 MachineJumpTableInfo *MachineFunction:: 267 getOrCreateJumpTableInfo(unsigned EntryKind) { 268 if (JumpTableInfo) return JumpTableInfo; 269 270 JumpTableInfo = new (Allocator) 271 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind); 272 return JumpTableInfo; 273 } 274 275 DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const { 276 if (&FPType == &APFloat::IEEEsingle()) { 277 Attribute Attr = F.getFnAttribute("denormal-fp-math-f32"); 278 StringRef Val = Attr.getValueAsString(); 279 if (!Val.empty()) 280 return parseDenormalFPAttribute(Val); 281 282 // If the f32 variant of the attribute isn't specified, try to use the 283 // generic one. 284 } 285 286 // TODO: Should probably avoid the connection to the IR and store directly 287 // in the MachineFunction. 288 Attribute Attr = F.getFnAttribute("denormal-fp-math"); 289 return parseDenormalFPAttribute(Attr.getValueAsString()); 290 } 291 292 /// Should we be emitting segmented stack stuff for the function 293 bool MachineFunction::shouldSplitStack() const { 294 return getFunction().hasFnAttribute("split-stack"); 295 } 296 297 LLVM_NODISCARD unsigned 298 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) { 299 FrameInstructions.push_back(Inst); 300 return FrameInstructions.size() - 1; 301 } 302 303 /// This discards all of the MachineBasicBlock numbers and recomputes them. 304 /// This guarantees that the MBB numbers are sequential, dense, and match the 305 /// ordering of the blocks within the function. If a specific MachineBasicBlock 306 /// is specified, only that block and those after it are renumbered. 307 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 308 if (empty()) { MBBNumbering.clear(); return; } 309 MachineFunction::iterator MBBI, E = end(); 310 if (MBB == nullptr) 311 MBBI = begin(); 312 else 313 MBBI = MBB->getIterator(); 314 315 // Figure out the block number this should have. 316 unsigned BlockNo = 0; 317 if (MBBI != begin()) 318 BlockNo = std::prev(MBBI)->getNumber() + 1; 319 320 for (; MBBI != E; ++MBBI, ++BlockNo) { 321 if (MBBI->getNumber() != (int)BlockNo) { 322 // Remove use of the old number. 323 if (MBBI->getNumber() != -1) { 324 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 325 "MBB number mismatch!"); 326 MBBNumbering[MBBI->getNumber()] = nullptr; 327 } 328 329 // If BlockNo is already taken, set that block's number to -1. 330 if (MBBNumbering[BlockNo]) 331 MBBNumbering[BlockNo]->setNumber(-1); 332 333 MBBNumbering[BlockNo] = &*MBBI; 334 MBBI->setNumber(BlockNo); 335 } 336 } 337 338 // Okay, all the blocks are renumbered. If we have compactified the block 339 // numbering, shrink MBBNumbering now. 340 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 341 MBBNumbering.resize(BlockNo); 342 } 343 344 /// This is used with -fbasic-block-sections or -fbasicblock-labels option. 345 /// A unary encoding of basic block labels is done to keep ".strtab" sizes 346 /// small. 347 void MachineFunction::createBBLabels() { 348 const TargetInstrInfo *TII = getSubtarget().getInstrInfo(); 349 this->BBSectionsSymbolPrefix.resize(getNumBlockIDs(), 'a'); 350 for (auto MBBI = begin(), E = end(); MBBI != E; ++MBBI) { 351 assert( 352 (MBBI->getNumber() >= 0 && MBBI->getNumber() < (int)getNumBlockIDs()) && 353 "BasicBlock number was out of range!"); 354 // 'a' - Normal block. 355 // 'r' - Return block. 356 // 'l' - Landing Pad. 357 // 'L' - Return and landing pad. 358 bool isEHPad = MBBI->isEHPad(); 359 bool isRetBlock = MBBI->isReturnBlock() && !TII->isTailCall(MBBI->back()); 360 char type = 'a'; 361 if (isEHPad && isRetBlock) 362 type = 'L'; 363 else if (isEHPad) 364 type = 'l'; 365 else if (isRetBlock) 366 type = 'r'; 367 BBSectionsSymbolPrefix[MBBI->getNumber()] = type; 368 } 369 } 370 371 /// This method iterates over the basic blocks and assigns their IsBeginSection 372 /// and IsEndSection fields. This must be called after MBB layout is finalized 373 /// and the SectionID's are assigned to MBBs. 374 void MachineFunction::assignBeginEndSections() { 375 front().setIsBeginSection(); 376 auto CurrentSectionID = front().getSectionID(); 377 for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) { 378 if (MBBI->getSectionID() == CurrentSectionID) 379 continue; 380 MBBI->setIsBeginSection(); 381 std::prev(MBBI)->setIsEndSection(); 382 CurrentSectionID = MBBI->getSectionID(); 383 } 384 back().setIsEndSection(); 385 } 386 387 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 388 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 389 const DebugLoc &DL, 390 bool NoImp) { 391 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 392 MachineInstr(*this, MCID, DL, NoImp); 393 } 394 395 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 396 /// identical in all ways except the instruction has no parent, prev, or next. 397 MachineInstr * 398 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 399 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 400 MachineInstr(*this, *Orig); 401 } 402 403 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB, 404 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) { 405 MachineInstr *FirstClone = nullptr; 406 MachineBasicBlock::const_instr_iterator I = Orig.getIterator(); 407 while (true) { 408 MachineInstr *Cloned = CloneMachineInstr(&*I); 409 MBB.insert(InsertBefore, Cloned); 410 if (FirstClone == nullptr) { 411 FirstClone = Cloned; 412 } else { 413 Cloned->bundleWithPred(); 414 } 415 416 if (!I->isBundledWithSucc()) 417 break; 418 ++I; 419 } 420 // Copy over call site info to the cloned instruction if needed. If Orig is in 421 // a bundle, copyCallSiteInfo takes care of finding the call instruction in 422 // the bundle. 423 if (Orig.shouldUpdateCallSiteInfo()) 424 copyCallSiteInfo(&Orig, FirstClone); 425 return *FirstClone; 426 } 427 428 /// Delete the given MachineInstr. 429 /// 430 /// This function also serves as the MachineInstr destructor - the real 431 /// ~MachineInstr() destructor must be empty. 432 void 433 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 434 // Verify that a call site info is at valid state. This assertion should 435 // be triggered during the implementation of support for the 436 // call site info of a new architecture. If the assertion is triggered, 437 // back trace will tell where to insert a call to updateCallSiteInfo(). 438 assert((!MI->isCandidateForCallSiteEntry() || 439 CallSitesInfo.find(MI) == CallSitesInfo.end()) && 440 "Call site info was not updated!"); 441 // Strip it for parts. The operand array and the MI object itself are 442 // independently recyclable. 443 if (MI->Operands) 444 deallocateOperandArray(MI->CapOperands, MI->Operands); 445 // Don't call ~MachineInstr() which must be trivial anyway because 446 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 447 // destructors. 448 InstructionRecycler.Deallocate(Allocator, MI); 449 } 450 451 /// Allocate a new MachineBasicBlock. Use this instead of 452 /// `new MachineBasicBlock'. 453 MachineBasicBlock * 454 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 455 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 456 MachineBasicBlock(*this, bb); 457 } 458 459 /// Delete the given MachineBasicBlock. 460 void 461 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 462 assert(MBB->getParent() == this && "MBB parent mismatch!"); 463 MBB->~MachineBasicBlock(); 464 BasicBlockRecycler.Deallocate(Allocator, MBB); 465 } 466 467 MachineMemOperand *MachineFunction::getMachineMemOperand( 468 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 469 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 470 SyncScope::ID SSID, AtomicOrdering Ordering, 471 AtomicOrdering FailureOrdering) { 472 return new (Allocator) 473 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges, 474 SSID, Ordering, FailureOrdering); 475 } 476 477 MachineMemOperand *MachineFunction::getMachineMemOperand( 478 const MachineMemOperand *MMO, MachinePointerInfo &PtrInfo, uint64_t Size) { 479 return new (Allocator) MachineMemOperand( 480 PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(), AAMDNodes(), nullptr, 481 MMO->getSyncScopeID(), MMO->getOrdering(), MMO->getFailureOrdering()); 482 } 483 484 MachineMemOperand * 485 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 486 int64_t Offset, uint64_t Size) { 487 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo(); 488 489 // If there is no pointer value, the offset isn't tracked so we need to adjust 490 // the base alignment. 491 Align Alignment = PtrInfo.V.isNull() 492 ? commonAlignment(MMO->getBaseAlign(), Offset) 493 : MMO->getBaseAlign(); 494 495 // Do not preserve ranges, since we don't necessarily know what the high bits 496 // are anymore. 497 return new (Allocator) 498 MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size, 499 Alignment, MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(), 500 MMO->getOrdering(), MMO->getFailureOrdering()); 501 } 502 503 MachineMemOperand * 504 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 505 const AAMDNodes &AAInfo) { 506 MachinePointerInfo MPI = MMO->getValue() ? 507 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) : 508 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()); 509 510 return new (Allocator) MachineMemOperand( 511 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo, 512 MMO->getRanges(), MMO->getSyncScopeID(), MMO->getOrdering(), 513 MMO->getFailureOrdering()); 514 } 515 516 MachineMemOperand * 517 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 518 MachineMemOperand::Flags Flags) { 519 return new (Allocator) MachineMemOperand( 520 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(), 521 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(), 522 MMO->getOrdering(), MMO->getFailureOrdering()); 523 } 524 525 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo( 526 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol, 527 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) { 528 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol, 529 PostInstrSymbol, HeapAllocMarker); 530 } 531 532 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 533 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 534 llvm::copy(Name, Dest); 535 Dest[Name.size()] = 0; 536 return Dest; 537 } 538 539 uint32_t *MachineFunction::allocateRegMask() { 540 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs(); 541 unsigned Size = MachineOperand::getRegMaskSize(NumRegs); 542 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size); 543 memset(Mask, 0, Size * sizeof(Mask[0])); 544 return Mask; 545 } 546 547 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) { 548 int* AllocMask = Allocator.Allocate<int>(Mask.size()); 549 copy(Mask, AllocMask); 550 return {AllocMask, Mask.size()}; 551 } 552 553 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 554 LLVM_DUMP_METHOD void MachineFunction::dump() const { 555 print(dbgs()); 556 } 557 #endif 558 559 StringRef MachineFunction::getName() const { 560 return getFunction().getName(); 561 } 562 563 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 564 OS << "# Machine code for function " << getName() << ": "; 565 getProperties().print(OS); 566 OS << '\n'; 567 568 // Print Frame Information 569 FrameInfo->print(*this, OS); 570 571 // Print JumpTable Information 572 if (JumpTableInfo) 573 JumpTableInfo->print(OS); 574 575 // Print Constant Pool 576 ConstantPool->print(OS); 577 578 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 579 580 if (RegInfo && !RegInfo->livein_empty()) { 581 OS << "Function Live Ins: "; 582 for (MachineRegisterInfo::livein_iterator 583 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 584 OS << printReg(I->first, TRI); 585 if (I->second) 586 OS << " in " << printReg(I->second, TRI); 587 if (std::next(I) != E) 588 OS << ", "; 589 } 590 OS << '\n'; 591 } 592 593 ModuleSlotTracker MST(getFunction().getParent()); 594 MST.incorporateFunction(getFunction()); 595 for (const auto &BB : *this) { 596 OS << '\n'; 597 // If we print the whole function, print it at its most verbose level. 598 BB.print(OS, MST, Indexes, /*IsStandalone=*/true); 599 } 600 601 OS << "\n# End machine code for function " << getName() << ".\n\n"; 602 } 603 604 /// True if this function needs frame moves for debug or exceptions. 605 bool MachineFunction::needsFrameMoves() const { 606 return getMMI().hasDebugInfo() || 607 getTarget().Options.ForceDwarfFrameSection || 608 F.needsUnwindTableEntry(); 609 } 610 611 namespace llvm { 612 613 template<> 614 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 615 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 616 617 static std::string getGraphName(const MachineFunction *F) { 618 return ("CFG for '" + F->getName() + "' function").str(); 619 } 620 621 std::string getNodeLabel(const MachineBasicBlock *Node, 622 const MachineFunction *Graph) { 623 std::string OutStr; 624 { 625 raw_string_ostream OSS(OutStr); 626 627 if (isSimple()) { 628 OSS << printMBBReference(*Node); 629 if (const BasicBlock *BB = Node->getBasicBlock()) 630 OSS << ": " << BB->getName(); 631 } else 632 Node->print(OSS); 633 } 634 635 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 636 637 // Process string output to make it nicer... 638 for (unsigned i = 0; i != OutStr.length(); ++i) 639 if (OutStr[i] == '\n') { // Left justify 640 OutStr[i] = '\\'; 641 OutStr.insert(OutStr.begin()+i+1, 'l'); 642 } 643 return OutStr; 644 } 645 }; 646 647 } // end namespace llvm 648 649 void MachineFunction::viewCFG() const 650 { 651 #ifndef NDEBUG 652 ViewGraph(this, "mf" + getName()); 653 #else 654 errs() << "MachineFunction::viewCFG is only available in debug builds on " 655 << "systems with Graphviz or gv!\n"; 656 #endif // NDEBUG 657 } 658 659 void MachineFunction::viewCFGOnly() const 660 { 661 #ifndef NDEBUG 662 ViewGraph(this, "mf" + getName(), true); 663 #else 664 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 665 << "systems with Graphviz or gv!\n"; 666 #endif // NDEBUG 667 } 668 669 /// Add the specified physical register as a live-in value and 670 /// create a corresponding virtual register for it. 671 Register MachineFunction::addLiveIn(MCRegister PReg, 672 const TargetRegisterClass *RC) { 673 MachineRegisterInfo &MRI = getRegInfo(); 674 Register VReg = MRI.getLiveInVirtReg(PReg); 675 if (VReg) { 676 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 677 (void)VRegRC; 678 // A physical register can be added several times. 679 // Between two calls, the register class of the related virtual register 680 // may have been constrained to match some operation constraints. 681 // In that case, check that the current register class includes the 682 // physical register and is a sub class of the specified RC. 683 assert((VRegRC == RC || (VRegRC->contains(PReg) && 684 RC->hasSubClassEq(VRegRC))) && 685 "Register class mismatch!"); 686 return VReg; 687 } 688 VReg = MRI.createVirtualRegister(RC); 689 MRI.addLiveIn(PReg, VReg); 690 return VReg; 691 } 692 693 /// Return the MCSymbol for the specified non-empty jump table. 694 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 695 /// normal 'L' label is returned. 696 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 697 bool isLinkerPrivate) const { 698 const DataLayout &DL = getDataLayout(); 699 assert(JumpTableInfo && "No jump tables"); 700 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 701 702 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 703 : DL.getPrivateGlobalPrefix(); 704 SmallString<60> Name; 705 raw_svector_ostream(Name) 706 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 707 return Ctx.getOrCreateSymbol(Name); 708 } 709 710 /// Return a function-local symbol to represent the PIC base. 711 MCSymbol *MachineFunction::getPICBaseSymbol() const { 712 const DataLayout &DL = getDataLayout(); 713 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 714 Twine(getFunctionNumber()) + "$pb"); 715 } 716 717 /// \name Exception Handling 718 /// \{ 719 720 LandingPadInfo & 721 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) { 722 unsigned N = LandingPads.size(); 723 for (unsigned i = 0; i < N; ++i) { 724 LandingPadInfo &LP = LandingPads[i]; 725 if (LP.LandingPadBlock == LandingPad) 726 return LP; 727 } 728 729 LandingPads.push_back(LandingPadInfo(LandingPad)); 730 return LandingPads[N]; 731 } 732 733 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad, 734 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 735 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 736 LP.BeginLabels.push_back(BeginLabel); 737 LP.EndLabels.push_back(EndLabel); 738 } 739 740 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) { 741 MCSymbol *LandingPadLabel = Ctx.createTempSymbol(); 742 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 743 LP.LandingPadLabel = LandingPadLabel; 744 745 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI(); 746 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) { 747 if (const auto *PF = 748 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts())) 749 getMMI().addPersonality(PF); 750 751 if (LPI->isCleanup()) 752 addCleanup(LandingPad); 753 754 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% 755 // correct, but we need to do it this way because of how the DWARF EH 756 // emitter processes the clauses. 757 for (unsigned I = LPI->getNumClauses(); I != 0; --I) { 758 Value *Val = LPI->getClause(I - 1); 759 if (LPI->isCatch(I - 1)) { 760 addCatchTypeInfo(LandingPad, 761 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 762 } else { 763 // Add filters in a list. 764 auto *CVal = cast<Constant>(Val); 765 SmallVector<const GlobalValue *, 4> FilterList; 766 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end(); 767 II != IE; ++II) 768 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts())); 769 770 addFilterTypeInfo(LandingPad, FilterList); 771 } 772 } 773 774 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) { 775 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) { 776 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts(); 777 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo)); 778 } 779 780 } else { 781 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!"); 782 } 783 784 return LandingPadLabel; 785 } 786 787 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad, 788 ArrayRef<const GlobalValue *> TyInfo) { 789 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 790 for (unsigned N = TyInfo.size(); N; --N) 791 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 792 } 793 794 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad, 795 ArrayRef<const GlobalValue *> TyInfo) { 796 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 797 std::vector<unsigned> IdsInFilter(TyInfo.size()); 798 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 799 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 800 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 801 } 802 803 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap, 804 bool TidyIfNoBeginLabels) { 805 for (unsigned i = 0; i != LandingPads.size(); ) { 806 LandingPadInfo &LandingPad = LandingPads[i]; 807 if (LandingPad.LandingPadLabel && 808 !LandingPad.LandingPadLabel->isDefined() && 809 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 810 LandingPad.LandingPadLabel = nullptr; 811 812 // Special case: we *should* emit LPs with null LP MBB. This indicates 813 // "nounwind" case. 814 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 815 LandingPads.erase(LandingPads.begin() + i); 816 continue; 817 } 818 819 if (TidyIfNoBeginLabels) { 820 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 821 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 822 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 823 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) && 824 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0))) 825 continue; 826 827 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 828 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 829 --j; 830 --e; 831 } 832 833 // Remove landing pads with no try-ranges. 834 if (LandingPads[i].BeginLabels.empty()) { 835 LandingPads.erase(LandingPads.begin() + i); 836 continue; 837 } 838 } 839 840 // If there is no landing pad, ensure that the list of typeids is empty. 841 // If the only typeid is a cleanup, this is the same as having no typeids. 842 if (!LandingPad.LandingPadBlock || 843 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 844 LandingPad.TypeIds.clear(); 845 ++i; 846 } 847 } 848 849 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) { 850 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 851 LP.TypeIds.push_back(0); 852 } 853 854 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad, 855 const Function *Filter, 856 const BlockAddress *RecoverBA) { 857 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 858 SEHHandler Handler; 859 Handler.FilterOrFinally = Filter; 860 Handler.RecoverBA = RecoverBA; 861 LP.SEHHandlers.push_back(Handler); 862 } 863 864 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 865 const Function *Cleanup) { 866 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 867 SEHHandler Handler; 868 Handler.FilterOrFinally = Cleanup; 869 Handler.RecoverBA = nullptr; 870 LP.SEHHandlers.push_back(Handler); 871 } 872 873 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym, 874 ArrayRef<unsigned> Sites) { 875 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 876 } 877 878 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) { 879 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 880 if (TypeInfos[i] == TI) return i + 1; 881 882 TypeInfos.push_back(TI); 883 return TypeInfos.size(); 884 } 885 886 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) { 887 // If the new filter coincides with the tail of an existing filter, then 888 // re-use the existing filter. Folding filters more than this requires 889 // re-ordering filters and/or their elements - probably not worth it. 890 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 891 E = FilterEnds.end(); I != E; ++I) { 892 unsigned i = *I, j = TyIds.size(); 893 894 while (i && j) 895 if (FilterIds[--i] != TyIds[--j]) 896 goto try_next; 897 898 if (!j) 899 // The new filter coincides with range [i, end) of the existing filter. 900 return -(1 + i); 901 902 try_next:; 903 } 904 905 // Add the new filter. 906 int FilterID = -(1 + FilterIds.size()); 907 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 908 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 909 FilterEnds.push_back(FilterIds.size()); 910 FilterIds.push_back(0); // terminator 911 return FilterID; 912 } 913 914 MachineFunction::CallSiteInfoMap::iterator 915 MachineFunction::getCallSiteInfo(const MachineInstr *MI) { 916 assert(MI->isCandidateForCallSiteEntry() && 917 "Call site info refers only to call (MI) candidates"); 918 919 if (!Target.Options.EmitCallSiteInfo) 920 return CallSitesInfo.end(); 921 return CallSitesInfo.find(MI); 922 } 923 924 /// Return the call machine instruction or find a call within bundle. 925 static const MachineInstr *getCallInstr(const MachineInstr *MI) { 926 if (!MI->isBundle()) 927 return MI; 928 929 for (auto &BMI : make_range(getBundleStart(MI->getIterator()), 930 getBundleEnd(MI->getIterator()))) 931 if (BMI.isCandidateForCallSiteEntry()) 932 return &BMI; 933 934 llvm_unreachable("Unexpected bundle without a call site candidate"); 935 } 936 937 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) { 938 assert(MI->shouldUpdateCallSiteInfo() && 939 "Call site info refers only to call (MI) candidates or " 940 "candidates inside bundles"); 941 942 const MachineInstr *CallMI = getCallInstr(MI); 943 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI); 944 if (CSIt == CallSitesInfo.end()) 945 return; 946 CallSitesInfo.erase(CSIt); 947 } 948 949 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old, 950 const MachineInstr *New) { 951 assert(Old->shouldUpdateCallSiteInfo() && 952 "Call site info refers only to call (MI) candidates or " 953 "candidates inside bundles"); 954 955 if (!New->isCandidateForCallSiteEntry()) 956 return eraseCallSiteInfo(Old); 957 958 const MachineInstr *OldCallMI = getCallInstr(Old); 959 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 960 if (CSIt == CallSitesInfo.end()) 961 return; 962 963 CallSiteInfo CSInfo = CSIt->second; 964 CallSitesInfo[New] = CSInfo; 965 } 966 967 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old, 968 const MachineInstr *New) { 969 assert(Old->shouldUpdateCallSiteInfo() && 970 "Call site info refers only to call (MI) candidates or " 971 "candidates inside bundles"); 972 973 if (!New->isCandidateForCallSiteEntry()) 974 return eraseCallSiteInfo(Old); 975 976 const MachineInstr *OldCallMI = getCallInstr(Old); 977 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 978 if (CSIt == CallSitesInfo.end()) 979 return; 980 981 CallSiteInfo CSInfo = std::move(CSIt->second); 982 CallSitesInfo.erase(CSIt); 983 CallSitesInfo[New] = CSInfo; 984 } 985 986 /// \} 987 988 //===----------------------------------------------------------------------===// 989 // MachineJumpTableInfo implementation 990 //===----------------------------------------------------------------------===// 991 992 /// Return the size of each entry in the jump table. 993 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 994 // The size of a jump table entry is 4 bytes unless the entry is just the 995 // address of a block, in which case it is the pointer size. 996 switch (getEntryKind()) { 997 case MachineJumpTableInfo::EK_BlockAddress: 998 return TD.getPointerSize(); 999 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 1000 return 8; 1001 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1002 case MachineJumpTableInfo::EK_LabelDifference32: 1003 case MachineJumpTableInfo::EK_Custom32: 1004 return 4; 1005 case MachineJumpTableInfo::EK_Inline: 1006 return 0; 1007 } 1008 llvm_unreachable("Unknown jump table encoding!"); 1009 } 1010 1011 /// Return the alignment of each entry in the jump table. 1012 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 1013 // The alignment of a jump table entry is the alignment of int32 unless the 1014 // entry is just the address of a block, in which case it is the pointer 1015 // alignment. 1016 switch (getEntryKind()) { 1017 case MachineJumpTableInfo::EK_BlockAddress: 1018 return TD.getPointerABIAlignment(0).value(); 1019 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 1020 return TD.getABIIntegerTypeAlignment(64).value(); 1021 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1022 case MachineJumpTableInfo::EK_LabelDifference32: 1023 case MachineJumpTableInfo::EK_Custom32: 1024 return TD.getABIIntegerTypeAlignment(32).value(); 1025 case MachineJumpTableInfo::EK_Inline: 1026 return 1; 1027 } 1028 llvm_unreachable("Unknown jump table encoding!"); 1029 } 1030 1031 /// Create a new jump table entry in the jump table info. 1032 unsigned MachineJumpTableInfo::createJumpTableIndex( 1033 const std::vector<MachineBasicBlock*> &DestBBs) { 1034 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 1035 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 1036 return JumpTables.size()-1; 1037 } 1038 1039 /// If Old is the target of any jump tables, update the jump tables to branch 1040 /// to New instead. 1041 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 1042 MachineBasicBlock *New) { 1043 assert(Old != New && "Not making a change?"); 1044 bool MadeChange = false; 1045 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 1046 ReplaceMBBInJumpTable(i, Old, New); 1047 return MadeChange; 1048 } 1049 1050 /// If Old is a target of the jump tables, update the jump table to branch to 1051 /// New instead. 1052 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 1053 MachineBasicBlock *Old, 1054 MachineBasicBlock *New) { 1055 assert(Old != New && "Not making a change?"); 1056 bool MadeChange = false; 1057 MachineJumpTableEntry &JTE = JumpTables[Idx]; 1058 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 1059 if (JTE.MBBs[j] == Old) { 1060 JTE.MBBs[j] = New; 1061 MadeChange = true; 1062 } 1063 return MadeChange; 1064 } 1065 1066 void MachineJumpTableInfo::print(raw_ostream &OS) const { 1067 if (JumpTables.empty()) return; 1068 1069 OS << "Jump Tables:\n"; 1070 1071 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 1072 OS << printJumpTableEntryReference(i) << ':'; 1073 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) 1074 OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]); 1075 if (i != e) 1076 OS << '\n'; 1077 } 1078 1079 OS << '\n'; 1080 } 1081 1082 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1083 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 1084 #endif 1085 1086 Printable llvm::printJumpTableEntryReference(unsigned Idx) { 1087 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; }); 1088 } 1089 1090 //===----------------------------------------------------------------------===// 1091 // MachineConstantPool implementation 1092 //===----------------------------------------------------------------------===// 1093 1094 void MachineConstantPoolValue::anchor() {} 1095 1096 Type *MachineConstantPoolEntry::getType() const { 1097 if (isMachineConstantPoolEntry()) 1098 return Val.MachineCPVal->getType(); 1099 return Val.ConstVal->getType(); 1100 } 1101 1102 bool MachineConstantPoolEntry::needsRelocation() const { 1103 if (isMachineConstantPoolEntry()) 1104 return true; 1105 return Val.ConstVal->needsRelocation(); 1106 } 1107 1108 SectionKind 1109 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 1110 if (needsRelocation()) 1111 return SectionKind::getReadOnlyWithRel(); 1112 switch (DL->getTypeAllocSize(getType())) { 1113 case 4: 1114 return SectionKind::getMergeableConst4(); 1115 case 8: 1116 return SectionKind::getMergeableConst8(); 1117 case 16: 1118 return SectionKind::getMergeableConst16(); 1119 case 32: 1120 return SectionKind::getMergeableConst32(); 1121 default: 1122 return SectionKind::getReadOnly(); 1123 } 1124 } 1125 1126 MachineConstantPool::~MachineConstantPool() { 1127 // A constant may be a member of both Constants and MachineCPVsSharingEntries, 1128 // so keep track of which we've deleted to avoid double deletions. 1129 DenseSet<MachineConstantPoolValue*> Deleted; 1130 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1131 if (Constants[i].isMachineConstantPoolEntry()) { 1132 Deleted.insert(Constants[i].Val.MachineCPVal); 1133 delete Constants[i].Val.MachineCPVal; 1134 } 1135 for (DenseSet<MachineConstantPoolValue*>::iterator I = 1136 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); 1137 I != E; ++I) { 1138 if (Deleted.count(*I) == 0) 1139 delete *I; 1140 } 1141 } 1142 1143 /// Test whether the given two constants can be allocated the same constant pool 1144 /// entry. 1145 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 1146 const DataLayout &DL) { 1147 // Handle the trivial case quickly. 1148 if (A == B) return true; 1149 1150 // If they have the same type but weren't the same constant, quickly 1151 // reject them. 1152 if (A->getType() == B->getType()) return false; 1153 1154 // We can't handle structs or arrays. 1155 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 1156 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 1157 return false; 1158 1159 // For now, only support constants with the same size. 1160 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 1161 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 1162 return false; 1163 1164 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 1165 1166 // Try constant folding a bitcast of both instructions to an integer. If we 1167 // get two identical ConstantInt's, then we are good to share them. We use 1168 // the constant folding APIs to do this so that we get the benefit of 1169 // DataLayout. 1170 if (isa<PointerType>(A->getType())) 1171 A = ConstantFoldCastOperand(Instruction::PtrToInt, 1172 const_cast<Constant *>(A), IntTy, DL); 1173 else if (A->getType() != IntTy) 1174 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 1175 IntTy, DL); 1176 if (isa<PointerType>(B->getType())) 1177 B = ConstantFoldCastOperand(Instruction::PtrToInt, 1178 const_cast<Constant *>(B), IntTy, DL); 1179 else if (B->getType() != IntTy) 1180 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 1181 IntTy, DL); 1182 1183 return A == B; 1184 } 1185 1186 /// Create a new entry in the constant pool or return an existing one. 1187 /// User must specify the log2 of the minimum required alignment for the object. 1188 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 1189 Align Alignment) { 1190 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1191 1192 // Check to see if we already have this constant. 1193 // 1194 // FIXME, this could be made much more efficient for large constant pools. 1195 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1196 if (!Constants[i].isMachineConstantPoolEntry() && 1197 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 1198 if (Constants[i].getAlign() < Alignment) 1199 Constants[i].Alignment = Alignment; 1200 return i; 1201 } 1202 1203 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 1204 return Constants.size()-1; 1205 } 1206 1207 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 1208 Align Alignment) { 1209 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1210 1211 // Check to see if we already have this constant. 1212 // 1213 // FIXME, this could be made much more efficient for large constant pools. 1214 int Idx = V->getExistingMachineCPValue(this, Alignment); 1215 if (Idx != -1) { 1216 MachineCPVsSharingEntries.insert(V); 1217 return (unsigned)Idx; 1218 } 1219 1220 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 1221 return Constants.size()-1; 1222 } 1223 1224 void MachineConstantPool::print(raw_ostream &OS) const { 1225 if (Constants.empty()) return; 1226 1227 OS << "Constant Pool:\n"; 1228 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 1229 OS << " cp#" << i << ": "; 1230 if (Constants[i].isMachineConstantPoolEntry()) 1231 Constants[i].Val.MachineCPVal->print(OS); 1232 else 1233 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 1234 OS << ", align=" << Constants[i].getAlign().value(); 1235 OS << "\n"; 1236 } 1237 } 1238 1239 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1240 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1241 #endif 1242