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 } 102 llvm_unreachable("Invalid machine function property"); 103 } 104 105 // Pin the vtable to this file. 106 void MachineFunction::Delegate::anchor() {} 107 108 void MachineFunctionProperties::print(raw_ostream &OS) const { 109 const char *Separator = ""; 110 for (BitVector::size_type I = 0; I < Properties.size(); ++I) { 111 if (!Properties[I]) 112 continue; 113 OS << Separator << getPropertyName(static_cast<Property>(I)); 114 Separator = ", "; 115 } 116 } 117 118 //===----------------------------------------------------------------------===// 119 // MachineFunction implementation 120 //===----------------------------------------------------------------------===// 121 122 // Out-of-line virtual method. 123 MachineFunctionInfo::~MachineFunctionInfo() = default; 124 125 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 126 MBB->getParent()->DeleteMachineBasicBlock(MBB); 127 } 128 129 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, 130 const Function &F) { 131 if (F.hasFnAttribute(Attribute::StackAlignment)) 132 return F.getFnStackAlignment(); 133 return STI->getFrameLowering()->getStackAlign().value(); 134 } 135 136 MachineFunction::MachineFunction(const Function &F, 137 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 sets the section ranges of cold or exception section with basic block 345 /// sections. 346 void MachineFunction::setSectionRange() { 347 // Compute the Section Range of cold and exception basic blocks. Find the 348 // first and last block of each range. 349 auto SectionRange = 350 ([&](llvm::MachineBasicBlockSection S) -> std::pair<int, int> { 351 auto MBBP = 352 std::find_if(begin(), end(), [&](MachineBasicBlock &MBB) -> bool { 353 return MBB.getSectionType() == S; 354 }); 355 if (MBBP == end()) 356 return std::make_pair(-1, -1); 357 358 auto MBBQ = 359 std::find_if(rbegin(), rend(), [&](MachineBasicBlock &MBB) -> bool { 360 return MBB.getSectionType() == S; 361 }); 362 assert(MBBQ != rend() && "Section end not found!"); 363 return std::make_pair(MBBP->getNumber(), MBBQ->getNumber()); 364 }); 365 366 ExceptionSectionRange = SectionRange(MBBS_Exception); 367 ColdSectionRange = SectionRange(llvm::MBBS_Cold); 368 } 369 370 /// This is used with -fbasicblock-sections or -fbasicblock-labels option. 371 /// A unary encoding of basic block labels is done to keep ".strtab" sizes 372 /// small. 373 void MachineFunction::createBBLabels() { 374 const TargetInstrInfo *TII = getSubtarget().getInstrInfo(); 375 this->BBSectionsSymbolPrefix.resize(getNumBlockIDs(), 'a'); 376 for (auto MBBI = begin(), E = end(); MBBI != E; ++MBBI) { 377 assert( 378 (MBBI->getNumber() >= 0 && MBBI->getNumber() < (int)getNumBlockIDs()) && 379 "BasicBlock number was out of range!"); 380 // 'a' - Normal block. 381 // 'r' - Return block. 382 // 'l' - Landing Pad. 383 // 'L' - Return and landing pad. 384 bool isEHPad = MBBI->isEHPad(); 385 bool isRetBlock = MBBI->isReturnBlock() && !TII->isTailCall(MBBI->back()); 386 char type = 'a'; 387 if (isEHPad && isRetBlock) 388 type = 'L'; 389 else if (isEHPad) 390 type = 'l'; 391 else if (isRetBlock) 392 type = 'r'; 393 BBSectionsSymbolPrefix[MBBI->getNumber()] = type; 394 } 395 } 396 397 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 398 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 399 const DebugLoc &DL, 400 bool NoImp) { 401 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 402 MachineInstr(*this, MCID, DL, NoImp); 403 } 404 405 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 406 /// identical in all ways except the instruction has no parent, prev, or next. 407 MachineInstr * 408 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 409 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 410 MachineInstr(*this, *Orig); 411 } 412 413 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB, 414 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) { 415 MachineInstr *FirstClone = nullptr; 416 MachineBasicBlock::const_instr_iterator I = Orig.getIterator(); 417 while (true) { 418 MachineInstr *Cloned = CloneMachineInstr(&*I); 419 MBB.insert(InsertBefore, Cloned); 420 if (FirstClone == nullptr) { 421 FirstClone = Cloned; 422 } else { 423 Cloned->bundleWithPred(); 424 } 425 426 if (!I->isBundledWithSucc()) 427 break; 428 ++I; 429 } 430 return *FirstClone; 431 } 432 433 /// Delete the given MachineInstr. 434 /// 435 /// This function also serves as the MachineInstr destructor - the real 436 /// ~MachineInstr() destructor must be empty. 437 void 438 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 439 // Verify that a call site info is at valid state. This assertion should 440 // be triggered during the implementation of support for the 441 // call site info of a new architecture. If the assertion is triggered, 442 // back trace will tell where to insert a call to updateCallSiteInfo(). 443 assert((!MI->isCandidateForCallSiteEntry() || 444 CallSitesInfo.find(MI) == CallSitesInfo.end()) && 445 "Call site info was not updated!"); 446 // Strip it for parts. The operand array and the MI object itself are 447 // independently recyclable. 448 if (MI->Operands) 449 deallocateOperandArray(MI->CapOperands, MI->Operands); 450 // Don't call ~MachineInstr() which must be trivial anyway because 451 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 452 // destructors. 453 InstructionRecycler.Deallocate(Allocator, MI); 454 } 455 456 /// Allocate a new MachineBasicBlock. Use this instead of 457 /// `new MachineBasicBlock'. 458 MachineBasicBlock * 459 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 460 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 461 MachineBasicBlock(*this, bb); 462 } 463 464 /// Delete the given MachineBasicBlock. 465 void 466 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 467 assert(MBB->getParent() == this && "MBB parent mismatch!"); 468 MBB->~MachineBasicBlock(); 469 BasicBlockRecycler.Deallocate(Allocator, MBB); 470 } 471 472 MachineMemOperand *MachineFunction::getMachineMemOperand( 473 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 474 Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 475 SyncScope::ID SSID, AtomicOrdering Ordering, 476 AtomicOrdering FailureOrdering) { 477 return new (Allocator) 478 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges, 479 SSID, Ordering, FailureOrdering); 480 } 481 482 MachineMemOperand * 483 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 484 int64_t Offset, uint64_t Size) { 485 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo(); 486 487 // If there is no pointer value, the offset isn't tracked so we need to adjust 488 // the base alignment. 489 Align Alignment = PtrInfo.V.isNull() 490 ? commonAlignment(MMO->getBaseAlign(), Offset) 491 : MMO->getBaseAlign(); 492 493 return new (Allocator) 494 MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size, 495 Alignment, AAMDNodes(), nullptr, MMO->getSyncScopeID(), 496 MMO->getOrdering(), MMO->getFailureOrdering()); 497 } 498 499 MachineMemOperand * 500 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 501 const AAMDNodes &AAInfo) { 502 MachinePointerInfo MPI = MMO->getValue() ? 503 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) : 504 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()); 505 506 return new (Allocator) MachineMemOperand( 507 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo, 508 MMO->getRanges(), MMO->getSyncScopeID(), MMO->getOrdering(), 509 MMO->getFailureOrdering()); 510 } 511 512 MachineMemOperand * 513 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 514 MachineMemOperand::Flags Flags) { 515 return new (Allocator) MachineMemOperand( 516 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(), 517 MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(), 518 MMO->getOrdering(), MMO->getFailureOrdering()); 519 } 520 521 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo( 522 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol, 523 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) { 524 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol, 525 PostInstrSymbol, HeapAllocMarker); 526 } 527 528 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 529 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 530 llvm::copy(Name, Dest); 531 Dest[Name.size()] = 0; 532 return Dest; 533 } 534 535 uint32_t *MachineFunction::allocateRegMask() { 536 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs(); 537 unsigned Size = MachineOperand::getRegMaskSize(NumRegs); 538 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size); 539 memset(Mask, 0, Size * sizeof(Mask[0])); 540 return Mask; 541 } 542 543 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) { 544 int* AllocMask = Allocator.Allocate<int>(Mask.size()); 545 copy(Mask, AllocMask); 546 return {AllocMask, Mask.size()}; 547 } 548 549 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 550 LLVM_DUMP_METHOD void MachineFunction::dump() const { 551 print(dbgs()); 552 } 553 #endif 554 555 StringRef MachineFunction::getName() const { 556 return getFunction().getName(); 557 } 558 559 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 560 OS << "# Machine code for function " << getName() << ": "; 561 getProperties().print(OS); 562 OS << '\n'; 563 564 // Print Frame Information 565 FrameInfo->print(*this, OS); 566 567 // Print JumpTable Information 568 if (JumpTableInfo) 569 JumpTableInfo->print(OS); 570 571 // Print Constant Pool 572 ConstantPool->print(OS); 573 574 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 575 576 if (RegInfo && !RegInfo->livein_empty()) { 577 OS << "Function Live Ins: "; 578 for (MachineRegisterInfo::livein_iterator 579 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 580 OS << printReg(I->first, TRI); 581 if (I->second) 582 OS << " in " << printReg(I->second, TRI); 583 if (std::next(I) != E) 584 OS << ", "; 585 } 586 OS << '\n'; 587 } 588 589 ModuleSlotTracker MST(getFunction().getParent()); 590 MST.incorporateFunction(getFunction()); 591 for (const auto &BB : *this) { 592 OS << '\n'; 593 // If we print the whole function, print it at its most verbose level. 594 BB.print(OS, MST, Indexes, /*IsStandalone=*/true); 595 } 596 597 OS << "\n# End machine code for function " << getName() << ".\n\n"; 598 } 599 600 /// True if this function needs frame moves for debug or exceptions. 601 bool MachineFunction::needsFrameMoves() const { 602 return getMMI().hasDebugInfo() || 603 getTarget().Options.ForceDwarfFrameSection || 604 F.needsUnwindTableEntry(); 605 } 606 607 namespace llvm { 608 609 template<> 610 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 611 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 612 613 static std::string getGraphName(const MachineFunction *F) { 614 return ("CFG for '" + F->getName() + "' function").str(); 615 } 616 617 std::string getNodeLabel(const MachineBasicBlock *Node, 618 const MachineFunction *Graph) { 619 std::string OutStr; 620 { 621 raw_string_ostream OSS(OutStr); 622 623 if (isSimple()) { 624 OSS << printMBBReference(*Node); 625 if (const BasicBlock *BB = Node->getBasicBlock()) 626 OSS << ": " << BB->getName(); 627 } else 628 Node->print(OSS); 629 } 630 631 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 632 633 // Process string output to make it nicer... 634 for (unsigned i = 0; i != OutStr.length(); ++i) 635 if (OutStr[i] == '\n') { // Left justify 636 OutStr[i] = '\\'; 637 OutStr.insert(OutStr.begin()+i+1, 'l'); 638 } 639 return OutStr; 640 } 641 }; 642 643 } // end namespace llvm 644 645 void MachineFunction::viewCFG() const 646 { 647 #ifndef NDEBUG 648 ViewGraph(this, "mf" + getName()); 649 #else 650 errs() << "MachineFunction::viewCFG is only available in debug builds on " 651 << "systems with Graphviz or gv!\n"; 652 #endif // NDEBUG 653 } 654 655 void MachineFunction::viewCFGOnly() const 656 { 657 #ifndef NDEBUG 658 ViewGraph(this, "mf" + getName(), true); 659 #else 660 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 661 << "systems with Graphviz or gv!\n"; 662 #endif // NDEBUG 663 } 664 665 /// Add the specified physical register as a live-in value and 666 /// create a corresponding virtual register for it. 667 unsigned MachineFunction::addLiveIn(unsigned PReg, 668 const TargetRegisterClass *RC) { 669 MachineRegisterInfo &MRI = getRegInfo(); 670 unsigned VReg = MRI.getLiveInVirtReg(PReg); 671 if (VReg) { 672 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 673 (void)VRegRC; 674 // A physical register can be added several times. 675 // Between two calls, the register class of the related virtual register 676 // may have been constrained to match some operation constraints. 677 // In that case, check that the current register class includes the 678 // physical register and is a sub class of the specified RC. 679 assert((VRegRC == RC || (VRegRC->contains(PReg) && 680 RC->hasSubClassEq(VRegRC))) && 681 "Register class mismatch!"); 682 return VReg; 683 } 684 VReg = MRI.createVirtualRegister(RC); 685 MRI.addLiveIn(PReg, VReg); 686 return VReg; 687 } 688 689 /// Return the MCSymbol for the specified non-empty jump table. 690 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 691 /// normal 'L' label is returned. 692 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 693 bool isLinkerPrivate) const { 694 const DataLayout &DL = getDataLayout(); 695 assert(JumpTableInfo && "No jump tables"); 696 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 697 698 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 699 : DL.getPrivateGlobalPrefix(); 700 SmallString<60> Name; 701 raw_svector_ostream(Name) 702 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 703 return Ctx.getOrCreateSymbol(Name); 704 } 705 706 /// Return a function-local symbol to represent the PIC base. 707 MCSymbol *MachineFunction::getPICBaseSymbol() const { 708 const DataLayout &DL = getDataLayout(); 709 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 710 Twine(getFunctionNumber()) + "$pb"); 711 } 712 713 /// \name Exception Handling 714 /// \{ 715 716 LandingPadInfo & 717 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) { 718 unsigned N = LandingPads.size(); 719 for (unsigned i = 0; i < N; ++i) { 720 LandingPadInfo &LP = LandingPads[i]; 721 if (LP.LandingPadBlock == LandingPad) 722 return LP; 723 } 724 725 LandingPads.push_back(LandingPadInfo(LandingPad)); 726 return LandingPads[N]; 727 } 728 729 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad, 730 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 731 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 732 LP.BeginLabels.push_back(BeginLabel); 733 LP.EndLabels.push_back(EndLabel); 734 } 735 736 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) { 737 MCSymbol *LandingPadLabel = Ctx.createTempSymbol(); 738 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 739 LP.LandingPadLabel = LandingPadLabel; 740 741 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI(); 742 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) { 743 if (const auto *PF = 744 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts())) 745 getMMI().addPersonality(PF); 746 747 if (LPI->isCleanup()) 748 addCleanup(LandingPad); 749 750 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% 751 // correct, but we need to do it this way because of how the DWARF EH 752 // emitter processes the clauses. 753 for (unsigned I = LPI->getNumClauses(); I != 0; --I) { 754 Value *Val = LPI->getClause(I - 1); 755 if (LPI->isCatch(I - 1)) { 756 addCatchTypeInfo(LandingPad, 757 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 758 } else { 759 // Add filters in a list. 760 auto *CVal = cast<Constant>(Val); 761 SmallVector<const GlobalValue *, 4> FilterList; 762 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end(); 763 II != IE; ++II) 764 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts())); 765 766 addFilterTypeInfo(LandingPad, FilterList); 767 } 768 } 769 770 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) { 771 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) { 772 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts(); 773 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo)); 774 } 775 776 } else { 777 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!"); 778 } 779 780 return LandingPadLabel; 781 } 782 783 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad, 784 ArrayRef<const GlobalValue *> TyInfo) { 785 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 786 for (unsigned N = TyInfo.size(); N; --N) 787 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 788 } 789 790 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad, 791 ArrayRef<const GlobalValue *> TyInfo) { 792 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 793 std::vector<unsigned> IdsInFilter(TyInfo.size()); 794 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 795 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 796 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 797 } 798 799 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap, 800 bool TidyIfNoBeginLabels) { 801 for (unsigned i = 0; i != LandingPads.size(); ) { 802 LandingPadInfo &LandingPad = LandingPads[i]; 803 if (LandingPad.LandingPadLabel && 804 !LandingPad.LandingPadLabel->isDefined() && 805 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 806 LandingPad.LandingPadLabel = nullptr; 807 808 // Special case: we *should* emit LPs with null LP MBB. This indicates 809 // "nounwind" case. 810 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 811 LandingPads.erase(LandingPads.begin() + i); 812 continue; 813 } 814 815 if (TidyIfNoBeginLabels) { 816 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 817 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 818 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 819 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) && 820 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0))) 821 continue; 822 823 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 824 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 825 --j; 826 --e; 827 } 828 829 // Remove landing pads with no try-ranges. 830 if (LandingPads[i].BeginLabels.empty()) { 831 LandingPads.erase(LandingPads.begin() + i); 832 continue; 833 } 834 } 835 836 // If there is no landing pad, ensure that the list of typeids is empty. 837 // If the only typeid is a cleanup, this is the same as having no typeids. 838 if (!LandingPad.LandingPadBlock || 839 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 840 LandingPad.TypeIds.clear(); 841 ++i; 842 } 843 } 844 845 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) { 846 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 847 LP.TypeIds.push_back(0); 848 } 849 850 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad, 851 const Function *Filter, 852 const BlockAddress *RecoverBA) { 853 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 854 SEHHandler Handler; 855 Handler.FilterOrFinally = Filter; 856 Handler.RecoverBA = RecoverBA; 857 LP.SEHHandlers.push_back(Handler); 858 } 859 860 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 861 const Function *Cleanup) { 862 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 863 SEHHandler Handler; 864 Handler.FilterOrFinally = Cleanup; 865 Handler.RecoverBA = nullptr; 866 LP.SEHHandlers.push_back(Handler); 867 } 868 869 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym, 870 ArrayRef<unsigned> Sites) { 871 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 872 } 873 874 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) { 875 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 876 if (TypeInfos[i] == TI) return i + 1; 877 878 TypeInfos.push_back(TI); 879 return TypeInfos.size(); 880 } 881 882 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) { 883 // If the new filter coincides with the tail of an existing filter, then 884 // re-use the existing filter. Folding filters more than this requires 885 // re-ordering filters and/or their elements - probably not worth it. 886 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 887 E = FilterEnds.end(); I != E; ++I) { 888 unsigned i = *I, j = TyIds.size(); 889 890 while (i && j) 891 if (FilterIds[--i] != TyIds[--j]) 892 goto try_next; 893 894 if (!j) 895 // The new filter coincides with range [i, end) of the existing filter. 896 return -(1 + i); 897 898 try_next:; 899 } 900 901 // Add the new filter. 902 int FilterID = -(1 + FilterIds.size()); 903 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 904 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 905 FilterEnds.push_back(FilterIds.size()); 906 FilterIds.push_back(0); // terminator 907 return FilterID; 908 } 909 910 MachineFunction::CallSiteInfoMap::iterator 911 MachineFunction::getCallSiteInfo(const MachineInstr *MI) { 912 assert(MI->isCandidateForCallSiteEntry() && 913 "Call site info refers only to call (MI) candidates"); 914 915 if (!Target.Options.EmitCallSiteInfo) 916 return CallSitesInfo.end(); 917 return CallSitesInfo.find(MI); 918 } 919 920 /// Return the call machine instruction or find a call within bundle. 921 static const MachineInstr *getCallInstr(const MachineInstr *MI) { 922 if (!MI->isBundle()) 923 return MI; 924 925 for (auto &BMI : make_range(getBundleStart(MI->getIterator()), 926 getBundleEnd(MI->getIterator()))) 927 if (BMI.isCandidateForCallSiteEntry()) 928 return &BMI; 929 930 llvm_unreachable("Unexpected bundle without a call site candidate"); 931 } 932 933 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) { 934 assert(MI->shouldUpdateCallSiteInfo() && 935 "Call site info refers only to call (MI) candidates or " 936 "candidates inside bundles"); 937 938 const MachineInstr *CallMI = getCallInstr(MI); 939 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI); 940 if (CSIt == CallSitesInfo.end()) 941 return; 942 CallSitesInfo.erase(CSIt); 943 } 944 945 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old, 946 const MachineInstr *New) { 947 assert(Old->shouldUpdateCallSiteInfo() && 948 "Call site info refers only to call (MI) candidates or " 949 "candidates inside bundles"); 950 951 if (!New->isCandidateForCallSiteEntry()) 952 return eraseCallSiteInfo(Old); 953 954 const MachineInstr *OldCallMI = getCallInstr(Old); 955 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 956 if (CSIt == CallSitesInfo.end()) 957 return; 958 959 CallSiteInfo CSInfo = CSIt->second; 960 CallSitesInfo[New] = CSInfo; 961 } 962 963 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old, 964 const MachineInstr *New) { 965 assert(Old->shouldUpdateCallSiteInfo() && 966 "Call site info refers only to call (MI) candidates or " 967 "candidates inside bundles"); 968 969 if (!New->isCandidateForCallSiteEntry()) 970 return eraseCallSiteInfo(Old); 971 972 const MachineInstr *OldCallMI = getCallInstr(Old); 973 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI); 974 if (CSIt == CallSitesInfo.end()) 975 return; 976 977 CallSiteInfo CSInfo = std::move(CSIt->second); 978 CallSitesInfo.erase(CSIt); 979 CallSitesInfo[New] = CSInfo; 980 } 981 982 /// \} 983 984 //===----------------------------------------------------------------------===// 985 // MachineJumpTableInfo implementation 986 //===----------------------------------------------------------------------===// 987 988 /// Return the size of each entry in the jump table. 989 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 990 // The size of a jump table entry is 4 bytes unless the entry is just the 991 // address of a block, in which case it is the pointer size. 992 switch (getEntryKind()) { 993 case MachineJumpTableInfo::EK_BlockAddress: 994 return TD.getPointerSize(); 995 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 996 return 8; 997 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 998 case MachineJumpTableInfo::EK_LabelDifference32: 999 case MachineJumpTableInfo::EK_Custom32: 1000 return 4; 1001 case MachineJumpTableInfo::EK_Inline: 1002 return 0; 1003 } 1004 llvm_unreachable("Unknown jump table encoding!"); 1005 } 1006 1007 /// Return the alignment of each entry in the jump table. 1008 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 1009 // The alignment of a jump table entry is the alignment of int32 unless the 1010 // entry is just the address of a block, in which case it is the pointer 1011 // alignment. 1012 switch (getEntryKind()) { 1013 case MachineJumpTableInfo::EK_BlockAddress: 1014 return TD.getPointerABIAlignment(0).value(); 1015 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 1016 return TD.getABIIntegerTypeAlignment(64).value(); 1017 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 1018 case MachineJumpTableInfo::EK_LabelDifference32: 1019 case MachineJumpTableInfo::EK_Custom32: 1020 return TD.getABIIntegerTypeAlignment(32).value(); 1021 case MachineJumpTableInfo::EK_Inline: 1022 return 1; 1023 } 1024 llvm_unreachable("Unknown jump table encoding!"); 1025 } 1026 1027 /// Create a new jump table entry in the jump table info. 1028 unsigned MachineJumpTableInfo::createJumpTableIndex( 1029 const std::vector<MachineBasicBlock*> &DestBBs) { 1030 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 1031 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 1032 return JumpTables.size()-1; 1033 } 1034 1035 /// If Old is the target of any jump tables, update the jump tables to branch 1036 /// to New instead. 1037 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 1038 MachineBasicBlock *New) { 1039 assert(Old != New && "Not making a change?"); 1040 bool MadeChange = false; 1041 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 1042 ReplaceMBBInJumpTable(i, Old, New); 1043 return MadeChange; 1044 } 1045 1046 /// If Old is a target of the jump tables, update the jump table to branch to 1047 /// New instead. 1048 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 1049 MachineBasicBlock *Old, 1050 MachineBasicBlock *New) { 1051 assert(Old != New && "Not making a change?"); 1052 bool MadeChange = false; 1053 MachineJumpTableEntry &JTE = JumpTables[Idx]; 1054 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 1055 if (JTE.MBBs[j] == Old) { 1056 JTE.MBBs[j] = New; 1057 MadeChange = true; 1058 } 1059 return MadeChange; 1060 } 1061 1062 void MachineJumpTableInfo::print(raw_ostream &OS) const { 1063 if (JumpTables.empty()) return; 1064 1065 OS << "Jump Tables:\n"; 1066 1067 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 1068 OS << printJumpTableEntryReference(i) << ':'; 1069 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) 1070 OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]); 1071 if (i != e) 1072 OS << '\n'; 1073 } 1074 1075 OS << '\n'; 1076 } 1077 1078 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1079 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 1080 #endif 1081 1082 Printable llvm::printJumpTableEntryReference(unsigned Idx) { 1083 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; }); 1084 } 1085 1086 //===----------------------------------------------------------------------===// 1087 // MachineConstantPool implementation 1088 //===----------------------------------------------------------------------===// 1089 1090 void MachineConstantPoolValue::anchor() {} 1091 1092 Type *MachineConstantPoolEntry::getType() const { 1093 if (isMachineConstantPoolEntry()) 1094 return Val.MachineCPVal->getType(); 1095 return Val.ConstVal->getType(); 1096 } 1097 1098 bool MachineConstantPoolEntry::needsRelocation() const { 1099 if (isMachineConstantPoolEntry()) 1100 return true; 1101 return Val.ConstVal->needsRelocation(); 1102 } 1103 1104 SectionKind 1105 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 1106 if (needsRelocation()) 1107 return SectionKind::getReadOnlyWithRel(); 1108 switch (DL->getTypeAllocSize(getType())) { 1109 case 4: 1110 return SectionKind::getMergeableConst4(); 1111 case 8: 1112 return SectionKind::getMergeableConst8(); 1113 case 16: 1114 return SectionKind::getMergeableConst16(); 1115 case 32: 1116 return SectionKind::getMergeableConst32(); 1117 default: 1118 return SectionKind::getReadOnly(); 1119 } 1120 } 1121 1122 MachineConstantPool::~MachineConstantPool() { 1123 // A constant may be a member of both Constants and MachineCPVsSharingEntries, 1124 // so keep track of which we've deleted to avoid double deletions. 1125 DenseSet<MachineConstantPoolValue*> Deleted; 1126 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1127 if (Constants[i].isMachineConstantPoolEntry()) { 1128 Deleted.insert(Constants[i].Val.MachineCPVal); 1129 delete Constants[i].Val.MachineCPVal; 1130 } 1131 for (DenseSet<MachineConstantPoolValue*>::iterator I = 1132 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); 1133 I != E; ++I) { 1134 if (Deleted.count(*I) == 0) 1135 delete *I; 1136 } 1137 } 1138 1139 /// Test whether the given two constants can be allocated the same constant pool 1140 /// entry. 1141 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 1142 const DataLayout &DL) { 1143 // Handle the trivial case quickly. 1144 if (A == B) return true; 1145 1146 // If they have the same type but weren't the same constant, quickly 1147 // reject them. 1148 if (A->getType() == B->getType()) return false; 1149 1150 // We can't handle structs or arrays. 1151 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 1152 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 1153 return false; 1154 1155 // For now, only support constants with the same size. 1156 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 1157 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 1158 return false; 1159 1160 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 1161 1162 // Try constant folding a bitcast of both instructions to an integer. If we 1163 // get two identical ConstantInt's, then we are good to share them. We use 1164 // the constant folding APIs to do this so that we get the benefit of 1165 // DataLayout. 1166 if (isa<PointerType>(A->getType())) 1167 A = ConstantFoldCastOperand(Instruction::PtrToInt, 1168 const_cast<Constant *>(A), IntTy, DL); 1169 else if (A->getType() != IntTy) 1170 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 1171 IntTy, DL); 1172 if (isa<PointerType>(B->getType())) 1173 B = ConstantFoldCastOperand(Instruction::PtrToInt, 1174 const_cast<Constant *>(B), IntTy, DL); 1175 else if (B->getType() != IntTy) 1176 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 1177 IntTy, DL); 1178 1179 return A == B; 1180 } 1181 1182 /// Create a new entry in the constant pool or return an existing one. 1183 /// User must specify the log2 of the minimum required alignment for the object. 1184 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 1185 unsigned Alignment) { 1186 assert(Alignment && "Alignment must be specified!"); 1187 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1188 1189 // Check to see if we already have this constant. 1190 // 1191 // FIXME, this could be made much more efficient for large constant pools. 1192 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1193 if (!Constants[i].isMachineConstantPoolEntry() && 1194 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 1195 if ((unsigned)Constants[i].getAlignment() < Alignment) 1196 Constants[i].Alignment = Alignment; 1197 return i; 1198 } 1199 1200 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 1201 return Constants.size()-1; 1202 } 1203 1204 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 1205 unsigned Alignment) { 1206 assert(Alignment && "Alignment must be specified!"); 1207 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1208 1209 // Check to see if we already have this constant. 1210 // 1211 // FIXME, this could be made much more efficient for large constant pools. 1212 int Idx = V->getExistingMachineCPValue(this, Alignment); 1213 if (Idx != -1) { 1214 MachineCPVsSharingEntries.insert(V); 1215 return (unsigned)Idx; 1216 } 1217 1218 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 1219 return Constants.size()-1; 1220 } 1221 1222 void MachineConstantPool::print(raw_ostream &OS) const { 1223 if (Constants.empty()) return; 1224 1225 OS << "Constant Pool:\n"; 1226 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 1227 OS << " cp#" << i << ": "; 1228 if (Constants[i].isMachineConstantPoolEntry()) 1229 Constants[i].Val.MachineCPVal->print(OS); 1230 else 1231 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 1232 OS << ", align=" << Constants[i].getAlignment(); 1233 OS << "\n"; 1234 } 1235 } 1236 1237 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1238 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1239 #endif 1240