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