Another attempt to fix the build bot breaks after r360426
[llvm-core.git] / lib / CodeGen / MachineFunction.cpp
blobbcc523f9a2a83f5954dff10e8e0afe60f615a015
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.
13 //===----------------------------------------------------------------------===//
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/TargetLowering.h"
37 #include "llvm/CodeGen/TargetRegisterInfo.h"
38 #include "llvm/CodeGen/TargetSubtargetInfo.h"
39 #include "llvm/CodeGen/WasmEHFuncInfo.h"
40 #include "llvm/CodeGen/WinEHFuncInfo.h"
41 #include "llvm/Config/llvm-config.h"
42 #include "llvm/IR/Attributes.h"
43 #include "llvm/IR/BasicBlock.h"
44 #include "llvm/IR/Constant.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSlotTracker.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/MC/MCContext.h"
57 #include "llvm/MC/MCSymbol.h"
58 #include "llvm/MC/SectionKind.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/DOTGraphTraits.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/GraphWriter.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include <algorithm>
69 #include <cassert>
70 #include <cstddef>
71 #include <cstdint>
72 #include <iterator>
73 #include <string>
74 #include <utility>
75 #include <vector>
77 using namespace llvm;
79 #define DEBUG_TYPE "codegen"
81 static cl::opt<unsigned>
82 AlignAllFunctions("align-all-functions",
83 cl::desc("Force the alignment of all functions."),
84 cl::init(0), cl::Hidden);
86 static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
87 using P = MachineFunctionProperties::Property;
89 switch(Prop) {
90 case P::FailedISel: return "FailedISel";
91 case P::IsSSA: return "IsSSA";
92 case P::Legalized: return "Legalized";
93 case P::NoPHIs: return "NoPHIs";
94 case P::NoVRegs: return "NoVRegs";
95 case P::RegBankSelected: return "RegBankSelected";
96 case P::Selected: return "Selected";
97 case P::TracksLiveness: return "TracksLiveness";
99 llvm_unreachable("Invalid machine function property");
102 // Pin the vtable to this file.
103 void MachineFunction::Delegate::anchor() {}
105 void MachineFunctionProperties::print(raw_ostream &OS) const {
106 const char *Separator = "";
107 for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
108 if (!Properties[I])
109 continue;
110 OS << Separator << getPropertyName(static_cast<Property>(I));
111 Separator = ", ";
115 //===----------------------------------------------------------------------===//
116 // MachineFunction implementation
117 //===----------------------------------------------------------------------===//
119 // Out-of-line virtual method.
120 MachineFunctionInfo::~MachineFunctionInfo() = default;
122 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
123 MBB->getParent()->DeleteMachineBasicBlock(MBB);
126 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
127 const Function &F) {
128 if (F.hasFnAttribute(Attribute::StackAlignment))
129 return F.getFnStackAlignment();
130 return STI->getFrameLowering()->getStackAlignment();
133 MachineFunction::MachineFunction(const Function &F,
134 const LLVMTargetMachine &Target,
135 const TargetSubtargetInfo &STI,
136 unsigned FunctionNum, MachineModuleInfo &mmi)
137 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
138 FunctionNumber = FunctionNum;
139 init();
142 void MachineFunction::handleInsertion(MachineInstr &MI) {
143 if (TheDelegate)
144 TheDelegate->MF_HandleInsertion(MI);
147 void MachineFunction::handleRemoval(MachineInstr &MI) {
148 if (TheDelegate)
149 TheDelegate->MF_HandleRemoval(MI);
152 void MachineFunction::init() {
153 // Assume the function starts in SSA form with correct liveness.
154 Properties.set(MachineFunctionProperties::Property::IsSSA);
155 Properties.set(MachineFunctionProperties::Property::TracksLiveness);
156 if (STI->getRegisterInfo())
157 RegInfo = new (Allocator) MachineRegisterInfo(this);
158 else
159 RegInfo = nullptr;
161 MFInfo = nullptr;
162 // We can realign the stack if the target supports it and the user hasn't
163 // explicitly asked us not to.
164 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
165 !F.hasFnAttribute("no-realign-stack");
166 FrameInfo = new (Allocator) MachineFrameInfo(
167 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
168 /*ForceRealign=*/CanRealignSP &&
169 F.hasFnAttribute(Attribute::StackAlignment));
171 if (F.hasFnAttribute(Attribute::StackAlignment))
172 FrameInfo->ensureMaxAlignment(F.getFnStackAlignment());
174 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
175 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
177 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
178 // FIXME: Use Function::hasOptSize().
179 if (!F.hasFnAttribute(Attribute::OptimizeForSize))
180 Alignment = std::max(Alignment,
181 STI->getTargetLowering()->getPrefFunctionAlignment());
183 if (AlignAllFunctions)
184 Alignment = AlignAllFunctions;
186 JumpTableInfo = nullptr;
188 if (isFuncletEHPersonality(classifyEHPersonality(
189 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
190 WinEHInfo = new (Allocator) WinEHFuncInfo();
193 if (isScopedEHPersonality(classifyEHPersonality(
194 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
195 WasmEHInfo = new (Allocator) WasmEHFuncInfo();
198 assert(Target.isCompatibleDataLayout(getDataLayout()) &&
199 "Can't create a MachineFunction using a Module with a "
200 "Target-incompatible DataLayout attached\n");
202 PSVManager =
203 llvm::make_unique<PseudoSourceValueManager>(*(getSubtarget().
204 getInstrInfo()));
207 MachineFunction::~MachineFunction() {
208 clear();
211 void MachineFunction::clear() {
212 Properties.reset();
213 // Don't call destructors on MachineInstr and MachineOperand. All of their
214 // memory comes from the BumpPtrAllocator which is about to be purged.
216 // Do call MachineBasicBlock destructors, it contains std::vectors.
217 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
218 I->Insts.clearAndLeakNodesUnsafely();
219 MBBNumbering.clear();
221 InstructionRecycler.clear(Allocator);
222 OperandRecycler.clear(Allocator);
223 BasicBlockRecycler.clear(Allocator);
224 CodeViewAnnotations.clear();
225 VariableDbgInfos.clear();
226 if (RegInfo) {
227 RegInfo->~MachineRegisterInfo();
228 Allocator.Deallocate(RegInfo);
230 if (MFInfo) {
231 MFInfo->~MachineFunctionInfo();
232 Allocator.Deallocate(MFInfo);
235 FrameInfo->~MachineFrameInfo();
236 Allocator.Deallocate(FrameInfo);
238 ConstantPool->~MachineConstantPool();
239 Allocator.Deallocate(ConstantPool);
241 if (JumpTableInfo) {
242 JumpTableInfo->~MachineJumpTableInfo();
243 Allocator.Deallocate(JumpTableInfo);
246 if (WinEHInfo) {
247 WinEHInfo->~WinEHFuncInfo();
248 Allocator.Deallocate(WinEHInfo);
251 if (WasmEHInfo) {
252 WasmEHInfo->~WasmEHFuncInfo();
253 Allocator.Deallocate(WasmEHInfo);
257 const DataLayout &MachineFunction::getDataLayout() const {
258 return F.getParent()->getDataLayout();
261 /// Get the JumpTableInfo for this function.
262 /// If it does not already exist, allocate one.
263 MachineJumpTableInfo *MachineFunction::
264 getOrCreateJumpTableInfo(unsigned EntryKind) {
265 if (JumpTableInfo) return JumpTableInfo;
267 JumpTableInfo = new (Allocator)
268 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
269 return JumpTableInfo;
272 /// Should we be emitting segmented stack stuff for the function
273 bool MachineFunction::shouldSplitStack() const {
274 return getFunction().hasFnAttribute("split-stack");
277 LLVM_NODISCARD unsigned
278 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
279 FrameInstructions.push_back(Inst);
280 return FrameInstructions.size() - 1;
283 /// This discards all of the MachineBasicBlock numbers and recomputes them.
284 /// This guarantees that the MBB numbers are sequential, dense, and match the
285 /// ordering of the blocks within the function. If a specific MachineBasicBlock
286 /// is specified, only that block and those after it are renumbered.
287 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
288 if (empty()) { MBBNumbering.clear(); return; }
289 MachineFunction::iterator MBBI, E = end();
290 if (MBB == nullptr)
291 MBBI = begin();
292 else
293 MBBI = MBB->getIterator();
295 // Figure out the block number this should have.
296 unsigned BlockNo = 0;
297 if (MBBI != begin())
298 BlockNo = std::prev(MBBI)->getNumber() + 1;
300 for (; MBBI != E; ++MBBI, ++BlockNo) {
301 if (MBBI->getNumber() != (int)BlockNo) {
302 // Remove use of the old number.
303 if (MBBI->getNumber() != -1) {
304 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
305 "MBB number mismatch!");
306 MBBNumbering[MBBI->getNumber()] = nullptr;
309 // If BlockNo is already taken, set that block's number to -1.
310 if (MBBNumbering[BlockNo])
311 MBBNumbering[BlockNo]->setNumber(-1);
313 MBBNumbering[BlockNo] = &*MBBI;
314 MBBI->setNumber(BlockNo);
318 // Okay, all the blocks are renumbered. If we have compactified the block
319 // numbering, shrink MBBNumbering now.
320 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
321 MBBNumbering.resize(BlockNo);
324 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
325 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
326 const DebugLoc &DL,
327 bool NoImp) {
328 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
329 MachineInstr(*this, MCID, DL, NoImp);
332 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
333 /// identical in all ways except the instruction has no parent, prev, or next.
334 MachineInstr *
335 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
336 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
337 MachineInstr(*this, *Orig);
340 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
341 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
342 MachineInstr *FirstClone = nullptr;
343 MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
344 while (true) {
345 MachineInstr *Cloned = CloneMachineInstr(&*I);
346 MBB.insert(InsertBefore, Cloned);
347 if (FirstClone == nullptr) {
348 FirstClone = Cloned;
349 } else {
350 Cloned->bundleWithPred();
353 if (!I->isBundledWithSucc())
354 break;
355 ++I;
357 return *FirstClone;
360 /// Delete the given MachineInstr.
362 /// This function also serves as the MachineInstr destructor - the real
363 /// ~MachineInstr() destructor must be empty.
364 void
365 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
366 // Strip it for parts. The operand array and the MI object itself are
367 // independently recyclable.
368 if (MI->Operands)
369 deallocateOperandArray(MI->CapOperands, MI->Operands);
370 // Don't call ~MachineInstr() which must be trivial anyway because
371 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
372 // destructors.
373 InstructionRecycler.Deallocate(Allocator, MI);
376 /// Allocate a new MachineBasicBlock. Use this instead of
377 /// `new MachineBasicBlock'.
378 MachineBasicBlock *
379 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
380 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
381 MachineBasicBlock(*this, bb);
384 /// Delete the given MachineBasicBlock.
385 void
386 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
387 assert(MBB->getParent() == this && "MBB parent mismatch!");
388 MBB->~MachineBasicBlock();
389 BasicBlockRecycler.Deallocate(Allocator, MBB);
392 MachineMemOperand *MachineFunction::getMachineMemOperand(
393 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
394 unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
395 SyncScope::ID SSID, AtomicOrdering Ordering,
396 AtomicOrdering FailureOrdering) {
397 return new (Allocator)
398 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
399 SSID, Ordering, FailureOrdering);
402 MachineMemOperand *
403 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
404 int64_t Offset, uint64_t Size) {
405 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
407 // If there is no pointer value, the offset isn't tracked so we need to adjust
408 // the base alignment.
409 unsigned Align = PtrInfo.V.isNull()
410 ? MinAlign(MMO->getBaseAlignment(), Offset)
411 : MMO->getBaseAlignment();
413 return new (Allocator)
414 MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size,
415 Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(),
416 MMO->getOrdering(), MMO->getFailureOrdering());
419 MachineMemOperand *
420 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
421 const AAMDNodes &AAInfo) {
422 MachinePointerInfo MPI = MMO->getValue() ?
423 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
424 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
426 return new (Allocator)
427 MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
428 MMO->getBaseAlignment(), AAInfo,
429 MMO->getRanges(), MMO->getSyncScopeID(),
430 MMO->getOrdering(), MMO->getFailureOrdering());
433 MachineInstr::ExtraInfo *
434 MachineFunction::createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
435 MCSymbol *PreInstrSymbol,
436 MCSymbol *PostInstrSymbol) {
437 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
438 PostInstrSymbol);
441 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
442 char *Dest = Allocator.Allocate<char>(Name.size() + 1);
443 llvm::copy(Name, Dest);
444 Dest[Name.size()] = 0;
445 return Dest;
448 uint32_t *MachineFunction::allocateRegMask() {
449 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
450 unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
451 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
452 memset(Mask, 0, Size * sizeof(Mask[0]));
453 return Mask;
456 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
457 LLVM_DUMP_METHOD void MachineFunction::dump() const {
458 print(dbgs());
460 #endif
462 StringRef MachineFunction::getName() const {
463 return getFunction().getName();
466 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
467 OS << "# Machine code for function " << getName() << ": ";
468 getProperties().print(OS);
469 OS << '\n';
471 // Print Frame Information
472 FrameInfo->print(*this, OS);
474 // Print JumpTable Information
475 if (JumpTableInfo)
476 JumpTableInfo->print(OS);
478 // Print Constant Pool
479 ConstantPool->print(OS);
481 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
483 if (RegInfo && !RegInfo->livein_empty()) {
484 OS << "Function Live Ins: ";
485 for (MachineRegisterInfo::livein_iterator
486 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
487 OS << printReg(I->first, TRI);
488 if (I->second)
489 OS << " in " << printReg(I->second, TRI);
490 if (std::next(I) != E)
491 OS << ", ";
493 OS << '\n';
496 ModuleSlotTracker MST(getFunction().getParent());
497 MST.incorporateFunction(getFunction());
498 for (const auto &BB : *this) {
499 OS << '\n';
500 // If we print the whole function, print it at its most verbose level.
501 BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
504 OS << "\n# End machine code for function " << getName() << ".\n\n";
507 namespace llvm {
509 template<>
510 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
511 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
513 static std::string getGraphName(const MachineFunction *F) {
514 return ("CFG for '" + F->getName() + "' function").str();
517 std::string getNodeLabel(const MachineBasicBlock *Node,
518 const MachineFunction *Graph) {
519 std::string OutStr;
521 raw_string_ostream OSS(OutStr);
523 if (isSimple()) {
524 OSS << printMBBReference(*Node);
525 if (const BasicBlock *BB = Node->getBasicBlock())
526 OSS << ": " << BB->getName();
527 } else
528 Node->print(OSS);
531 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
533 // Process string output to make it nicer...
534 for (unsigned i = 0; i != OutStr.length(); ++i)
535 if (OutStr[i] == '\n') { // Left justify
536 OutStr[i] = '\\';
537 OutStr.insert(OutStr.begin()+i+1, 'l');
539 return OutStr;
543 } // end namespace llvm
545 void MachineFunction::viewCFG() const
547 #ifndef NDEBUG
548 ViewGraph(this, "mf" + getName());
549 #else
550 errs() << "MachineFunction::viewCFG is only available in debug builds on "
551 << "systems with Graphviz or gv!\n";
552 #endif // NDEBUG
555 void MachineFunction::viewCFGOnly() const
557 #ifndef NDEBUG
558 ViewGraph(this, "mf" + getName(), true);
559 #else
560 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
561 << "systems with Graphviz or gv!\n";
562 #endif // NDEBUG
565 /// Add the specified physical register as a live-in value and
566 /// create a corresponding virtual register for it.
567 unsigned MachineFunction::addLiveIn(unsigned PReg,
568 const TargetRegisterClass *RC) {
569 MachineRegisterInfo &MRI = getRegInfo();
570 unsigned VReg = MRI.getLiveInVirtReg(PReg);
571 if (VReg) {
572 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
573 (void)VRegRC;
574 // A physical register can be added several times.
575 // Between two calls, the register class of the related virtual register
576 // may have been constrained to match some operation constraints.
577 // In that case, check that the current register class includes the
578 // physical register and is a sub class of the specified RC.
579 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
580 RC->hasSubClassEq(VRegRC))) &&
581 "Register class mismatch!");
582 return VReg;
584 VReg = MRI.createVirtualRegister(RC);
585 MRI.addLiveIn(PReg, VReg);
586 return VReg;
589 /// Return the MCSymbol for the specified non-empty jump table.
590 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
591 /// normal 'L' label is returned.
592 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
593 bool isLinkerPrivate) const {
594 const DataLayout &DL = getDataLayout();
595 assert(JumpTableInfo && "No jump tables");
596 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
598 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
599 : DL.getPrivateGlobalPrefix();
600 SmallString<60> Name;
601 raw_svector_ostream(Name)
602 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
603 return Ctx.getOrCreateSymbol(Name);
606 /// Return a function-local symbol to represent the PIC base.
607 MCSymbol *MachineFunction::getPICBaseSymbol() const {
608 const DataLayout &DL = getDataLayout();
609 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
610 Twine(getFunctionNumber()) + "$pb");
613 /// \name Exception Handling
614 /// \{
616 LandingPadInfo &
617 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
618 unsigned N = LandingPads.size();
619 for (unsigned i = 0; i < N; ++i) {
620 LandingPadInfo &LP = LandingPads[i];
621 if (LP.LandingPadBlock == LandingPad)
622 return LP;
625 LandingPads.push_back(LandingPadInfo(LandingPad));
626 return LandingPads[N];
629 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
630 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
631 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
632 LP.BeginLabels.push_back(BeginLabel);
633 LP.EndLabels.push_back(EndLabel);
636 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
637 MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
638 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
639 LP.LandingPadLabel = LandingPadLabel;
641 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
642 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
643 if (const auto *PF =
644 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
645 getMMI().addPersonality(PF);
647 if (LPI->isCleanup())
648 addCleanup(LandingPad);
650 // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
651 // correct, but we need to do it this way because of how the DWARF EH
652 // emitter processes the clauses.
653 for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
654 Value *Val = LPI->getClause(I - 1);
655 if (LPI->isCatch(I - 1)) {
656 addCatchTypeInfo(LandingPad,
657 dyn_cast<GlobalValue>(Val->stripPointerCasts()));
658 } else {
659 // Add filters in a list.
660 auto *CVal = cast<Constant>(Val);
661 SmallVector<const GlobalValue *, 4> FilterList;
662 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
663 II != IE; ++II)
664 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
666 addFilterTypeInfo(LandingPad, FilterList);
670 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
671 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
672 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
673 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
676 } else {
677 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
680 return LandingPadLabel;
683 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
684 ArrayRef<const GlobalValue *> TyInfo) {
685 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
686 for (unsigned N = TyInfo.size(); N; --N)
687 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
690 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
691 ArrayRef<const GlobalValue *> TyInfo) {
692 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
693 std::vector<unsigned> IdsInFilter(TyInfo.size());
694 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
695 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
696 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
699 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
700 bool TidyIfNoBeginLabels) {
701 for (unsigned i = 0; i != LandingPads.size(); ) {
702 LandingPadInfo &LandingPad = LandingPads[i];
703 if (LandingPad.LandingPadLabel &&
704 !LandingPad.LandingPadLabel->isDefined() &&
705 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
706 LandingPad.LandingPadLabel = nullptr;
708 // Special case: we *should* emit LPs with null LP MBB. This indicates
709 // "nounwind" case.
710 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
711 LandingPads.erase(LandingPads.begin() + i);
712 continue;
715 if (TidyIfNoBeginLabels) {
716 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
717 MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
718 MCSymbol *EndLabel = LandingPad.EndLabels[j];
719 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
720 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
721 continue;
723 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
724 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
725 --j;
726 --e;
729 // Remove landing pads with no try-ranges.
730 if (LandingPads[i].BeginLabels.empty()) {
731 LandingPads.erase(LandingPads.begin() + i);
732 continue;
736 // If there is no landing pad, ensure that the list of typeids is empty.
737 // If the only typeid is a cleanup, this is the same as having no typeids.
738 if (!LandingPad.LandingPadBlock ||
739 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
740 LandingPad.TypeIds.clear();
741 ++i;
745 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
746 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
747 LP.TypeIds.push_back(0);
750 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
751 const Function *Filter,
752 const BlockAddress *RecoverBA) {
753 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
754 SEHHandler Handler;
755 Handler.FilterOrFinally = Filter;
756 Handler.RecoverBA = RecoverBA;
757 LP.SEHHandlers.push_back(Handler);
760 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
761 const Function *Cleanup) {
762 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
763 SEHHandler Handler;
764 Handler.FilterOrFinally = Cleanup;
765 Handler.RecoverBA = nullptr;
766 LP.SEHHandlers.push_back(Handler);
769 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
770 ArrayRef<unsigned> Sites) {
771 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
774 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
775 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
776 if (TypeInfos[i] == TI) return i + 1;
778 TypeInfos.push_back(TI);
779 return TypeInfos.size();
782 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
783 // If the new filter coincides with the tail of an existing filter, then
784 // re-use the existing filter. Folding filters more than this requires
785 // re-ordering filters and/or their elements - probably not worth it.
786 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
787 E = FilterEnds.end(); I != E; ++I) {
788 unsigned i = *I, j = TyIds.size();
790 while (i && j)
791 if (FilterIds[--i] != TyIds[--j])
792 goto try_next;
794 if (!j)
795 // The new filter coincides with range [i, end) of the existing filter.
796 return -(1 + i);
798 try_next:;
801 // Add the new filter.
802 int FilterID = -(1 + FilterIds.size());
803 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
804 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
805 FilterEnds.push_back(FilterIds.size());
806 FilterIds.push_back(0); // terminator
807 return FilterID;
810 void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I, MDNode *MD) {
811 MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true);
812 MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true);
813 I->setPreInstrSymbol(*this, BeginLabel);
814 I->setPostInstrSymbol(*this, EndLabel);
816 DIType *DI = dyn_cast<DIType>(MD);
817 CodeViewHeapAllocSites.push_back(std::make_tuple(BeginLabel, EndLabel, DI));
820 /// \}
822 //===----------------------------------------------------------------------===//
823 // MachineJumpTableInfo implementation
824 //===----------------------------------------------------------------------===//
826 /// Return the size of each entry in the jump table.
827 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
828 // The size of a jump table entry is 4 bytes unless the entry is just the
829 // address of a block, in which case it is the pointer size.
830 switch (getEntryKind()) {
831 case MachineJumpTableInfo::EK_BlockAddress:
832 return TD.getPointerSize();
833 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
834 return 8;
835 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
836 case MachineJumpTableInfo::EK_LabelDifference32:
837 case MachineJumpTableInfo::EK_Custom32:
838 return 4;
839 case MachineJumpTableInfo::EK_Inline:
840 return 0;
842 llvm_unreachable("Unknown jump table encoding!");
845 /// Return the alignment of each entry in the jump table.
846 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
847 // The alignment of a jump table entry is the alignment of int32 unless the
848 // entry is just the address of a block, in which case it is the pointer
849 // alignment.
850 switch (getEntryKind()) {
851 case MachineJumpTableInfo::EK_BlockAddress:
852 return TD.getPointerABIAlignment(0);
853 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
854 return TD.getABIIntegerTypeAlignment(64);
855 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
856 case MachineJumpTableInfo::EK_LabelDifference32:
857 case MachineJumpTableInfo::EK_Custom32:
858 return TD.getABIIntegerTypeAlignment(32);
859 case MachineJumpTableInfo::EK_Inline:
860 return 1;
862 llvm_unreachable("Unknown jump table encoding!");
865 /// Create a new jump table entry in the jump table info.
866 unsigned MachineJumpTableInfo::createJumpTableIndex(
867 const std::vector<MachineBasicBlock*> &DestBBs) {
868 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
869 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
870 return JumpTables.size()-1;
873 /// If Old is the target of any jump tables, update the jump tables to branch
874 /// to New instead.
875 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
876 MachineBasicBlock *New) {
877 assert(Old != New && "Not making a change?");
878 bool MadeChange = false;
879 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
880 ReplaceMBBInJumpTable(i, Old, New);
881 return MadeChange;
884 /// If Old is a target of the jump tables, update the jump table to branch to
885 /// New instead.
886 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
887 MachineBasicBlock *Old,
888 MachineBasicBlock *New) {
889 assert(Old != New && "Not making a change?");
890 bool MadeChange = false;
891 MachineJumpTableEntry &JTE = JumpTables[Idx];
892 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
893 if (JTE.MBBs[j] == Old) {
894 JTE.MBBs[j] = New;
895 MadeChange = true;
897 return MadeChange;
900 void MachineJumpTableInfo::print(raw_ostream &OS) const {
901 if (JumpTables.empty()) return;
903 OS << "Jump Tables:\n";
905 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
906 OS << printJumpTableEntryReference(i) << ": ";
907 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
908 OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
911 OS << '\n';
914 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
915 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
916 #endif
918 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
919 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
922 //===----------------------------------------------------------------------===//
923 // MachineConstantPool implementation
924 //===----------------------------------------------------------------------===//
926 void MachineConstantPoolValue::anchor() {}
928 Type *MachineConstantPoolEntry::getType() const {
929 if (isMachineConstantPoolEntry())
930 return Val.MachineCPVal->getType();
931 return Val.ConstVal->getType();
934 bool MachineConstantPoolEntry::needsRelocation() const {
935 if (isMachineConstantPoolEntry())
936 return true;
937 return Val.ConstVal->needsRelocation();
940 SectionKind
941 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
942 if (needsRelocation())
943 return SectionKind::getReadOnlyWithRel();
944 switch (DL->getTypeAllocSize(getType())) {
945 case 4:
946 return SectionKind::getMergeableConst4();
947 case 8:
948 return SectionKind::getMergeableConst8();
949 case 16:
950 return SectionKind::getMergeableConst16();
951 case 32:
952 return SectionKind::getMergeableConst32();
953 default:
954 return SectionKind::getReadOnly();
958 MachineConstantPool::~MachineConstantPool() {
959 // A constant may be a member of both Constants and MachineCPVsSharingEntries,
960 // so keep track of which we've deleted to avoid double deletions.
961 DenseSet<MachineConstantPoolValue*> Deleted;
962 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
963 if (Constants[i].isMachineConstantPoolEntry()) {
964 Deleted.insert(Constants[i].Val.MachineCPVal);
965 delete Constants[i].Val.MachineCPVal;
967 for (DenseSet<MachineConstantPoolValue*>::iterator I =
968 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
969 I != E; ++I) {
970 if (Deleted.count(*I) == 0)
971 delete *I;
975 /// Test whether the given two constants can be allocated the same constant pool
976 /// entry.
977 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
978 const DataLayout &DL) {
979 // Handle the trivial case quickly.
980 if (A == B) return true;
982 // If they have the same type but weren't the same constant, quickly
983 // reject them.
984 if (A->getType() == B->getType()) return false;
986 // We can't handle structs or arrays.
987 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
988 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
989 return false;
991 // For now, only support constants with the same size.
992 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
993 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
994 return false;
996 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
998 // Try constant folding a bitcast of both instructions to an integer. If we
999 // get two identical ConstantInt's, then we are good to share them. We use
1000 // the constant folding APIs to do this so that we get the benefit of
1001 // DataLayout.
1002 if (isa<PointerType>(A->getType()))
1003 A = ConstantFoldCastOperand(Instruction::PtrToInt,
1004 const_cast<Constant *>(A), IntTy, DL);
1005 else if (A->getType() != IntTy)
1006 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1007 IntTy, DL);
1008 if (isa<PointerType>(B->getType()))
1009 B = ConstantFoldCastOperand(Instruction::PtrToInt,
1010 const_cast<Constant *>(B), IntTy, DL);
1011 else if (B->getType() != IntTy)
1012 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1013 IntTy, DL);
1015 return A == B;
1018 /// Create a new entry in the constant pool or return an existing one.
1019 /// User must specify the log2 of the minimum required alignment for the object.
1020 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1021 unsigned Alignment) {
1022 assert(Alignment && "Alignment must be specified!");
1023 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1025 // Check to see if we already have this constant.
1027 // FIXME, this could be made much more efficient for large constant pools.
1028 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1029 if (!Constants[i].isMachineConstantPoolEntry() &&
1030 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1031 if ((unsigned)Constants[i].getAlignment() < Alignment)
1032 Constants[i].Alignment = Alignment;
1033 return i;
1036 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1037 return Constants.size()-1;
1040 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1041 unsigned Alignment) {
1042 assert(Alignment && "Alignment must be specified!");
1043 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1045 // Check to see if we already have this constant.
1047 // FIXME, this could be made much more efficient for large constant pools.
1048 int Idx = V->getExistingMachineCPValue(this, Alignment);
1049 if (Idx != -1) {
1050 MachineCPVsSharingEntries.insert(V);
1051 return (unsigned)Idx;
1054 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1055 return Constants.size()-1;
1058 void MachineConstantPool::print(raw_ostream &OS) const {
1059 if (Constants.empty()) return;
1061 OS << "Constant Pool:\n";
1062 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1063 OS << " cp#" << i << ": ";
1064 if (Constants[i].isMachineConstantPoolEntry())
1065 Constants[i].Val.MachineCPVal->print(OS);
1066 else
1067 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1068 OS << ", align=" << Constants[i].getAlignment();
1069 OS << "\n";
1073 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1074 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1075 #endif