1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
14 //===----------------------------------------------------------------------===//
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/EHPersonalities.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/CodeGen/WinEHFuncInfo.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/ModuleSlotTracker.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/GraphWriter.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetFrameLowering.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
47 #define DEBUG_TYPE "codegen"
49 static cl::opt<unsigned>
50 AlignAllFunctions("align-all-functions",
51 cl::desc("Force the alignment of all functions."),
52 cl::init(0), cl::Hidden);
54 static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
55 typedef MachineFunctionProperties::Property P;
57 case P::FailedISel: return "FailedISel";
58 case P::IsSSA: return "IsSSA";
59 case P::Legalized: return "Legalized";
60 case P::NoPHIs: return "NoPHIs";
61 case P::NoVRegs: return "NoVRegs";
62 case P::RegBankSelected: return "RegBankSelected";
63 case P::Selected: return "Selected";
64 case P::TracksLiveness: return "TracksLiveness";
66 llvm_unreachable("Invalid machine function property");
69 void MachineFunctionProperties::print(raw_ostream &OS) const {
70 const char *Separator = "";
71 for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
74 OS << Separator << getPropertyName(static_cast<Property>(I));
79 //===----------------------------------------------------------------------===//
80 // MachineFunction implementation
81 //===----------------------------------------------------------------------===//
83 // Out-of-line virtual method.
84 MachineFunctionInfo::~MachineFunctionInfo() {}
86 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
87 MBB->getParent()->DeleteMachineBasicBlock(MBB);
90 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
92 if (Fn->hasFnAttribute(Attribute::StackAlignment))
93 return Fn->getFnStackAlignment();
94 return STI->getFrameLowering()->getStackAlignment();
97 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
98 unsigned FunctionNum, MachineModuleInfo &mmi)
99 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
101 FunctionNumber = FunctionNum;
105 void MachineFunction::init() {
106 // Assume the function starts in SSA form with correct liveness.
107 Properties.set(MachineFunctionProperties::Property::IsSSA);
108 Properties.set(MachineFunctionProperties::Property::TracksLiveness);
109 if (STI->getRegisterInfo())
110 RegInfo = new (Allocator) MachineRegisterInfo(this);
115 // We can realign the stack if the target supports it and the user hasn't
116 // explicitly asked us not to.
117 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
118 !Fn->hasFnAttribute("no-realign-stack");
119 FrameInfo = new (Allocator) MachineFrameInfo(
120 getFnStackAlignment(STI, Fn), /*StackRealignable=*/CanRealignSP,
121 /*ForceRealign=*/CanRealignSP &&
122 Fn->hasFnAttribute(Attribute::StackAlignment));
124 if (Fn->hasFnAttribute(Attribute::StackAlignment))
125 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
127 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
128 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
130 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
131 // FIXME: Use Function::optForSize().
132 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
133 Alignment = std::max(Alignment,
134 STI->getTargetLowering()->getPrefFunctionAlignment());
136 if (AlignAllFunctions)
137 Alignment = AlignAllFunctions;
139 JumpTableInfo = nullptr;
141 if (isFuncletEHPersonality(classifyEHPersonality(
142 Fn->hasPersonalityFn() ? Fn->getPersonalityFn() : nullptr))) {
143 WinEHInfo = new (Allocator) WinEHFuncInfo();
146 assert(Target.isCompatibleDataLayout(getDataLayout()) &&
147 "Can't create a MachineFunction using a Module with a "
148 "Target-incompatible DataLayout attached\n");
150 PSVManager = llvm::make_unique<PseudoSourceValueManager>();
153 MachineFunction::~MachineFunction() {
157 void MachineFunction::clear() {
159 // Don't call destructors on MachineInstr and MachineOperand. All of their
160 // memory comes from the BumpPtrAllocator which is about to be purged.
162 // Do call MachineBasicBlock destructors, it contains std::vectors.
163 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
164 I->Insts.clearAndLeakNodesUnsafely();
166 InstructionRecycler.clear(Allocator);
167 OperandRecycler.clear(Allocator);
168 BasicBlockRecycler.clear(Allocator);
169 VariableDbgInfos.clear();
171 RegInfo->~MachineRegisterInfo();
172 Allocator.Deallocate(RegInfo);
175 MFInfo->~MachineFunctionInfo();
176 Allocator.Deallocate(MFInfo);
179 FrameInfo->~MachineFrameInfo();
180 Allocator.Deallocate(FrameInfo);
182 ConstantPool->~MachineConstantPool();
183 Allocator.Deallocate(ConstantPool);
186 JumpTableInfo->~MachineJumpTableInfo();
187 Allocator.Deallocate(JumpTableInfo);
191 WinEHInfo->~WinEHFuncInfo();
192 Allocator.Deallocate(WinEHInfo);
196 const DataLayout &MachineFunction::getDataLayout() const {
197 return Fn->getParent()->getDataLayout();
200 /// Get the JumpTableInfo for this function.
201 /// If it does not already exist, allocate one.
202 MachineJumpTableInfo *MachineFunction::
203 getOrCreateJumpTableInfo(unsigned EntryKind) {
204 if (JumpTableInfo) return JumpTableInfo;
206 JumpTableInfo = new (Allocator)
207 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
208 return JumpTableInfo;
211 /// Should we be emitting segmented stack stuff for the function
212 bool MachineFunction::shouldSplitStack() const {
213 return getFunction()->hasFnAttribute("split-stack");
216 /// This discards all of the MachineBasicBlock numbers and recomputes them.
217 /// This guarantees that the MBB numbers are sequential, dense, and match the
218 /// ordering of the blocks within the function. If a specific MachineBasicBlock
219 /// is specified, only that block and those after it are renumbered.
220 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
221 if (empty()) { MBBNumbering.clear(); return; }
222 MachineFunction::iterator MBBI, E = end();
226 MBBI = MBB->getIterator();
228 // Figure out the block number this should have.
229 unsigned BlockNo = 0;
231 BlockNo = std::prev(MBBI)->getNumber() + 1;
233 for (; MBBI != E; ++MBBI, ++BlockNo) {
234 if (MBBI->getNumber() != (int)BlockNo) {
235 // Remove use of the old number.
236 if (MBBI->getNumber() != -1) {
237 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
238 "MBB number mismatch!");
239 MBBNumbering[MBBI->getNumber()] = nullptr;
242 // If BlockNo is already taken, set that block's number to -1.
243 if (MBBNumbering[BlockNo])
244 MBBNumbering[BlockNo]->setNumber(-1);
246 MBBNumbering[BlockNo] = &*MBBI;
247 MBBI->setNumber(BlockNo);
251 // Okay, all the blocks are renumbered. If we have compactified the block
252 // numbering, shrink MBBNumbering now.
253 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
254 MBBNumbering.resize(BlockNo);
257 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
258 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
261 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
262 MachineInstr(*this, MCID, DL, NoImp);
265 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
266 /// identical in all ways except the instruction has no parent, prev, or next.
268 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
269 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
270 MachineInstr(*this, *Orig);
273 /// Delete the given MachineInstr.
275 /// This function also serves as the MachineInstr destructor - the real
276 /// ~MachineInstr() destructor must be empty.
278 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
279 // Strip it for parts. The operand array and the MI object itself are
280 // independently recyclable.
282 deallocateOperandArray(MI->CapOperands, MI->Operands);
283 // Don't call ~MachineInstr() which must be trivial anyway because
284 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
286 InstructionRecycler.Deallocate(Allocator, MI);
289 /// Allocate a new MachineBasicBlock. Use this instead of
290 /// `new MachineBasicBlock'.
292 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
293 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
294 MachineBasicBlock(*this, bb);
297 /// Delete the given MachineBasicBlock.
299 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
300 assert(MBB->getParent() == this && "MBB parent mismatch!");
301 MBB->~MachineBasicBlock();
302 BasicBlockRecycler.Deallocate(Allocator, MBB);
305 MachineMemOperand *MachineFunction::getMachineMemOperand(
306 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
307 unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
308 SyncScope::ID SSID, AtomicOrdering Ordering,
309 AtomicOrdering FailureOrdering) {
310 return new (Allocator)
311 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
312 SSID, Ordering, FailureOrdering);
316 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
317 int64_t Offset, uint64_t Size) {
319 return new (Allocator)
320 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
321 MMO->getOffset()+Offset),
322 MMO->getFlags(), Size, MMO->getBaseAlignment(),
323 AAMDNodes(), nullptr, MMO->getSyncScopeID(),
324 MMO->getOrdering(), MMO->getFailureOrdering());
325 return new (Allocator)
326 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
327 MMO->getOffset()+Offset),
328 MMO->getFlags(), Size, MMO->getBaseAlignment(),
329 AAMDNodes(), nullptr, MMO->getSyncScopeID(),
330 MMO->getOrdering(), MMO->getFailureOrdering());
334 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
335 const AAMDNodes &AAInfo) {
336 MachinePointerInfo MPI = MMO->getValue() ?
337 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
338 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
340 return new (Allocator)
341 MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
342 MMO->getBaseAlignment(), AAInfo,
343 MMO->getRanges(), MMO->getSyncScopeID(),
344 MMO->getOrdering(), MMO->getFailureOrdering());
347 MachineInstr::mmo_iterator
348 MachineFunction::allocateMemRefsArray(unsigned long Num) {
349 return Allocator.Allocate<MachineMemOperand *>(Num);
352 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
353 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
354 MachineInstr::mmo_iterator End) {
355 // Count the number of load mem refs.
357 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
361 // Allocate a new array and populate it with the load information.
362 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
364 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
365 if ((*I)->isLoad()) {
366 if (!(*I)->isStore())
370 // Clone the MMO and unset the store flag.
371 MachineMemOperand *JustLoad =
372 getMachineMemOperand((*I)->getPointerInfo(),
373 (*I)->getFlags() & ~MachineMemOperand::MOStore,
374 (*I)->getSize(), (*I)->getBaseAlignment(),
375 (*I)->getAAInfo(), nullptr,
376 (*I)->getSyncScopeID(), (*I)->getOrdering(),
377 (*I)->getFailureOrdering());
378 Result[Index] = JustLoad;
383 return std::make_pair(Result, Result + Num);
386 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
387 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
388 MachineInstr::mmo_iterator End) {
389 // Count the number of load mem refs.
391 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
395 // Allocate a new array and populate it with the store information.
396 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
398 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
399 if ((*I)->isStore()) {
404 // Clone the MMO and unset the load flag.
405 MachineMemOperand *JustStore =
406 getMachineMemOperand((*I)->getPointerInfo(),
407 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
408 (*I)->getSize(), (*I)->getBaseAlignment(),
409 (*I)->getAAInfo(), nullptr,
410 (*I)->getSyncScopeID(), (*I)->getOrdering(),
411 (*I)->getFailureOrdering());
412 Result[Index] = JustStore;
417 return std::make_pair(Result, Result + Num);
420 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
421 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
422 std::copy(Name.begin(), Name.end(), Dest);
423 Dest[Name.size()] = 0;
427 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
428 LLVM_DUMP_METHOD void MachineFunction::dump() const {
433 StringRef MachineFunction::getName() const {
434 assert(getFunction() && "No function!");
435 return getFunction()->getName();
438 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
439 OS << "# Machine code for function " << getName() << ": ";
440 getProperties().print(OS);
443 // Print Frame Information
444 FrameInfo->print(*this, OS);
446 // Print JumpTable Information
448 JumpTableInfo->print(OS);
450 // Print Constant Pool
451 ConstantPool->print(OS);
453 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
455 if (RegInfo && !RegInfo->livein_empty()) {
456 OS << "Function Live Ins: ";
457 for (MachineRegisterInfo::livein_iterator
458 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
459 OS << PrintReg(I->first, TRI);
461 OS << " in " << PrintReg(I->second, TRI);
462 if (std::next(I) != E)
468 ModuleSlotTracker MST(getFunction()->getParent());
469 MST.incorporateFunction(*getFunction());
470 for (const auto &BB : *this) {
472 BB.print(OS, MST, Indexes);
475 OS << "\n# End machine code for function " << getName() << ".\n\n";
480 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
482 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
484 static std::string getGraphName(const MachineFunction *F) {
485 return ("CFG for '" + F->getName() + "' function").str();
488 std::string getNodeLabel(const MachineBasicBlock *Node,
489 const MachineFunction *Graph) {
492 raw_string_ostream OSS(OutStr);
495 OSS << "BB#" << Node->getNumber();
496 if (const BasicBlock *BB = Node->getBasicBlock())
497 OSS << ": " << BB->getName();
502 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
504 // Process string output to make it nicer...
505 for (unsigned i = 0; i != OutStr.length(); ++i)
506 if (OutStr[i] == '\n') { // Left justify
508 OutStr.insert(OutStr.begin()+i+1, 'l');
515 void MachineFunction::viewCFG() const
518 ViewGraph(this, "mf" + getName());
520 errs() << "MachineFunction::viewCFG is only available in debug builds on "
521 << "systems with Graphviz or gv!\n";
525 void MachineFunction::viewCFGOnly() const
528 ViewGraph(this, "mf" + getName(), true);
530 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
531 << "systems with Graphviz or gv!\n";
535 /// Add the specified physical register as a live-in value and
536 /// create a corresponding virtual register for it.
537 unsigned MachineFunction::addLiveIn(unsigned PReg,
538 const TargetRegisterClass *RC) {
539 MachineRegisterInfo &MRI = getRegInfo();
540 unsigned VReg = MRI.getLiveInVirtReg(PReg);
542 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
544 // A physical register can be added several times.
545 // Between two calls, the register class of the related virtual register
546 // may have been constrained to match some operation constraints.
547 // In that case, check that the current register class includes the
548 // physical register and is a sub class of the specified RC.
549 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
550 RC->hasSubClassEq(VRegRC))) &&
551 "Register class mismatch!");
554 VReg = MRI.createVirtualRegister(RC);
555 MRI.addLiveIn(PReg, VReg);
559 /// Return the MCSymbol for the specified non-empty jump table.
560 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
561 /// normal 'L' label is returned.
562 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
563 bool isLinkerPrivate) const {
564 const DataLayout &DL = getDataLayout();
565 assert(JumpTableInfo && "No jump tables");
566 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
568 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
569 : DL.getPrivateGlobalPrefix();
570 SmallString<60> Name;
571 raw_svector_ostream(Name)
572 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
573 return Ctx.getOrCreateSymbol(Name);
576 /// Return a function-local symbol to represent the PIC base.
577 MCSymbol *MachineFunction::getPICBaseSymbol() const {
578 const DataLayout &DL = getDataLayout();
579 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
580 Twine(getFunctionNumber()) + "$pb");
583 /// \name Exception Handling
587 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
588 unsigned N = LandingPads.size();
589 for (unsigned i = 0; i < N; ++i) {
590 LandingPadInfo &LP = LandingPads[i];
591 if (LP.LandingPadBlock == LandingPad)
595 LandingPads.push_back(LandingPadInfo(LandingPad));
596 return LandingPads[N];
599 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
600 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
601 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
602 LP.BeginLabels.push_back(BeginLabel);
603 LP.EndLabels.push_back(EndLabel);
606 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
607 MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
608 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
609 LP.LandingPadLabel = LandingPadLabel;
610 return LandingPadLabel;
613 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
614 ArrayRef<const GlobalValue *> TyInfo) {
615 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
616 for (unsigned N = TyInfo.size(); N; --N)
617 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
620 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
621 ArrayRef<const GlobalValue *> TyInfo) {
622 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
623 std::vector<unsigned> IdsInFilter(TyInfo.size());
624 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
625 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
626 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
629 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
630 for (unsigned i = 0; i != LandingPads.size(); ) {
631 LandingPadInfo &LandingPad = LandingPads[i];
632 if (LandingPad.LandingPadLabel &&
633 !LandingPad.LandingPadLabel->isDefined() &&
634 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
635 LandingPad.LandingPadLabel = nullptr;
637 // Special case: we *should* emit LPs with null LP MBB. This indicates
639 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
640 LandingPads.erase(LandingPads.begin() + i);
644 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
645 MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
646 MCSymbol *EndLabel = LandingPad.EndLabels[j];
647 if ((BeginLabel->isDefined() ||
648 (LPMap && (*LPMap)[BeginLabel] != 0)) &&
649 (EndLabel->isDefined() ||
650 (LPMap && (*LPMap)[EndLabel] != 0))) continue;
652 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
653 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
658 // Remove landing pads with no try-ranges.
659 if (LandingPads[i].BeginLabels.empty()) {
660 LandingPads.erase(LandingPads.begin() + i);
664 // If there is no landing pad, ensure that the list of typeids is empty.
665 // If the only typeid is a cleanup, this is the same as having no typeids.
666 if (!LandingPad.LandingPadBlock ||
667 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
668 LandingPad.TypeIds.clear();
673 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
674 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
675 LP.TypeIds.push_back(0);
678 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
679 const Function *Filter,
680 const BlockAddress *RecoverBA) {
681 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
683 Handler.FilterOrFinally = Filter;
684 Handler.RecoverBA = RecoverBA;
685 LP.SEHHandlers.push_back(Handler);
688 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
689 const Function *Cleanup) {
690 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
692 Handler.FilterOrFinally = Cleanup;
693 Handler.RecoverBA = nullptr;
694 LP.SEHHandlers.push_back(Handler);
697 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
698 ArrayRef<unsigned> Sites) {
699 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
702 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
703 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
704 if (TypeInfos[i] == TI) return i + 1;
706 TypeInfos.push_back(TI);
707 return TypeInfos.size();
710 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
711 // If the new filter coincides with the tail of an existing filter, then
712 // re-use the existing filter. Folding filters more than this requires
713 // re-ordering filters and/or their elements - probably not worth it.
714 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
715 E = FilterEnds.end(); I != E; ++I) {
716 unsigned i = *I, j = TyIds.size();
719 if (FilterIds[--i] != TyIds[--j])
723 // The new filter coincides with range [i, end) of the existing filter.
729 // Add the new filter.
730 int FilterID = -(1 + FilterIds.size());
731 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
732 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
733 FilterEnds.push_back(FilterIds.size());
734 FilterIds.push_back(0); // terminator
738 void llvm::addLandingPadInfo(const LandingPadInst &I, MachineBasicBlock &MBB) {
739 MachineFunction &MF = *MBB.getParent();
740 if (const auto *PF = dyn_cast<Function>(
741 I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts()))
742 MF.getMMI().addPersonality(PF);
747 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
748 // but we need to do it this way because of how the DWARF EH emitter
749 // processes the clauses.
750 for (unsigned i = I.getNumClauses(); i != 0; --i) {
751 Value *Val = I.getClause(i - 1);
752 if (I.isCatch(i - 1)) {
753 MF.addCatchTypeInfo(&MBB,
754 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
756 // Add filters in a list.
757 Constant *CVal = cast<Constant>(Val);
758 SmallVector<const GlobalValue *, 4> FilterList;
759 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
761 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
763 MF.addFilterTypeInfo(&MBB, FilterList);
770 //===----------------------------------------------------------------------===//
771 // MachineJumpTableInfo implementation
772 //===----------------------------------------------------------------------===//
774 /// Return the size of each entry in the jump table.
775 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
776 // The size of a jump table entry is 4 bytes unless the entry is just the
777 // address of a block, in which case it is the pointer size.
778 switch (getEntryKind()) {
779 case MachineJumpTableInfo::EK_BlockAddress:
780 return TD.getPointerSize();
781 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
783 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
784 case MachineJumpTableInfo::EK_LabelDifference32:
785 case MachineJumpTableInfo::EK_Custom32:
787 case MachineJumpTableInfo::EK_Inline:
790 llvm_unreachable("Unknown jump table encoding!");
793 /// Return the alignment of each entry in the jump table.
794 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
795 // The alignment of a jump table entry is the alignment of int32 unless the
796 // entry is just the address of a block, in which case it is the pointer
798 switch (getEntryKind()) {
799 case MachineJumpTableInfo::EK_BlockAddress:
800 return TD.getPointerABIAlignment();
801 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
802 return TD.getABIIntegerTypeAlignment(64);
803 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
804 case MachineJumpTableInfo::EK_LabelDifference32:
805 case MachineJumpTableInfo::EK_Custom32:
806 return TD.getABIIntegerTypeAlignment(32);
807 case MachineJumpTableInfo::EK_Inline:
810 llvm_unreachable("Unknown jump table encoding!");
813 /// Create a new jump table entry in the jump table info.
814 unsigned MachineJumpTableInfo::createJumpTableIndex(
815 const std::vector<MachineBasicBlock*> &DestBBs) {
816 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
817 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
818 return JumpTables.size()-1;
821 /// If Old is the target of any jump tables, update the jump tables to branch
823 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
824 MachineBasicBlock *New) {
825 assert(Old != New && "Not making a change?");
826 bool MadeChange = false;
827 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
828 ReplaceMBBInJumpTable(i, Old, New);
832 /// If Old is a target of the jump tables, update the jump table to branch to
834 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
835 MachineBasicBlock *Old,
836 MachineBasicBlock *New) {
837 assert(Old != New && "Not making a change?");
838 bool MadeChange = false;
839 MachineJumpTableEntry &JTE = JumpTables[Idx];
840 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
841 if (JTE.MBBs[j] == Old) {
848 void MachineJumpTableInfo::print(raw_ostream &OS) const {
849 if (JumpTables.empty()) return;
851 OS << "Jump Tables:\n";
853 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
854 OS << " jt#" << i << ": ";
855 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
856 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
862 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
863 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
867 //===----------------------------------------------------------------------===//
868 // MachineConstantPool implementation
869 //===----------------------------------------------------------------------===//
871 void MachineConstantPoolValue::anchor() { }
873 Type *MachineConstantPoolEntry::getType() const {
874 if (isMachineConstantPoolEntry())
875 return Val.MachineCPVal->getType();
876 return Val.ConstVal->getType();
879 bool MachineConstantPoolEntry::needsRelocation() const {
880 if (isMachineConstantPoolEntry())
882 return Val.ConstVal->needsRelocation();
886 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
887 if (needsRelocation())
888 return SectionKind::getReadOnlyWithRel();
889 switch (DL->getTypeAllocSize(getType())) {
891 return SectionKind::getMergeableConst4();
893 return SectionKind::getMergeableConst8();
895 return SectionKind::getMergeableConst16();
897 return SectionKind::getMergeableConst32();
899 return SectionKind::getReadOnly();
903 MachineConstantPool::~MachineConstantPool() {
904 // A constant may be a member of both Constants and MachineCPVsSharingEntries,
905 // so keep track of which we've deleted to avoid double deletions.
906 DenseSet<MachineConstantPoolValue*> Deleted;
907 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
908 if (Constants[i].isMachineConstantPoolEntry()) {
909 Deleted.insert(Constants[i].Val.MachineCPVal);
910 delete Constants[i].Val.MachineCPVal;
912 for (DenseSet<MachineConstantPoolValue*>::iterator I =
913 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
915 if (Deleted.count(*I) == 0)
920 /// Test whether the given two constants can be allocated the same constant pool
922 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
923 const DataLayout &DL) {
924 // Handle the trivial case quickly.
925 if (A == B) return true;
927 // If they have the same type but weren't the same constant, quickly
929 if (A->getType() == B->getType()) return false;
931 // We can't handle structs or arrays.
932 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
933 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
936 // For now, only support constants with the same size.
937 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
938 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
941 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
943 // Try constant folding a bitcast of both instructions to an integer. If we
944 // get two identical ConstantInt's, then we are good to share them. We use
945 // the constant folding APIs to do this so that we get the benefit of
947 if (isa<PointerType>(A->getType()))
948 A = ConstantFoldCastOperand(Instruction::PtrToInt,
949 const_cast<Constant *>(A), IntTy, DL);
950 else if (A->getType() != IntTy)
951 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
953 if (isa<PointerType>(B->getType()))
954 B = ConstantFoldCastOperand(Instruction::PtrToInt,
955 const_cast<Constant *>(B), IntTy, DL);
956 else if (B->getType() != IntTy)
957 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
963 /// Create a new entry in the constant pool or return an existing one.
964 /// User must specify the log2 of the minimum required alignment for the object.
965 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
966 unsigned Alignment) {
967 assert(Alignment && "Alignment must be specified!");
968 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
970 // Check to see if we already have this constant.
972 // FIXME, this could be made much more efficient for large constant pools.
973 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
974 if (!Constants[i].isMachineConstantPoolEntry() &&
975 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
976 if ((unsigned)Constants[i].getAlignment() < Alignment)
977 Constants[i].Alignment = Alignment;
981 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
982 return Constants.size()-1;
985 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
986 unsigned Alignment) {
987 assert(Alignment && "Alignment must be specified!");
988 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
990 // Check to see if we already have this constant.
992 // FIXME, this could be made much more efficient for large constant pools.
993 int Idx = V->getExistingMachineCPValue(this, Alignment);
995 MachineCPVsSharingEntries.insert(V);
996 return (unsigned)Idx;
999 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1000 return Constants.size()-1;
1003 void MachineConstantPool::print(raw_ostream &OS) const {
1004 if (Constants.empty()) return;
1006 OS << "Constant Pool:\n";
1007 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1008 OS << " cp#" << i << ": ";
1009 if (Constants[i].isMachineConstantPoolEntry())
1010 Constants[i].Val.MachineCPVal->print(OS);
1012 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1013 OS << ", align=" << Constants[i].getAlignment();
1018 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1019 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }