1044eb2f6SDimitry Andric //===- MachineFunction.cpp ------------------------------------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // Collect native machine code information for a function. This allows
10009b1c42SEd Schouten // target-specific information about the generated code to be stored with each
11009b1c42SEd Schouten // function.
12009b1c42SEd Schouten //
13009b1c42SEd Schouten //===----------------------------------------------------------------------===//
14009b1c42SEd Schouten
1559850d08SRoman Divacky #include "llvm/CodeGen/MachineFunction.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/BitVector.h"
17044eb2f6SDimitry Andric #include "llvm/ADT/DenseMap.h"
18044eb2f6SDimitry Andric #include "llvm/ADT/DenseSet.h"
194a16efa3SDimitry Andric #include "llvm/ADT/STLExtras.h"
204a16efa3SDimitry Andric #include "llvm/ADT/SmallString.h"
21044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
22044eb2f6SDimitry Andric #include "llvm/ADT/StringRef.h"
23044eb2f6SDimitry Andric #include "llvm/ADT/Twine.h"
244a16efa3SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
257fa27ce4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
26044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
2763faed5bSDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
28009b1c42SEd Schouten #include "llvm/CodeGen/MachineFrameInfo.h"
29009b1c42SEd Schouten #include "llvm/CodeGen/MachineInstr.h"
30009b1c42SEd Schouten #include "llvm/CodeGen/MachineJumpTableInfo.h"
31044eb2f6SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
329f4a1da9SRoman Divacky #include "llvm/CodeGen/MachineModuleInfo.h"
33009b1c42SEd Schouten #include "llvm/CodeGen/MachineRegisterInfo.h"
34dd58ef01SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
35b1c73532SDimitry Andric #include "llvm/CodeGen/PseudoSourceValueManager.h"
36044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
37cfca06d7SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
38044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
39044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
40044eb2f6SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
41eb11fae6SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
42dd58ef01SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
43eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
44044eb2f6SDimitry Andric #include "llvm/IR/Attributes.h"
45044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
46044eb2f6SDimitry Andric #include "llvm/IR/Constant.h"
474a16efa3SDimitry Andric #include "llvm/IR/DataLayout.h"
48044eb2f6SDimitry Andric #include "llvm/IR/DerivedTypes.h"
497fa27ce4SDimitry Andric #include "llvm/IR/EHPersonalities.h"
504a16efa3SDimitry Andric #include "llvm/IR/Function.h"
51044eb2f6SDimitry Andric #include "llvm/IR/GlobalValue.h"
52044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
53044eb2f6SDimitry Andric #include "llvm/IR/Instructions.h"
54044eb2f6SDimitry Andric #include "llvm/IR/Metadata.h"
55ee8648bdSDimitry Andric #include "llvm/IR/Module.h"
561a82d4c0SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
57044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
586fe5c7aaSRoman Divacky #include "llvm/MC/MCContext.h"
59044eb2f6SDimitry Andric #include "llvm/MC/MCSymbol.h"
60044eb2f6SDimitry Andric #include "llvm/MC/SectionKind.h"
61044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
62044eb2f6SDimitry Andric #include "llvm/Support/CommandLine.h"
63044eb2f6SDimitry Andric #include "llvm/Support/Compiler.h"
64044eb2f6SDimitry Andric #include "llvm/Support/DOTGraphTraits.h"
65044eb2f6SDimitry Andric #include "llvm/Support/ErrorHandling.h"
66009b1c42SEd Schouten #include "llvm/Support/GraphWriter.h"
67009b1c42SEd Schouten #include "llvm/Support/raw_ostream.h"
684a16efa3SDimitry Andric #include "llvm/Target/TargetMachine.h"
69044eb2f6SDimitry Andric #include <algorithm>
70044eb2f6SDimitry Andric #include <cassert>
71044eb2f6SDimitry Andric #include <cstddef>
72044eb2f6SDimitry Andric #include <cstdint>
73044eb2f6SDimitry Andric #include <iterator>
74044eb2f6SDimitry Andric #include <string>
75cfca06d7SDimitry Andric #include <type_traits>
76044eb2f6SDimitry Andric #include <utility>
77044eb2f6SDimitry Andric #include <vector>
78044eb2f6SDimitry Andric
796f8fc217SDimitry Andric #include "LiveDebugValues/LiveDebugValues.h"
806f8fc217SDimitry Andric
81009b1c42SEd Schouten using namespace llvm;
82009b1c42SEd Schouten
835ca98fd9SDimitry Andric #define DEBUG_TYPE "codegen"
845ca98fd9SDimitry Andric
851d5ae102SDimitry Andric static cl::opt<unsigned> AlignAllFunctions(
861d5ae102SDimitry Andric "align-all-functions",
871d5ae102SDimitry Andric cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
881d5ae102SDimitry Andric "means align on 16B boundaries)."),
89dd58ef01SDimitry Andric cl::init(0), cl::Hidden);
90dd58ef01SDimitry Andric
getPropertyName(MachineFunctionProperties::Property Prop)91b915e9e0SDimitry Andric static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
92044eb2f6SDimitry Andric using P = MachineFunctionProperties::Property;
93044eb2f6SDimitry Andric
9477fc4c14SDimitry Andric // clang-format off
95b915e9e0SDimitry Andric switch(Prop) {
96b915e9e0SDimitry Andric case P::FailedISel: return "FailedISel";
97b915e9e0SDimitry Andric case P::IsSSA: return "IsSSA";
98b915e9e0SDimitry Andric case P::Legalized: return "Legalized";
99b915e9e0SDimitry Andric case P::NoPHIs: return "NoPHIs";
100b915e9e0SDimitry Andric case P::NoVRegs: return "NoVRegs";
101b915e9e0SDimitry Andric case P::RegBankSelected: return "RegBankSelected";
102b915e9e0SDimitry Andric case P::Selected: return "Selected";
103b915e9e0SDimitry Andric case P::TracksLiveness: return "TracksLiveness";
104cfca06d7SDimitry Andric case P::TiedOpsRewritten: return "TiedOpsRewritten";
105c0981da4SDimitry Andric case P::FailsVerification: return "FailsVerification";
10677fc4c14SDimitry Andric case P::TracksDebugUserValues: return "TracksDebugUserValues";
107b915e9e0SDimitry Andric }
10877fc4c14SDimitry Andric // clang-format on
109b915e9e0SDimitry Andric llvm_unreachable("Invalid machine function property");
110b915e9e0SDimitry Andric }
111b915e9e0SDimitry Andric
setUnsafeStackSize(const Function & F,MachineFrameInfo & FrameInfo)112145449b1SDimitry Andric void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo) {
113145449b1SDimitry Andric if (!F.hasFnAttribute(Attribute::SafeStack))
114145449b1SDimitry Andric return;
115145449b1SDimitry Andric
116145449b1SDimitry Andric auto *Existing =
117145449b1SDimitry Andric dyn_cast_or_null<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
118145449b1SDimitry Andric
119145449b1SDimitry Andric if (!Existing || Existing->getNumOperands() != 2)
120145449b1SDimitry Andric return;
121145449b1SDimitry Andric
122145449b1SDimitry Andric auto *MetadataName = "unsafe-stack-size";
123145449b1SDimitry Andric if (auto &N = Existing->getOperand(0)) {
1247fa27ce4SDimitry Andric if (N.equalsStr(MetadataName)) {
125145449b1SDimitry Andric if (auto &Op = Existing->getOperand(1)) {
126145449b1SDimitry Andric auto Val = mdconst::extract<ConstantInt>(Op)->getZExtValue();
127145449b1SDimitry Andric FrameInfo.setUnsafeStackSize(Val);
128145449b1SDimitry Andric }
129145449b1SDimitry Andric }
130145449b1SDimitry Andric }
131145449b1SDimitry Andric }
132145449b1SDimitry Andric
133d8e91e46SDimitry Andric // Pin the vtable to this file.
anchor()134d8e91e46SDimitry Andric void MachineFunction::Delegate::anchor() {}
135d8e91e46SDimitry Andric
print(raw_ostream & OS) const136b915e9e0SDimitry Andric void MachineFunctionProperties::print(raw_ostream &OS) const {
137b915e9e0SDimitry Andric const char *Separator = "";
138b915e9e0SDimitry Andric for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
139b915e9e0SDimitry Andric if (!Properties[I])
14001095a5dSDimitry Andric continue;
141b915e9e0SDimitry Andric OS << Separator << getPropertyName(static_cast<Property>(I));
142b915e9e0SDimitry Andric Separator = ", ";
14301095a5dSDimitry Andric }
14401095a5dSDimitry Andric }
14501095a5dSDimitry Andric
1466fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
147009b1c42SEd Schouten // MachineFunction implementation
1486fe5c7aaSRoman Divacky //===----------------------------------------------------------------------===//
149009b1c42SEd Schouten
1503a0822f0SDimitry Andric // Out-of-line virtual method.
151044eb2f6SDimitry Andric MachineFunctionInfo::~MachineFunctionInfo() = default;
15259850d08SRoman Divacky
deleteNode(MachineBasicBlock * MBB)153b915e9e0SDimitry Andric void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
15477fc4c14SDimitry Andric MBB->getParent()->deleteMachineBasicBlock(MBB);
155009b1c42SEd Schouten }
156009b1c42SEd Schouten
getFnStackAlignment(const TargetSubtargetInfo * STI,const Function & F)157145449b1SDimitry Andric static inline Align getFnStackAlignment(const TargetSubtargetInfo *STI,
158044eb2f6SDimitry Andric const Function &F) {
159c0981da4SDimitry Andric if (auto MA = F.getFnStackAlign())
160145449b1SDimitry Andric return *MA;
161145449b1SDimitry Andric return STI->getFrameLowering()->getStackAlign();
16201095a5dSDimitry Andric }
16301095a5dSDimitry Andric
MachineFunction(Function & F,const LLVMTargetMachine & Target,const TargetSubtargetInfo & STI,unsigned FunctionNum,MachineModuleInfo & mmi)164cfca06d7SDimitry Andric MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
165044eb2f6SDimitry Andric const TargetSubtargetInfo &STI,
16667c32a98SDimitry Andric unsigned FunctionNum, MachineModuleInfo &mmi)
167044eb2f6SDimitry Andric : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
168b915e9e0SDimitry Andric FunctionNumber = FunctionNum;
169b915e9e0SDimitry Andric init();
170b915e9e0SDimitry Andric }
171b915e9e0SDimitry Andric
handleInsertion(MachineInstr & MI)172d8e91e46SDimitry Andric void MachineFunction::handleInsertion(MachineInstr &MI) {
173d8e91e46SDimitry Andric if (TheDelegate)
174d8e91e46SDimitry Andric TheDelegate->MF_HandleInsertion(MI);
175d8e91e46SDimitry Andric }
176d8e91e46SDimitry Andric
handleRemoval(MachineInstr & MI)177d8e91e46SDimitry Andric void MachineFunction::handleRemoval(MachineInstr &MI) {
178d8e91e46SDimitry Andric if (TheDelegate)
179d8e91e46SDimitry Andric TheDelegate->MF_HandleRemoval(MI);
180d8e91e46SDimitry Andric }
181d8e91e46SDimitry Andric
handleChangeDesc(MachineInstr & MI,const MCInstrDesc & TID)182b1c73532SDimitry Andric void MachineFunction::handleChangeDesc(MachineInstr &MI,
183b1c73532SDimitry Andric const MCInstrDesc &TID) {
184b1c73532SDimitry Andric if (TheDelegate)
185b1c73532SDimitry Andric TheDelegate->MF_HandleChangeDesc(MI, TID);
186b1c73532SDimitry Andric }
187b1c73532SDimitry Andric
init()188b915e9e0SDimitry Andric void MachineFunction::init() {
18901095a5dSDimitry Andric // Assume the function starts in SSA form with correct liveness.
19001095a5dSDimitry Andric Properties.set(MachineFunctionProperties::Property::IsSSA);
19101095a5dSDimitry Andric Properties.set(MachineFunctionProperties::Property::TracksLiveness);
19267c32a98SDimitry Andric if (STI->getRegisterInfo())
19367c32a98SDimitry Andric RegInfo = new (Allocator) MachineRegisterInfo(this);
194009b1c42SEd Schouten else
1955ca98fd9SDimitry Andric RegInfo = nullptr;
196f8af5cf6SDimitry Andric
1975ca98fd9SDimitry Andric MFInfo = nullptr;
198e3b55780SDimitry Andric
19901095a5dSDimitry Andric // We can realign the stack if the target supports it and the user hasn't
20001095a5dSDimitry Andric // explicitly asked us not to.
20101095a5dSDimitry Andric bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
202044eb2f6SDimitry Andric !F.hasFnAttribute("no-realign-stack");
203ac9a064cSDimitry Andric bool ForceRealignSP = F.hasFnAttribute(Attribute::StackAlignment) ||
204ac9a064cSDimitry Andric F.hasFnAttribute("stackrealign");
20501095a5dSDimitry Andric FrameInfo = new (Allocator) MachineFrameInfo(
206044eb2f6SDimitry Andric getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
207ac9a064cSDimitry Andric /*ForcedRealign=*/ForceRealignSP && CanRealignSP);
208f8af5cf6SDimitry Andric
209145449b1SDimitry Andric setUnsafeStackSize(F, *FrameInfo);
210145449b1SDimitry Andric
211044eb2f6SDimitry Andric if (F.hasFnAttribute(Attribute::StackAlignment))
212cfca06d7SDimitry Andric FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
213f8af5cf6SDimitry Andric
214ee8648bdSDimitry Andric ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
21567c32a98SDimitry Andric Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
216f8af5cf6SDimitry Andric
217044eb2f6SDimitry Andric // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
218e6d15924SDimitry Andric // FIXME: Use Function::hasOptSize().
219044eb2f6SDimitry Andric if (!F.hasFnAttribute(Attribute::OptimizeForSize))
22056fe8f14SDimitry Andric Alignment = std::max(Alignment,
22167c32a98SDimitry Andric STI->getTargetLowering()->getPrefFunctionAlignment());
222f8af5cf6SDimitry Andric
2237fa27ce4SDimitry Andric // -fsanitize=function and -fsanitize=kcfi instrument indirect function calls
2247fa27ce4SDimitry Andric // to load a type hash before the function label. Ensure functions are aligned
2257fa27ce4SDimitry Andric // by a least 4 to avoid unaligned access, which is especially important for
2267fa27ce4SDimitry Andric // -mno-unaligned-access.
2277fa27ce4SDimitry Andric if (F.hasMetadata(LLVMContext::MD_func_sanitize) ||
2287fa27ce4SDimitry Andric F.getMetadata(LLVMContext::MD_kcfi_type))
2297fa27ce4SDimitry Andric Alignment = std::max(Alignment, Align(4));
2307fa27ce4SDimitry Andric
231dd58ef01SDimitry Andric if (AlignAllFunctions)
2321d5ae102SDimitry Andric Alignment = Align(1ULL << AlignAllFunctions);
233dd58ef01SDimitry Andric
2345ca98fd9SDimitry Andric JumpTableInfo = nullptr;
235dd58ef01SDimitry Andric
236dd58ef01SDimitry Andric if (isFuncletEHPersonality(classifyEHPersonality(
237044eb2f6SDimitry Andric F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
238dd58ef01SDimitry Andric WinEHInfo = new (Allocator) WinEHFuncInfo();
239dd58ef01SDimitry Andric }
240dd58ef01SDimitry Andric
241eb11fae6SDimitry Andric if (isScopedEHPersonality(classifyEHPersonality(
242eb11fae6SDimitry Andric F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
243eb11fae6SDimitry Andric WasmEHInfo = new (Allocator) WasmEHFuncInfo();
244eb11fae6SDimitry Andric }
245eb11fae6SDimitry Andric
246b915e9e0SDimitry Andric assert(Target.isCompatibleDataLayout(getDataLayout()) &&
247dd58ef01SDimitry Andric "Can't create a MachineFunction using a Module with a "
248dd58ef01SDimitry Andric "Target-incompatible DataLayout attached\n");
249dd58ef01SDimitry Andric
250145449b1SDimitry Andric PSVManager = std::make_unique<PseudoSourceValueManager>(getTarget());
251009b1c42SEd Schouten }
252009b1c42SEd Schouten
initTargetMachineFunctionInfo(const TargetSubtargetInfo & STI)253e3b55780SDimitry Andric void MachineFunction::initTargetMachineFunctionInfo(
254e3b55780SDimitry Andric const TargetSubtargetInfo &STI) {
255e3b55780SDimitry Andric assert(!MFInfo && "MachineFunctionInfo already set");
256e3b55780SDimitry Andric MFInfo = Target.createMachineFunctionInfo(Allocator, F, &STI);
257e3b55780SDimitry Andric }
258e3b55780SDimitry Andric
~MachineFunction()259009b1c42SEd Schouten MachineFunction::~MachineFunction() {
260b915e9e0SDimitry Andric clear();
261b915e9e0SDimitry Andric }
262b915e9e0SDimitry Andric
clear()263b915e9e0SDimitry Andric void MachineFunction::clear() {
264b915e9e0SDimitry Andric Properties.reset();
2654a16efa3SDimitry Andric // Don't call destructors on MachineInstr and MachineOperand. All of their
2664a16efa3SDimitry Andric // memory comes from the BumpPtrAllocator which is about to be purged.
2674a16efa3SDimitry Andric //
2684a16efa3SDimitry Andric // Do call MachineBasicBlock destructors, it contains std::vectors.
2694a16efa3SDimitry Andric for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
2704a16efa3SDimitry Andric I->Insts.clearAndLeakNodesUnsafely();
271eb11fae6SDimitry Andric MBBNumbering.clear();
2724a16efa3SDimitry Andric
273009b1c42SEd Schouten InstructionRecycler.clear(Allocator);
2744a16efa3SDimitry Andric OperandRecycler.clear(Allocator);
275009b1c42SEd Schouten BasicBlockRecycler.clear(Allocator);
276044eb2f6SDimitry Andric CodeViewAnnotations.clear();
27771d5a254SDimitry Andric VariableDbgInfos.clear();
278f859468fSEd Schouten if (RegInfo) {
279f859468fSEd Schouten RegInfo->~MachineRegisterInfo();
280f859468fSEd Schouten Allocator.Deallocate(RegInfo);
281f859468fSEd Schouten }
282009b1c42SEd Schouten if (MFInfo) {
283f859468fSEd Schouten MFInfo->~MachineFunctionInfo();
284f859468fSEd Schouten Allocator.Deallocate(MFInfo);
285009b1c42SEd Schouten }
28658b69754SDimitry Andric
28758b69754SDimitry Andric FrameInfo->~MachineFrameInfo();
28858b69754SDimitry Andric Allocator.Deallocate(FrameInfo);
28958b69754SDimitry Andric
29058b69754SDimitry Andric ConstantPool->~MachineConstantPool();
29158b69754SDimitry Andric Allocator.Deallocate(ConstantPool);
2926fe5c7aaSRoman Divacky
2936fe5c7aaSRoman Divacky if (JumpTableInfo) {
2946fe5c7aaSRoman Divacky JumpTableInfo->~MachineJumpTableInfo();
2956fe5c7aaSRoman Divacky Allocator.Deallocate(JumpTableInfo);
2966fe5c7aaSRoman Divacky }
297dd58ef01SDimitry Andric
298dd58ef01SDimitry Andric if (WinEHInfo) {
299dd58ef01SDimitry Andric WinEHInfo->~WinEHFuncInfo();
300dd58ef01SDimitry Andric Allocator.Deallocate(WinEHInfo);
301dd58ef01SDimitry Andric }
302d8e91e46SDimitry Andric
303d8e91e46SDimitry Andric if (WasmEHInfo) {
304d8e91e46SDimitry Andric WasmEHInfo->~WasmEHFuncInfo();
305d8e91e46SDimitry Andric Allocator.Deallocate(WasmEHInfo);
306d8e91e46SDimitry Andric }
307009b1c42SEd Schouten }
308009b1c42SEd Schouten
getDataLayout() const309ee8648bdSDimitry Andric const DataLayout &MachineFunction::getDataLayout() const {
310ac9a064cSDimitry Andric return F.getDataLayout();
311ee8648bdSDimitry Andric }
312ee8648bdSDimitry Andric
3133a0822f0SDimitry Andric /// Get the JumpTableInfo for this function.
3143a0822f0SDimitry Andric /// If it does not already exist, allocate one.
3156fe5c7aaSRoman Divacky MachineJumpTableInfo *MachineFunction::
getOrCreateJumpTableInfo(unsigned EntryKind)3166fe5c7aaSRoman Divacky getOrCreateJumpTableInfo(unsigned EntryKind) {
3176fe5c7aaSRoman Divacky if (JumpTableInfo) return JumpTableInfo;
3186fe5c7aaSRoman Divacky
3192f12f10aSRoman Divacky JumpTableInfo = new (Allocator)
3206fe5c7aaSRoman Divacky MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
3216fe5c7aaSRoman Divacky return JumpTableInfo;
3226fe5c7aaSRoman Divacky }
323009b1c42SEd Schouten
getDenormalMode(const fltSemantics & FPType) const324706b4fc4SDimitry Andric DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
325b60736ecSDimitry Andric return F.getDenormalMode(FPType);
326706b4fc4SDimitry Andric }
327706b4fc4SDimitry Andric
3285ca98fd9SDimitry Andric /// Should we be emitting segmented stack stuff for the function
shouldSplitStack() const329dadbdfffSDimitry Andric bool MachineFunction::shouldSplitStack() const {
330044eb2f6SDimitry Andric return getFunction().hasFnAttribute("split-stack");
3315ca98fd9SDimitry Andric }
3325ca98fd9SDimitry Andric
333e3b55780SDimitry Andric [[nodiscard]] unsigned
addFrameInst(const MCCFIInstruction & Inst)334e6d15924SDimitry Andric MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
335e6d15924SDimitry Andric FrameInstructions.push_back(Inst);
336e6d15924SDimitry Andric return FrameInstructions.size() - 1;
337e6d15924SDimitry Andric }
338e6d15924SDimitry Andric
3393a0822f0SDimitry Andric /// This discards all of the MachineBasicBlock numbers and recomputes them.
3403a0822f0SDimitry Andric /// This guarantees that the MBB numbers are sequential, dense, and match the
3413a0822f0SDimitry Andric /// ordering of the blocks within the function. If a specific MachineBasicBlock
3423a0822f0SDimitry Andric /// is specified, only that block and those after it are renumbered.
RenumberBlocks(MachineBasicBlock * MBB)343009b1c42SEd Schouten void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
344009b1c42SEd Schouten if (empty()) { MBBNumbering.clear(); return; }
345009b1c42SEd Schouten MachineFunction::iterator MBBI, E = end();
3465ca98fd9SDimitry Andric if (MBB == nullptr)
347009b1c42SEd Schouten MBBI = begin();
348009b1c42SEd Schouten else
349dd58ef01SDimitry Andric MBBI = MBB->getIterator();
350009b1c42SEd Schouten
351009b1c42SEd Schouten // Figure out the block number this should have.
352009b1c42SEd Schouten unsigned BlockNo = 0;
353009b1c42SEd Schouten if (MBBI != begin())
3545ca98fd9SDimitry Andric BlockNo = std::prev(MBBI)->getNumber() + 1;
355009b1c42SEd Schouten
356009b1c42SEd Schouten for (; MBBI != E; ++MBBI, ++BlockNo) {
357009b1c42SEd Schouten if (MBBI->getNumber() != (int)BlockNo) {
358009b1c42SEd Schouten // Remove use of the old number.
359009b1c42SEd Schouten if (MBBI->getNumber() != -1) {
360009b1c42SEd Schouten assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
361009b1c42SEd Schouten "MBB number mismatch!");
3625ca98fd9SDimitry Andric MBBNumbering[MBBI->getNumber()] = nullptr;
363009b1c42SEd Schouten }
364009b1c42SEd Schouten
365009b1c42SEd Schouten // If BlockNo is already taken, set that block's number to -1.
366009b1c42SEd Schouten if (MBBNumbering[BlockNo])
367009b1c42SEd Schouten MBBNumbering[BlockNo]->setNumber(-1);
368009b1c42SEd Schouten
369dd58ef01SDimitry Andric MBBNumbering[BlockNo] = &*MBBI;
370009b1c42SEd Schouten MBBI->setNumber(BlockNo);
371009b1c42SEd Schouten }
372009b1c42SEd Schouten }
373009b1c42SEd Schouten
374009b1c42SEd Schouten // Okay, all the blocks are renumbered. If we have compactified the block
375009b1c42SEd Schouten // numbering, shrink MBBNumbering now.
376009b1c42SEd Schouten assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
377009b1c42SEd Schouten MBBNumbering.resize(BlockNo);
378009b1c42SEd Schouten }
379009b1c42SEd Schouten
380cfca06d7SDimitry Andric /// This method iterates over the basic blocks and assigns their IsBeginSection
381cfca06d7SDimitry Andric /// and IsEndSection fields. This must be called after MBB layout is finalized
382cfca06d7SDimitry Andric /// and the SectionID's are assigned to MBBs.
assignBeginEndSections()383cfca06d7SDimitry Andric void MachineFunction::assignBeginEndSections() {
384cfca06d7SDimitry Andric front().setIsBeginSection();
385cfca06d7SDimitry Andric auto CurrentSectionID = front().getSectionID();
386cfca06d7SDimitry Andric for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
387cfca06d7SDimitry Andric if (MBBI->getSectionID() == CurrentSectionID)
388cfca06d7SDimitry Andric continue;
389cfca06d7SDimitry Andric MBBI->setIsBeginSection();
390cfca06d7SDimitry Andric std::prev(MBBI)->setIsEndSection();
391cfca06d7SDimitry Andric CurrentSectionID = MBBI->getSectionID();
392cfca06d7SDimitry Andric }
393cfca06d7SDimitry Andric back().setIsEndSection();
394cfca06d7SDimitry Andric }
395cfca06d7SDimitry Andric
3963a0822f0SDimitry Andric /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
CreateMachineInstr(const MCInstrDesc & MCID,DebugLoc DL,bool NoImplicit)39701095a5dSDimitry Andric MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
39877fc4c14SDimitry Andric DebugLoc DL,
399b60736ecSDimitry Andric bool NoImplicit) {
400009b1c42SEd Schouten return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
40177fc4c14SDimitry Andric MachineInstr(*this, MCID, std::move(DL), NoImplicit);
402009b1c42SEd Schouten }
403009b1c42SEd Schouten
4043a0822f0SDimitry Andric /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
4053a0822f0SDimitry Andric /// identical in all ways except the instruction has no parent, prev, or next.
406009b1c42SEd Schouten MachineInstr *
CloneMachineInstr(const MachineInstr * Orig)407009b1c42SEd Schouten MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
408009b1c42SEd Schouten return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
409009b1c42SEd Schouten MachineInstr(*this, *Orig);
410009b1c42SEd Schouten }
411009b1c42SEd Schouten
cloneMachineInstrBundle(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const MachineInstr & Orig)41277fc4c14SDimitry Andric MachineInstr &MachineFunction::cloneMachineInstrBundle(
41377fc4c14SDimitry Andric MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
41477fc4c14SDimitry Andric const MachineInstr &Orig) {
415044eb2f6SDimitry Andric MachineInstr *FirstClone = nullptr;
416044eb2f6SDimitry Andric MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
417044eb2f6SDimitry Andric while (true) {
418044eb2f6SDimitry Andric MachineInstr *Cloned = CloneMachineInstr(&*I);
419044eb2f6SDimitry Andric MBB.insert(InsertBefore, Cloned);
420044eb2f6SDimitry Andric if (FirstClone == nullptr) {
421044eb2f6SDimitry Andric FirstClone = Cloned;
422044eb2f6SDimitry Andric } else {
423044eb2f6SDimitry Andric Cloned->bundleWithPred();
424044eb2f6SDimitry Andric }
425044eb2f6SDimitry Andric
426044eb2f6SDimitry Andric if (!I->isBundledWithSucc())
427044eb2f6SDimitry Andric break;
428044eb2f6SDimitry Andric ++I;
429044eb2f6SDimitry Andric }
430cfca06d7SDimitry Andric // Copy over call site info to the cloned instruction if needed. If Orig is in
431cfca06d7SDimitry Andric // a bundle, copyCallSiteInfo takes care of finding the call instruction in
432cfca06d7SDimitry Andric // the bundle.
433cfca06d7SDimitry Andric if (Orig.shouldUpdateCallSiteInfo())
434cfca06d7SDimitry Andric copyCallSiteInfo(&Orig, FirstClone);
435044eb2f6SDimitry Andric return *FirstClone;
436044eb2f6SDimitry Andric }
437044eb2f6SDimitry Andric
4383a0822f0SDimitry Andric /// Delete the given MachineInstr.
439009b1c42SEd Schouten ///
4404a16efa3SDimitry Andric /// This function also serves as the MachineInstr destructor - the real
4414a16efa3SDimitry Andric /// ~MachineInstr() destructor must be empty.
deleteMachineInstr(MachineInstr * MI)44277fc4c14SDimitry Andric void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
443e6d15924SDimitry Andric // Verify that a call site info is at valid state. This assertion should
444e6d15924SDimitry Andric // be triggered during the implementation of support for the
445e6d15924SDimitry Andric // call site info of a new architecture. If the assertion is triggered,
446e6d15924SDimitry Andric // back trace will tell where to insert a call to updateCallSiteInfo().
4477fa27ce4SDimitry Andric assert((!MI->isCandidateForCallSiteEntry() || !CallSitesInfo.contains(MI)) &&
448e6d15924SDimitry Andric "Call site info was not updated!");
4494a16efa3SDimitry Andric // Strip it for parts. The operand array and the MI object itself are
4504a16efa3SDimitry Andric // independently recyclable.
4514a16efa3SDimitry Andric if (MI->Operands)
4524a16efa3SDimitry Andric deallocateOperandArray(MI->CapOperands, MI->Operands);
4534a16efa3SDimitry Andric // Don't call ~MachineInstr() which must be trivial anyway because
4544a16efa3SDimitry Andric // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
4554a16efa3SDimitry Andric // destructors.
456009b1c42SEd Schouten InstructionRecycler.Deallocate(Allocator, MI);
457009b1c42SEd Schouten }
458009b1c42SEd Schouten
4593a0822f0SDimitry Andric /// Allocate a new MachineBasicBlock. Use this instead of
4603a0822f0SDimitry Andric /// `new MachineBasicBlock'.
461009b1c42SEd Schouten MachineBasicBlock *
CreateMachineBasicBlock(const BasicBlock * BB,std::optional<UniqueBBID> BBID)462b1c73532SDimitry Andric MachineFunction::CreateMachineBasicBlock(const BasicBlock *BB,
463b1c73532SDimitry Andric std::optional<UniqueBBID> BBID) {
464e3b55780SDimitry Andric MachineBasicBlock *MBB =
465e3b55780SDimitry Andric new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
466b1c73532SDimitry Andric MachineBasicBlock(*this, BB);
467e3b55780SDimitry Andric // Set BBID for `-basic-block=sections=labels` and
468e3b55780SDimitry Andric // `-basic-block-sections=list` to allow robust mapping of profiles to basic
469e3b55780SDimitry Andric // blocks.
470e3b55780SDimitry Andric if (Target.getBBSectionsType() == BasicBlockSection::Labels ||
471ac9a064cSDimitry Andric Target.Options.BBAddrMap ||
472e3b55780SDimitry Andric Target.getBBSectionsType() == BasicBlockSection::List)
473b1c73532SDimitry Andric MBB->setBBID(BBID.has_value() ? *BBID : UniqueBBID{NextBBID++, 0});
474e3b55780SDimitry Andric return MBB;
475009b1c42SEd Schouten }
476009b1c42SEd Schouten
4773a0822f0SDimitry Andric /// Delete the given MachineBasicBlock.
deleteMachineBasicBlock(MachineBasicBlock * MBB)47877fc4c14SDimitry Andric void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
479009b1c42SEd Schouten assert(MBB->getParent() == this && "MBB parent mismatch!");
480b60736ecSDimitry Andric // Clean up any references to MBB in jump tables before deleting it.
481b60736ecSDimitry Andric if (JumpTableInfo)
482b60736ecSDimitry Andric JumpTableInfo->RemoveMBBFromJumpTables(MBB);
483009b1c42SEd Schouten MBB->~MachineBasicBlock();
484009b1c42SEd Schouten BasicBlockRecycler.Deallocate(Allocator, MBB);
485009b1c42SEd Schouten }
486009b1c42SEd Schouten
getMachineMemOperand(MachinePointerInfo PtrInfo,MachineMemOperand::Flags F,LocationSize Size,Align BaseAlignment,const AAMDNodes & AAInfo,const MDNode * Ranges,SyncScope::ID SSID,AtomicOrdering Ordering,AtomicOrdering FailureOrdering)48701095a5dSDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
488ac9a064cSDimitry Andric MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LocationSize Size,
489ac9a064cSDimitry Andric Align BaseAlignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
490ca089b24SDimitry Andric SyncScope::ID SSID, AtomicOrdering Ordering,
491b915e9e0SDimitry Andric AtomicOrdering FailureOrdering) {
492ac9a064cSDimitry Andric assert((!Size.hasValue() ||
493ac9a064cSDimitry Andric Size.getValue().getKnownMinValue() != ~UINT64_C(0)) &&
494ac9a064cSDimitry Andric "Unexpected an unknown size to be represented using "
495ac9a064cSDimitry Andric "LocationSize::beforeOrAfter()");
49601095a5dSDimitry Andric return new (Allocator)
497ac9a064cSDimitry Andric MachineMemOperand(PtrInfo, F, Size, BaseAlignment, AAInfo, Ranges, SSID,
498ac9a064cSDimitry Andric Ordering, FailureOrdering);
499009b1c42SEd Schouten }
500009b1c42SEd Schouten
getMachineMemOperand(MachinePointerInfo PtrInfo,MachineMemOperand::Flags f,LLT MemTy,Align base_alignment,const AAMDNodes & AAInfo,const MDNode * Ranges,SyncScope::ID SSID,AtomicOrdering Ordering,AtomicOrdering FailureOrdering)501b60736ecSDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
502344a3780SDimitry Andric MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
503344a3780SDimitry Andric Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
504344a3780SDimitry Andric SyncScope::ID SSID, AtomicOrdering Ordering,
505344a3780SDimitry Andric AtomicOrdering FailureOrdering) {
506344a3780SDimitry Andric return new (Allocator)
507344a3780SDimitry Andric MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
508344a3780SDimitry Andric Ordering, FailureOrdering);
509344a3780SDimitry Andric }
510344a3780SDimitry Andric
511ac9a064cSDimitry Andric MachineMemOperand *
getMachineMemOperand(const MachineMemOperand * MMO,const MachinePointerInfo & PtrInfo,LocationSize Size)512ac9a064cSDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
513ac9a064cSDimitry Andric const MachinePointerInfo &PtrInfo,
514ac9a064cSDimitry Andric LocationSize Size) {
515ac9a064cSDimitry Andric assert((!Size.hasValue() ||
516ac9a064cSDimitry Andric Size.getValue().getKnownMinValue() != ~UINT64_C(0)) &&
517ac9a064cSDimitry Andric "Unexpected an unknown size to be represented using "
518ac9a064cSDimitry Andric "LocationSize::beforeOrAfter()");
519344a3780SDimitry Andric return new (Allocator)
520344a3780SDimitry Andric MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
521344a3780SDimitry Andric AAMDNodes(), nullptr, MMO->getSyncScopeID(),
522344a3780SDimitry Andric MMO->getSuccessOrdering(), MMO->getFailureOrdering());
523344a3780SDimitry Andric }
524344a3780SDimitry Andric
getMachineMemOperand(const MachineMemOperand * MMO,const MachinePointerInfo & PtrInfo,LLT Ty)525344a3780SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
526344a3780SDimitry Andric const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
527344a3780SDimitry Andric return new (Allocator)
528344a3780SDimitry Andric MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
529344a3780SDimitry Andric AAMDNodes(), nullptr, MMO->getSyncScopeID(),
530344a3780SDimitry Andric MMO->getSuccessOrdering(), MMO->getFailureOrdering());
531b60736ecSDimitry Andric }
532b60736ecSDimitry Andric
53359850d08SRoman Divacky MachineMemOperand *
getMachineMemOperand(const MachineMemOperand * MMO,int64_t Offset,LLT Ty)53459850d08SRoman Divacky MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
535344a3780SDimitry Andric int64_t Offset, LLT Ty) {
536e6d15924SDimitry Andric const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
537e6d15924SDimitry Andric
538e6d15924SDimitry Andric // If there is no pointer value, the offset isn't tracked so we need to adjust
539e6d15924SDimitry Andric // the base alignment.
540cfca06d7SDimitry Andric Align Alignment = PtrInfo.V.isNull()
541cfca06d7SDimitry Andric ? commonAlignment(MMO->getBaseAlign(), Offset)
542cfca06d7SDimitry Andric : MMO->getBaseAlign();
543e6d15924SDimitry Andric
544b60736ecSDimitry Andric // Do not preserve ranges, since we don't necessarily know what the high bits
545b60736ecSDimitry Andric // are anymore.
546344a3780SDimitry Andric return new (Allocator) MachineMemOperand(
547344a3780SDimitry Andric PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
548344a3780SDimitry Andric MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
549344a3780SDimitry Andric MMO->getSuccessOrdering(), MMO->getFailureOrdering());
55059850d08SRoman Divacky }
55159850d08SRoman Divacky
5524e20bb04SDimitry Andric MachineMemOperand *
getMachineMemOperand(const MachineMemOperand * MMO,const AAMDNodes & AAInfo)5534e20bb04SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
5544e20bb04SDimitry Andric const AAMDNodes &AAInfo) {
5554e20bb04SDimitry Andric MachinePointerInfo MPI = MMO->getValue() ?
5564e20bb04SDimitry Andric MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
5574e20bb04SDimitry Andric MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
5584e20bb04SDimitry Andric
559cfca06d7SDimitry Andric return new (Allocator) MachineMemOperand(
560cfca06d7SDimitry Andric MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
561344a3780SDimitry Andric MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
562cfca06d7SDimitry Andric MMO->getFailureOrdering());
5634e20bb04SDimitry Andric }
5644e20bb04SDimitry Andric
565e6d15924SDimitry Andric MachineMemOperand *
getMachineMemOperand(const MachineMemOperand * MMO,MachineMemOperand::Flags Flags)566e6d15924SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
567e6d15924SDimitry Andric MachineMemOperand::Flags Flags) {
568e6d15924SDimitry Andric return new (Allocator) MachineMemOperand(
569cfca06d7SDimitry Andric MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
570e6d15924SDimitry Andric MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
571344a3780SDimitry Andric MMO->getSuccessOrdering(), MMO->getFailureOrdering());
572e6d15924SDimitry Andric }
573e6d15924SDimitry Andric
createMIExtraInfo(ArrayRef<MachineMemOperand * > MMOs,MCSymbol * PreInstrSymbol,MCSymbol * PostInstrSymbol,MDNode * HeapAllocMarker,MDNode * PCSections,uint32_t CFIType,MDNode * MMRAs)574706b4fc4SDimitry Andric MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
575706b4fc4SDimitry Andric ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
576e3b55780SDimitry Andric MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections,
577ac9a064cSDimitry Andric uint32_t CFIType, MDNode *MMRAs) {
578d8e91e46SDimitry Andric return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
579e3b55780SDimitry Andric PostInstrSymbol, HeapAllocMarker,
580ac9a064cSDimitry Andric PCSections, CFIType, MMRAs);
58159850d08SRoman Divacky }
58259850d08SRoman Divacky
createExternalSymbolName(StringRef Name)583dd58ef01SDimitry Andric const char *MachineFunction::createExternalSymbolName(StringRef Name) {
584dd58ef01SDimitry Andric char *Dest = Allocator.Allocate<char>(Name.size() + 1);
585d8e91e46SDimitry Andric llvm::copy(Name, Dest);
586dd58ef01SDimitry Andric Dest[Name.size()] = 0;
587dd58ef01SDimitry Andric return Dest;
588dd58ef01SDimitry Andric }
589dd58ef01SDimitry Andric
allocateRegMask()590eb11fae6SDimitry Andric uint32_t *MachineFunction::allocateRegMask() {
591eb11fae6SDimitry Andric unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
592eb11fae6SDimitry Andric unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
593eb11fae6SDimitry Andric uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
594eb11fae6SDimitry Andric memset(Mask, 0, Size * sizeof(Mask[0]));
595eb11fae6SDimitry Andric return Mask;
596eb11fae6SDimitry Andric }
597eb11fae6SDimitry Andric
allocateShuffleMask(ArrayRef<int> Mask)598706b4fc4SDimitry Andric ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
599706b4fc4SDimitry Andric int* AllocMask = Allocator.Allocate<int>(Mask.size());
600706b4fc4SDimitry Andric copy(Mask, AllocMask);
601706b4fc4SDimitry Andric return {AllocMask, Mask.size()};
602706b4fc4SDimitry Andric }
603706b4fc4SDimitry Andric
604522600a2SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const60501095a5dSDimitry Andric LLVM_DUMP_METHOD void MachineFunction::dump() const {
606829000e0SRoman Divacky print(dbgs());
60759850d08SRoman Divacky }
608522600a2SDimitry Andric #endif
609522600a2SDimitry Andric
getName() const610522600a2SDimitry Andric StringRef MachineFunction::getName() const {
611044eb2f6SDimitry Andric return getFunction().getName();
612522600a2SDimitry Andric }
61359850d08SRoman Divacky
print(raw_ostream & OS,const SlotIndexes * Indexes) const61401095a5dSDimitry Andric void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
615522600a2SDimitry Andric OS << "# Machine code for function " << getName() << ": ";
61601095a5dSDimitry Andric getProperties().print(OS);
617b915e9e0SDimitry Andric OS << '\n';
618009b1c42SEd Schouten
619009b1c42SEd Schouten // Print Frame Information
620009b1c42SEd Schouten FrameInfo->print(*this, OS);
621009b1c42SEd Schouten
622009b1c42SEd Schouten // Print JumpTable Information
6236fe5c7aaSRoman Divacky if (JumpTableInfo)
624009b1c42SEd Schouten JumpTableInfo->print(OS);
625009b1c42SEd Schouten
626009b1c42SEd Schouten // Print Constant Pool
62759850d08SRoman Divacky ConstantPool->print(OS);
628009b1c42SEd Schouten
62967c32a98SDimitry Andric const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
630009b1c42SEd Schouten
631009b1c42SEd Schouten if (RegInfo && !RegInfo->livein_empty()) {
63236bf506aSRoman Divacky OS << "Function Live Ins: ";
633009b1c42SEd Schouten for (MachineRegisterInfo::livein_iterator
634009b1c42SEd Schouten I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
635044eb2f6SDimitry Andric OS << printReg(I->first, TRI);
636009b1c42SEd Schouten if (I->second)
637044eb2f6SDimitry Andric OS << " in " << printReg(I->second, TRI);
6385ca98fd9SDimitry Andric if (std::next(I) != E)
63936bf506aSRoman Divacky OS << ", ";
640009b1c42SEd Schouten }
64159850d08SRoman Divacky OS << '\n';
642009b1c42SEd Schouten }
643009b1c42SEd Schouten
644044eb2f6SDimitry Andric ModuleSlotTracker MST(getFunction().getParent());
645044eb2f6SDimitry Andric MST.incorporateFunction(getFunction());
6465ca98fd9SDimitry Andric for (const auto &BB : *this) {
64736bf506aSRoman Divacky OS << '\n';
648eb11fae6SDimitry Andric // If we print the whole function, print it at its most verbose level.
649eb11fae6SDimitry Andric BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
65036bf506aSRoman Divacky }
651009b1c42SEd Schouten
652522600a2SDimitry Andric OS << "\n# End machine code for function " << getName() << ".\n\n";
653009b1c42SEd Schouten }
654009b1c42SEd Schouten
655706b4fc4SDimitry Andric /// True if this function needs frame moves for debug or exceptions.
needsFrameMoves() const656706b4fc4SDimitry Andric bool MachineFunction::needsFrameMoves() const {
657706b4fc4SDimitry Andric return getMMI().hasDebugInfo() ||
658706b4fc4SDimitry Andric getTarget().Options.ForceDwarfFrameSection ||
659706b4fc4SDimitry Andric F.needsUnwindTableEntry();
660706b4fc4SDimitry Andric }
661706b4fc4SDimitry Andric
662009b1c42SEd Schouten namespace llvm {
663044eb2f6SDimitry Andric
664009b1c42SEd Schouten template<>
665009b1c42SEd Schouten struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits66606f9d401SRoman Divacky DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
66706f9d401SRoman Divacky
getGraphNamellvm::DOTGraphTraits668009b1c42SEd Schouten static std::string getGraphName(const MachineFunction *F) {
6695a5ac124SDimitry Andric return ("CFG for '" + F->getName() + "' function").str();
670009b1c42SEd Schouten }
671009b1c42SEd Schouten
getNodeLabelllvm::DOTGraphTraits67206f9d401SRoman Divacky std::string getNodeLabel(const MachineBasicBlock *Node,
67306f9d401SRoman Divacky const MachineFunction *Graph) {
67459850d08SRoman Divacky std::string OutStr;
67559850d08SRoman Divacky {
67659850d08SRoman Divacky raw_string_ostream OSS(OutStr);
67759850d08SRoman Divacky
678cf099d11SDimitry Andric if (isSimple()) {
679044eb2f6SDimitry Andric OSS << printMBBReference(*Node);
680cf099d11SDimitry Andric if (const BasicBlock *BB = Node->getBasicBlock())
681cf099d11SDimitry Andric OSS << ": " << BB->getName();
682cf099d11SDimitry Andric } else
68359850d08SRoman Divacky Node->print(OSS);
684009b1c42SEd Schouten }
685009b1c42SEd Schouten
686009b1c42SEd Schouten if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
687009b1c42SEd Schouten
688009b1c42SEd Schouten // Process string output to make it nicer...
689009b1c42SEd Schouten for (unsigned i = 0; i != OutStr.length(); ++i)
690009b1c42SEd Schouten if (OutStr[i] == '\n') { // Left justify
691009b1c42SEd Schouten OutStr[i] = '\\';
692009b1c42SEd Schouten OutStr.insert(OutStr.begin()+i+1, 'l');
693009b1c42SEd Schouten }
694009b1c42SEd Schouten return OutStr;
695009b1c42SEd Schouten }
696009b1c42SEd Schouten };
697044eb2f6SDimitry Andric
698044eb2f6SDimitry Andric } // end namespace llvm
699009b1c42SEd Schouten
viewCFG() const700009b1c42SEd Schouten void MachineFunction::viewCFG() const
701009b1c42SEd Schouten {
702009b1c42SEd Schouten #ifndef NDEBUG
703522600a2SDimitry Andric ViewGraph(this, "mf" + getName());
704009b1c42SEd Schouten #else
70566e41e3cSRoman Divacky errs() << "MachineFunction::viewCFG is only available in debug builds on "
706009b1c42SEd Schouten << "systems with Graphviz or gv!\n";
707009b1c42SEd Schouten #endif // NDEBUG
708009b1c42SEd Schouten }
709009b1c42SEd Schouten
viewCFGOnly() const710009b1c42SEd Schouten void MachineFunction::viewCFGOnly() const
711009b1c42SEd Schouten {
712f859468fSEd Schouten #ifndef NDEBUG
713522600a2SDimitry Andric ViewGraph(this, "mf" + getName(), true);
714f859468fSEd Schouten #else
71566e41e3cSRoman Divacky errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
716f859468fSEd Schouten << "systems with Graphviz or gv!\n";
717f859468fSEd Schouten #endif // NDEBUG
718009b1c42SEd Schouten }
719009b1c42SEd Schouten
7203a0822f0SDimitry Andric /// Add the specified physical register as a live-in value and
721009b1c42SEd Schouten /// create a corresponding virtual register for it.
addLiveIn(MCRegister PReg,const TargetRegisterClass * RC)722cfca06d7SDimitry Andric Register MachineFunction::addLiveIn(MCRegister PReg,
723d0e4e96dSDimitry Andric const TargetRegisterClass *RC) {
724abdf259dSRoman Divacky MachineRegisterInfo &MRI = getRegInfo();
725cfca06d7SDimitry Andric Register VReg = MRI.getLiveInVirtReg(PReg);
726abdf259dSRoman Divacky if (VReg) {
7275ca98fd9SDimitry Andric const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
7285ca98fd9SDimitry Andric (void)VRegRC;
7295ca98fd9SDimitry Andric // A physical register can be added several times.
7305ca98fd9SDimitry Andric // Between two calls, the register class of the related virtual register
7315ca98fd9SDimitry Andric // may have been constrained to match some operation constraints.
7325ca98fd9SDimitry Andric // In that case, check that the current register class includes the
7335ca98fd9SDimitry Andric // physical register and is a sub class of the specified RC.
7345ca98fd9SDimitry Andric assert((VRegRC == RC || (VRegRC->contains(PReg) &&
7355ca98fd9SDimitry Andric RC->hasSubClassEq(VRegRC))) &&
7365ca98fd9SDimitry Andric "Register class mismatch!");
737abdf259dSRoman Divacky return VReg;
738abdf259dSRoman Divacky }
739abdf259dSRoman Divacky VReg = MRI.createVirtualRegister(RC);
740abdf259dSRoman Divacky MRI.addLiveIn(PReg, VReg);
741009b1c42SEd Schouten return VReg;
742009b1c42SEd Schouten }
743009b1c42SEd Schouten
7443a0822f0SDimitry Andric /// Return the MCSymbol for the specified non-empty jump table.
7456fe5c7aaSRoman Divacky /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
7466fe5c7aaSRoman Divacky /// normal 'L' label is returned.
getJTISymbol(unsigned JTI,MCContext & Ctx,bool isLinkerPrivate) const7476fe5c7aaSRoman Divacky MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
7486fe5c7aaSRoman Divacky bool isLinkerPrivate) const {
749ee8648bdSDimitry Andric const DataLayout &DL = getDataLayout();
7506fe5c7aaSRoman Divacky assert(JumpTableInfo && "No jump tables");
7516fe5c7aaSRoman Divacky assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
7526fe5c7aaSRoman Divacky
753b915e9e0SDimitry Andric StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
754ee8648bdSDimitry Andric : DL.getPrivateGlobalPrefix();
7556fe5c7aaSRoman Divacky SmallString<60> Name;
7566fe5c7aaSRoman Divacky raw_svector_ostream(Name)
7576fe5c7aaSRoman Divacky << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
7585a5ac124SDimitry Andric return Ctx.getOrCreateSymbol(Name);
7596fe5c7aaSRoman Divacky }
7606fe5c7aaSRoman Divacky
7613a0822f0SDimitry Andric /// Return a function-local symbol to represent the PIC base.
getPICBaseSymbol() const762cf099d11SDimitry Andric MCSymbol *MachineFunction::getPICBaseSymbol() const {
763ee8648bdSDimitry Andric const DataLayout &DL = getDataLayout();
764ee8648bdSDimitry Andric return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
765cf099d11SDimitry Andric Twine(getFunctionNumber()) + "$pb");
766cf099d11SDimitry Andric }
7676fe5c7aaSRoman Divacky
768b915e9e0SDimitry Andric /// \name Exception Handling
769b915e9e0SDimitry Andric /// \{
770b915e9e0SDimitry Andric
771b915e9e0SDimitry Andric LandingPadInfo &
getOrCreateLandingPadInfo(MachineBasicBlock * LandingPad)772b915e9e0SDimitry Andric MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
773b915e9e0SDimitry Andric unsigned N = LandingPads.size();
774b915e9e0SDimitry Andric for (unsigned i = 0; i < N; ++i) {
775b915e9e0SDimitry Andric LandingPadInfo &LP = LandingPads[i];
776b915e9e0SDimitry Andric if (LP.LandingPadBlock == LandingPad)
777b915e9e0SDimitry Andric return LP;
778b915e9e0SDimitry Andric }
779b915e9e0SDimitry Andric
780b915e9e0SDimitry Andric LandingPads.push_back(LandingPadInfo(LandingPad));
781b915e9e0SDimitry Andric return LandingPads[N];
782b915e9e0SDimitry Andric }
783b915e9e0SDimitry Andric
addInvoke(MachineBasicBlock * LandingPad,MCSymbol * BeginLabel,MCSymbol * EndLabel)784b915e9e0SDimitry Andric void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
785b915e9e0SDimitry Andric MCSymbol *BeginLabel, MCSymbol *EndLabel) {
786b915e9e0SDimitry Andric LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
787b915e9e0SDimitry Andric LP.BeginLabels.push_back(BeginLabel);
788b915e9e0SDimitry Andric LP.EndLabels.push_back(EndLabel);
789b915e9e0SDimitry Andric }
790b915e9e0SDimitry Andric
addLandingPad(MachineBasicBlock * LandingPad)791b915e9e0SDimitry Andric MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
792b915e9e0SDimitry Andric MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
793b915e9e0SDimitry Andric LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
794b915e9e0SDimitry Andric LP.LandingPadLabel = LandingPadLabel;
795d8e91e46SDimitry Andric
796d8e91e46SDimitry Andric const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
797d8e91e46SDimitry Andric if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
798e3b55780SDimitry Andric // If there's no typeid list specified, then "cleanup" is implicit.
799e3b55780SDimitry Andric // Otherwise, id 0 is reserved for the cleanup action.
800e3b55780SDimitry Andric if (LPI->isCleanup() && LPI->getNumClauses() != 0)
801e3b55780SDimitry Andric LP.TypeIds.push_back(0);
802d8e91e46SDimitry Andric
803d8e91e46SDimitry Andric // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
804d8e91e46SDimitry Andric // correct, but we need to do it this way because of how the DWARF EH
805d8e91e46SDimitry Andric // emitter processes the clauses.
806d8e91e46SDimitry Andric for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
807d8e91e46SDimitry Andric Value *Val = LPI->getClause(I - 1);
808d8e91e46SDimitry Andric if (LPI->isCatch(I - 1)) {
809e3b55780SDimitry Andric LP.TypeIds.push_back(
810e3b55780SDimitry Andric getTypeIDFor(dyn_cast<GlobalValue>(Val->stripPointerCasts())));
811d8e91e46SDimitry Andric } else {
812d8e91e46SDimitry Andric // Add filters in a list.
813d8e91e46SDimitry Andric auto *CVal = cast<Constant>(Val);
814e3b55780SDimitry Andric SmallVector<unsigned, 4> FilterList;
815c0981da4SDimitry Andric for (const Use &U : CVal->operands())
816e3b55780SDimitry Andric FilterList.push_back(
817e3b55780SDimitry Andric getTypeIDFor(cast<GlobalValue>(U->stripPointerCasts())));
818d8e91e46SDimitry Andric
819e3b55780SDimitry Andric LP.TypeIds.push_back(getFilterIDFor(FilterList));
820d8e91e46SDimitry Andric }
821d8e91e46SDimitry Andric }
822d8e91e46SDimitry Andric
823d8e91e46SDimitry Andric } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
824e3b55780SDimitry Andric for (unsigned I = CPI->arg_size(); I != 0; --I) {
825e3b55780SDimitry Andric auto *TypeInfo =
826e3b55780SDimitry Andric dyn_cast<GlobalValue>(CPI->getArgOperand(I - 1)->stripPointerCasts());
827e3b55780SDimitry Andric LP.TypeIds.push_back(getTypeIDFor(TypeInfo));
828d8e91e46SDimitry Andric }
829d8e91e46SDimitry Andric
830d8e91e46SDimitry Andric } else {
831d8e91e46SDimitry Andric assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
832d8e91e46SDimitry Andric }
833d8e91e46SDimitry Andric
834b915e9e0SDimitry Andric return LandingPadLabel;
835b915e9e0SDimitry Andric }
836b915e9e0SDimitry Andric
setCallSiteLandingPad(MCSymbol * Sym,ArrayRef<unsigned> Sites)837b915e9e0SDimitry Andric void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
838b915e9e0SDimitry Andric ArrayRef<unsigned> Sites) {
839b915e9e0SDimitry Andric LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
840b915e9e0SDimitry Andric }
841b915e9e0SDimitry Andric
getTypeIDFor(const GlobalValue * TI)842b915e9e0SDimitry Andric unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
843b915e9e0SDimitry Andric for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
844b915e9e0SDimitry Andric if (TypeInfos[i] == TI) return i + 1;
845b915e9e0SDimitry Andric
846b915e9e0SDimitry Andric TypeInfos.push_back(TI);
847b915e9e0SDimitry Andric return TypeInfos.size();
848b915e9e0SDimitry Andric }
849b915e9e0SDimitry Andric
getFilterIDFor(ArrayRef<unsigned> TyIds)850e3b55780SDimitry Andric int MachineFunction::getFilterIDFor(ArrayRef<unsigned> TyIds) {
851b915e9e0SDimitry Andric // If the new filter coincides with the tail of an existing filter, then
852b915e9e0SDimitry Andric // re-use the existing filter. Folding filters more than this requires
853b915e9e0SDimitry Andric // re-ordering filters and/or their elements - probably not worth it.
854344a3780SDimitry Andric for (unsigned i : FilterEnds) {
855344a3780SDimitry Andric unsigned j = TyIds.size();
856b915e9e0SDimitry Andric
857b915e9e0SDimitry Andric while (i && j)
858b915e9e0SDimitry Andric if (FilterIds[--i] != TyIds[--j])
859b915e9e0SDimitry Andric goto try_next;
860b915e9e0SDimitry Andric
861b915e9e0SDimitry Andric if (!j)
862b915e9e0SDimitry Andric // The new filter coincides with range [i, end) of the existing filter.
863b915e9e0SDimitry Andric return -(1 + i);
864b915e9e0SDimitry Andric
865b915e9e0SDimitry Andric try_next:;
866b915e9e0SDimitry Andric }
867b915e9e0SDimitry Andric
868b915e9e0SDimitry Andric // Add the new filter.
869b915e9e0SDimitry Andric int FilterID = -(1 + FilterIds.size());
870b915e9e0SDimitry Andric FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
871b60736ecSDimitry Andric llvm::append_range(FilterIds, TyIds);
872b915e9e0SDimitry Andric FilterEnds.push_back(FilterIds.size());
873b915e9e0SDimitry Andric FilterIds.push_back(0); // terminator
874b915e9e0SDimitry Andric return FilterID;
875b915e9e0SDimitry Andric }
876b915e9e0SDimitry Andric
877706b4fc4SDimitry Andric MachineFunction::CallSiteInfoMap::iterator
getCallSiteInfo(const MachineInstr * MI)878706b4fc4SDimitry Andric MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
879cfca06d7SDimitry Andric assert(MI->isCandidateForCallSiteEntry() &&
880cfca06d7SDimitry Andric "Call site info refers only to call (MI) candidates");
881e6d15924SDimitry Andric
882cfca06d7SDimitry Andric if (!Target.Options.EmitCallSiteInfo)
883706b4fc4SDimitry Andric return CallSitesInfo.end();
884706b4fc4SDimitry Andric return CallSitesInfo.find(MI);
885e6d15924SDimitry Andric }
886e6d15924SDimitry Andric
887cfca06d7SDimitry Andric /// Return the call machine instruction or find a call within bundle.
getCallInstr(const MachineInstr * MI)888cfca06d7SDimitry Andric static const MachineInstr *getCallInstr(const MachineInstr *MI) {
889cfca06d7SDimitry Andric if (!MI->isBundle())
890cfca06d7SDimitry Andric return MI;
891e6d15924SDimitry Andric
8924b4fe385SDimitry Andric for (const auto &BMI : make_range(getBundleStart(MI->getIterator()),
893cfca06d7SDimitry Andric getBundleEnd(MI->getIterator())))
894cfca06d7SDimitry Andric if (BMI.isCandidateForCallSiteEntry())
895cfca06d7SDimitry Andric return &BMI;
8961d5ae102SDimitry Andric
897cfca06d7SDimitry Andric llvm_unreachable("Unexpected bundle without a call site candidate");
8981d5ae102SDimitry Andric }
8991d5ae102SDimitry Andric
eraseCallSiteInfo(const MachineInstr * MI)9001d5ae102SDimitry Andric void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
901cfca06d7SDimitry Andric assert(MI->shouldUpdateCallSiteInfo() &&
902cfca06d7SDimitry Andric "Call site info refers only to call (MI) candidates or "
903cfca06d7SDimitry Andric "candidates inside bundles");
904cfca06d7SDimitry Andric
905cfca06d7SDimitry Andric const MachineInstr *CallMI = getCallInstr(MI);
906cfca06d7SDimitry Andric CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
9071d5ae102SDimitry Andric if (CSIt == CallSitesInfo.end())
9081d5ae102SDimitry Andric return;
9091d5ae102SDimitry Andric CallSitesInfo.erase(CSIt);
9101d5ae102SDimitry Andric }
9111d5ae102SDimitry Andric
copyCallSiteInfo(const MachineInstr * Old,const MachineInstr * New)9121d5ae102SDimitry Andric void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
9131d5ae102SDimitry Andric const MachineInstr *New) {
914cfca06d7SDimitry Andric assert(Old->shouldUpdateCallSiteInfo() &&
915cfca06d7SDimitry Andric "Call site info refers only to call (MI) candidates or "
916cfca06d7SDimitry Andric "candidates inside bundles");
9171d5ae102SDimitry Andric
918cfca06d7SDimitry Andric if (!New->isCandidateForCallSiteEntry())
919cfca06d7SDimitry Andric return eraseCallSiteInfo(Old);
920cfca06d7SDimitry Andric
921cfca06d7SDimitry Andric const MachineInstr *OldCallMI = getCallInstr(Old);
922cfca06d7SDimitry Andric CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9231d5ae102SDimitry Andric if (CSIt == CallSitesInfo.end())
9241d5ae102SDimitry Andric return;
9251d5ae102SDimitry Andric
9261d5ae102SDimitry Andric CallSiteInfo CSInfo = CSIt->second;
927e6d15924SDimitry Andric CallSitesInfo[New] = CSInfo;
928e6d15924SDimitry Andric }
929e6d15924SDimitry Andric
moveCallSiteInfo(const MachineInstr * Old,const MachineInstr * New)930cfca06d7SDimitry Andric void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
931cfca06d7SDimitry Andric const MachineInstr *New) {
932cfca06d7SDimitry Andric assert(Old->shouldUpdateCallSiteInfo() &&
933cfca06d7SDimitry Andric "Call site info refers only to call (MI) candidates or "
934cfca06d7SDimitry Andric "candidates inside bundles");
935cfca06d7SDimitry Andric
936cfca06d7SDimitry Andric if (!New->isCandidateForCallSiteEntry())
937cfca06d7SDimitry Andric return eraseCallSiteInfo(Old);
938cfca06d7SDimitry Andric
939cfca06d7SDimitry Andric const MachineInstr *OldCallMI = getCallInstr(Old);
940cfca06d7SDimitry Andric CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
941cfca06d7SDimitry Andric if (CSIt == CallSitesInfo.end())
942cfca06d7SDimitry Andric return;
943cfca06d7SDimitry Andric
944cfca06d7SDimitry Andric CallSiteInfo CSInfo = std::move(CSIt->second);
945cfca06d7SDimitry Andric CallSitesInfo.erase(CSIt);
946cfca06d7SDimitry Andric CallSitesInfo[New] = CSInfo;
947cfca06d7SDimitry Andric }
948cfca06d7SDimitry Andric
setDebugInstrNumberingCount(unsigned Num)949b60736ecSDimitry Andric void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
950b60736ecSDimitry Andric DebugInstrNumberingCount = Num;
951b60736ecSDimitry Andric }
952b60736ecSDimitry Andric
makeDebugValueSubstitution(DebugInstrOperandPair A,DebugInstrOperandPair B,unsigned Subreg)953b60736ecSDimitry Andric void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
954344a3780SDimitry Andric DebugInstrOperandPair B,
955344a3780SDimitry Andric unsigned Subreg) {
956344a3780SDimitry Andric // Catch any accidental self-loops.
957344a3780SDimitry Andric assert(A.first != B.first);
958c0981da4SDimitry Andric // Don't allow any substitutions _from_ the memory operand number.
959c0981da4SDimitry Andric assert(A.second != DebugOperandMemNumber);
960c0981da4SDimitry Andric
961344a3780SDimitry Andric DebugValueSubstitutions.push_back({A, B, Subreg});
962b60736ecSDimitry Andric }
963b60736ecSDimitry Andric
substituteDebugValuesForInst(const MachineInstr & Old,MachineInstr & New,unsigned MaxOperand)964b60736ecSDimitry Andric void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
965b60736ecSDimitry Andric MachineInstr &New,
966b60736ecSDimitry Andric unsigned MaxOperand) {
967b60736ecSDimitry Andric // If the Old instruction wasn't tracked at all, there is no work to do.
968b60736ecSDimitry Andric unsigned OldInstrNum = Old.peekDebugInstrNum();
969b60736ecSDimitry Andric if (!OldInstrNum)
970b60736ecSDimitry Andric return;
971b60736ecSDimitry Andric
972b60736ecSDimitry Andric // Iterate over all operands looking for defs to create substitutions for.
973b60736ecSDimitry Andric // Avoid creating new instr numbers unless we create a new substitution.
974b60736ecSDimitry Andric // While this has no functional effect, it risks confusing someone reading
975b60736ecSDimitry Andric // MIR output.
976b60736ecSDimitry Andric // Examine all the operands, or the first N specified by the caller.
977b60736ecSDimitry Andric MaxOperand = std::min(MaxOperand, Old.getNumOperands());
978344a3780SDimitry Andric for (unsigned int I = 0; I < MaxOperand; ++I) {
979b60736ecSDimitry Andric const auto &OldMO = Old.getOperand(I);
980b60736ecSDimitry Andric auto &NewMO = New.getOperand(I);
981b60736ecSDimitry Andric (void)NewMO;
982b60736ecSDimitry Andric
983b60736ecSDimitry Andric if (!OldMO.isReg() || !OldMO.isDef())
984b60736ecSDimitry Andric continue;
985b60736ecSDimitry Andric assert(NewMO.isDef());
986b60736ecSDimitry Andric
987b60736ecSDimitry Andric unsigned NewInstrNum = New.getDebugInstrNum();
988b60736ecSDimitry Andric makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
989b60736ecSDimitry Andric std::make_pair(NewInstrNum, I));
990b60736ecSDimitry Andric }
991b60736ecSDimitry Andric }
992b60736ecSDimitry Andric
salvageCopySSA(MachineInstr & MI,DenseMap<Register,DebugInstrOperandPair> & DbgPHICache)993145449b1SDimitry Andric auto MachineFunction::salvageCopySSA(
994145449b1SDimitry Andric MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache)
995145449b1SDimitry Andric -> DebugInstrOperandPair {
996145449b1SDimitry Andric const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
997145449b1SDimitry Andric
998145449b1SDimitry Andric // Check whether this copy-like instruction has already been salvaged into
999145449b1SDimitry Andric // an operand pair.
1000145449b1SDimitry Andric Register Dest;
1001145449b1SDimitry Andric if (auto CopyDstSrc = TII.isCopyInstr(MI)) {
1002145449b1SDimitry Andric Dest = CopyDstSrc->Destination->getReg();
1003145449b1SDimitry Andric } else {
1004145449b1SDimitry Andric assert(MI.isSubregToReg());
1005145449b1SDimitry Andric Dest = MI.getOperand(0).getReg();
1006145449b1SDimitry Andric }
1007145449b1SDimitry Andric
1008145449b1SDimitry Andric auto CacheIt = DbgPHICache.find(Dest);
1009145449b1SDimitry Andric if (CacheIt != DbgPHICache.end())
1010145449b1SDimitry Andric return CacheIt->second;
1011145449b1SDimitry Andric
1012145449b1SDimitry Andric // Calculate the instruction number to use, or install a DBG_PHI.
1013145449b1SDimitry Andric auto OperandPair = salvageCopySSAImpl(MI);
1014145449b1SDimitry Andric DbgPHICache.insert({Dest, OperandPair});
1015145449b1SDimitry Andric return OperandPair;
1016145449b1SDimitry Andric }
1017145449b1SDimitry Andric
salvageCopySSAImpl(MachineInstr & MI)1018145449b1SDimitry Andric auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI)
1019344a3780SDimitry Andric -> DebugInstrOperandPair {
1020344a3780SDimitry Andric MachineRegisterInfo &MRI = getRegInfo();
1021344a3780SDimitry Andric const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1022344a3780SDimitry Andric const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1023344a3780SDimitry Andric
1024344a3780SDimitry Andric // Chase the value read by a copy-like instruction back to the instruction
1025344a3780SDimitry Andric // that ultimately _defines_ that value. This may pass:
1026344a3780SDimitry Andric // * Through multiple intermediate copies, including subregister moves /
1027344a3780SDimitry Andric // copies,
1028344a3780SDimitry Andric // * Copies from physical registers that must then be traced back to the
1029344a3780SDimitry Andric // defining instruction,
1030344a3780SDimitry Andric // * Or, physical registers may be live-in to (only) the entry block, which
1031344a3780SDimitry Andric // requires a DBG_PHI to be created.
1032344a3780SDimitry Andric // We can pursue this problem in that order: trace back through copies,
1033344a3780SDimitry Andric // optionally through a physical register, to a defining instruction. We
1034344a3780SDimitry Andric // should never move from physreg to vreg. As we're still in SSA form, no need
1035344a3780SDimitry Andric // to worry about partial definitions of registers.
1036344a3780SDimitry Andric
1037344a3780SDimitry Andric // Helper lambda to interpret a copy-like instruction. Takes instruction,
1038344a3780SDimitry Andric // returns the register read and any subregister identifying which part is
1039344a3780SDimitry Andric // read.
1040344a3780SDimitry Andric auto GetRegAndSubreg =
1041344a3780SDimitry Andric [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1042344a3780SDimitry Andric Register NewReg, OldReg;
1043344a3780SDimitry Andric unsigned SubReg;
1044344a3780SDimitry Andric if (Cpy.isCopy()) {
1045344a3780SDimitry Andric OldReg = Cpy.getOperand(0).getReg();
1046344a3780SDimitry Andric NewReg = Cpy.getOperand(1).getReg();
1047344a3780SDimitry Andric SubReg = Cpy.getOperand(1).getSubReg();
1048344a3780SDimitry Andric } else if (Cpy.isSubregToReg()) {
1049344a3780SDimitry Andric OldReg = Cpy.getOperand(0).getReg();
1050344a3780SDimitry Andric NewReg = Cpy.getOperand(2).getReg();
1051344a3780SDimitry Andric SubReg = Cpy.getOperand(3).getImm();
1052344a3780SDimitry Andric } else {
1053344a3780SDimitry Andric auto CopyDetails = *TII.isCopyInstr(Cpy);
1054344a3780SDimitry Andric const MachineOperand &Src = *CopyDetails.Source;
1055344a3780SDimitry Andric const MachineOperand &Dest = *CopyDetails.Destination;
1056344a3780SDimitry Andric OldReg = Dest.getReg();
1057344a3780SDimitry Andric NewReg = Src.getReg();
1058344a3780SDimitry Andric SubReg = Src.getSubReg();
1059344a3780SDimitry Andric }
1060344a3780SDimitry Andric
1061344a3780SDimitry Andric return {NewReg, SubReg};
1062344a3780SDimitry Andric };
1063344a3780SDimitry Andric
1064344a3780SDimitry Andric // First seek either the defining instruction, or a copy from a physreg.
1065344a3780SDimitry Andric // During search, the current state is the current copy instruction, and which
1066344a3780SDimitry Andric // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1067344a3780SDimitry Andric // deal with those later.
1068344a3780SDimitry Andric auto State = GetRegAndSubreg(MI);
1069344a3780SDimitry Andric auto CurInst = MI.getIterator();
1070344a3780SDimitry Andric SmallVector<unsigned, 4> SubregsSeen;
1071344a3780SDimitry Andric while (true) {
1072344a3780SDimitry Andric // If we've found a copy from a physreg, first portion of search is over.
1073344a3780SDimitry Andric if (!State.first.isVirtual())
1074344a3780SDimitry Andric break;
1075344a3780SDimitry Andric
1076344a3780SDimitry Andric // Record any subregister qualifier.
1077344a3780SDimitry Andric if (State.second)
1078344a3780SDimitry Andric SubregsSeen.push_back(State.second);
1079344a3780SDimitry Andric
1080344a3780SDimitry Andric assert(MRI.hasOneDef(State.first));
1081344a3780SDimitry Andric MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1082344a3780SDimitry Andric CurInst = Inst.getIterator();
1083344a3780SDimitry Andric
1084344a3780SDimitry Andric // Any non-copy instruction is the defining instruction we're seeking.
1085344a3780SDimitry Andric if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1086344a3780SDimitry Andric break;
1087344a3780SDimitry Andric State = GetRegAndSubreg(Inst);
1088344a3780SDimitry Andric };
1089344a3780SDimitry Andric
1090344a3780SDimitry Andric // Helper lambda to apply additional subregister substitutions to a known
1091344a3780SDimitry Andric // instruction/operand pair. Adds new (fake) substitutions so that we can
1092344a3780SDimitry Andric // record the subregister. FIXME: this isn't very space efficient if multiple
1093344a3780SDimitry Andric // values are tracked back through the same copies; cache something later.
1094344a3780SDimitry Andric auto ApplySubregisters =
1095344a3780SDimitry Andric [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1096344a3780SDimitry Andric for (unsigned Subreg : reverse(SubregsSeen)) {
1097344a3780SDimitry Andric // Fetch a new instruction number, not attached to an actual instruction.
1098344a3780SDimitry Andric unsigned NewInstrNumber = getNewDebugInstrNum();
1099344a3780SDimitry Andric // Add a substitution from the "new" number to the known one, with a
1100344a3780SDimitry Andric // qualifying subreg.
1101344a3780SDimitry Andric makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1102344a3780SDimitry Andric // Return the new number; to find the underlying value, consumers need to
1103344a3780SDimitry Andric // deal with the qualifying subreg.
1104344a3780SDimitry Andric P = {NewInstrNumber, 0};
1105344a3780SDimitry Andric }
1106344a3780SDimitry Andric return P;
1107344a3780SDimitry Andric };
1108344a3780SDimitry Andric
1109344a3780SDimitry Andric // If we managed to find the defining instruction after COPYs, return an
1110344a3780SDimitry Andric // instruction / operand pair after adding subregister qualifiers.
1111344a3780SDimitry Andric if (State.first.isVirtual()) {
1112344a3780SDimitry Andric // Virtual register def -- we can just look up where this happens.
1113344a3780SDimitry Andric MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
11147fa27ce4SDimitry Andric for (auto &MO : Inst->all_defs()) {
11157fa27ce4SDimitry Andric if (MO.getReg() != State.first)
1116344a3780SDimitry Andric continue;
11177fa27ce4SDimitry Andric return ApplySubregisters({Inst->getDebugInstrNum(), MO.getOperandNo()});
1118344a3780SDimitry Andric }
1119344a3780SDimitry Andric
1120344a3780SDimitry Andric llvm_unreachable("Vreg def with no corresponding operand?");
1121344a3780SDimitry Andric }
1122344a3780SDimitry Andric
1123344a3780SDimitry Andric // Our search ended in a copy from a physreg: walk back up the function
1124344a3780SDimitry Andric // looking for whatever defines the physreg.
1125344a3780SDimitry Andric assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1126344a3780SDimitry Andric State = GetRegAndSubreg(*CurInst);
1127344a3780SDimitry Andric Register RegToSeek = State.first;
1128344a3780SDimitry Andric
1129344a3780SDimitry Andric auto RMII = CurInst->getReverseIterator();
1130344a3780SDimitry Andric auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1131344a3780SDimitry Andric for (auto &ToExamine : PrevInstrs) {
11327fa27ce4SDimitry Andric for (auto &MO : ToExamine.all_defs()) {
1133344a3780SDimitry Andric // Test for operand that defines something aliasing RegToSeek.
11347fa27ce4SDimitry Andric if (!TRI.regsOverlap(RegToSeek, MO.getReg()))
1135344a3780SDimitry Andric continue;
1136344a3780SDimitry Andric
1137344a3780SDimitry Andric return ApplySubregisters(
11387fa27ce4SDimitry Andric {ToExamine.getDebugInstrNum(), MO.getOperandNo()});
1139344a3780SDimitry Andric }
1140344a3780SDimitry Andric }
1141344a3780SDimitry Andric
1142344a3780SDimitry Andric MachineBasicBlock &InsertBB = *CurInst->getParent();
1143344a3780SDimitry Andric
1144344a3780SDimitry Andric // We reached the start of the block before finding a defining instruction.
1145145449b1SDimitry Andric // There are numerous scenarios where this can happen:
1146145449b1SDimitry Andric // * Constant physical registers,
1147145449b1SDimitry Andric // * Several intrinsics that allow LLVM-IR to read arbitary registers,
1148145449b1SDimitry Andric // * Arguments in the entry block,
1149145449b1SDimitry Andric // * Exception handling landing pads.
1150145449b1SDimitry Andric // Validating all of them is too difficult, so just insert a DBG_PHI reading
1151145449b1SDimitry Andric // the variable value at this position, rather than checking it makes sense.
1152344a3780SDimitry Andric
1153344a3780SDimitry Andric // Create DBG_PHI for specified physreg.
1154344a3780SDimitry Andric auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1155344a3780SDimitry Andric TII.get(TargetOpcode::DBG_PHI));
1156c0981da4SDimitry Andric Builder.addReg(State.first);
1157344a3780SDimitry Andric unsigned NewNum = getNewDebugInstrNum();
1158344a3780SDimitry Andric Builder.addImm(NewNum);
1159344a3780SDimitry Andric return ApplySubregisters({NewNum, 0u});
1160344a3780SDimitry Andric }
1161344a3780SDimitry Andric
finalizeDebugInstrRefs()1162344a3780SDimitry Andric void MachineFunction::finalizeDebugInstrRefs() {
1163344a3780SDimitry Andric auto *TII = getSubtarget().getInstrInfo();
1164344a3780SDimitry Andric
1165f65dcba8SDimitry Andric auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1166e3b55780SDimitry Andric const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE_LIST);
1167344a3780SDimitry Andric MI.setDesc(RefII);
1168e3b55780SDimitry Andric MI.setDebugValueUndef();
1169344a3780SDimitry Andric };
1170344a3780SDimitry Andric
1171145449b1SDimitry Andric DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs;
1172344a3780SDimitry Andric for (auto &MBB : *this) {
1173344a3780SDimitry Andric for (auto &MI : MBB) {
1174e3b55780SDimitry Andric if (!MI.isDebugRef())
1175344a3780SDimitry Andric continue;
1176344a3780SDimitry Andric
1177e3b55780SDimitry Andric bool IsValidRef = true;
1178e3b55780SDimitry Andric
1179e3b55780SDimitry Andric for (MachineOperand &MO : MI.debug_operands()) {
1180e3b55780SDimitry Andric if (!MO.isReg())
1181e3b55780SDimitry Andric continue;
1182e3b55780SDimitry Andric
1183e3b55780SDimitry Andric Register Reg = MO.getReg();
1184344a3780SDimitry Andric
1185344a3780SDimitry Andric // Some vregs can be deleted as redundant in the meantime. Mark those
1186f65dcba8SDimitry Andric // as DBG_VALUE $noreg. Additionally, some normal instructions are
1187f65dcba8SDimitry Andric // quickly deleted, leaving dangling references to vregs with no def.
1188f65dcba8SDimitry Andric if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
1189e3b55780SDimitry Andric IsValidRef = false;
1190e3b55780SDimitry Andric break;
1191344a3780SDimitry Andric }
1192344a3780SDimitry Andric
1193344a3780SDimitry Andric assert(Reg.isVirtual());
1194344a3780SDimitry Andric MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1195344a3780SDimitry Andric
1196344a3780SDimitry Andric // If we've found a copy-like instruction, follow it back to the
1197344a3780SDimitry Andric // instruction that defines the source value, see salvageCopySSA docs
1198344a3780SDimitry Andric // for why this is important.
1199344a3780SDimitry Andric if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
1200145449b1SDimitry Andric auto Result = salvageCopySSA(DefMI, ArgDbgPHIs);
1201e3b55780SDimitry Andric MO.ChangeToDbgInstrRef(Result.first, Result.second);
1202344a3780SDimitry Andric } else {
1203344a3780SDimitry Andric // Otherwise, identify the operand number that the VReg refers to.
1204344a3780SDimitry Andric unsigned OperandIdx = 0;
1205e3b55780SDimitry Andric for (const auto &DefMO : DefMI.operands()) {
1206e3b55780SDimitry Andric if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg)
1207344a3780SDimitry Andric break;
1208344a3780SDimitry Andric ++OperandIdx;
1209344a3780SDimitry Andric }
1210344a3780SDimitry Andric assert(OperandIdx < DefMI.getNumOperands());
1211344a3780SDimitry Andric
1212344a3780SDimitry Andric // Morph this instr ref to point at the given instruction and operand.
1213344a3780SDimitry Andric unsigned ID = DefMI.getDebugInstrNum();
1214e3b55780SDimitry Andric MO.ChangeToDbgInstrRef(ID, OperandIdx);
1215344a3780SDimitry Andric }
1216344a3780SDimitry Andric }
1217e3b55780SDimitry Andric
1218e3b55780SDimitry Andric if (!IsValidRef)
1219e3b55780SDimitry Andric MakeUndefDbgValue(MI);
1220e3b55780SDimitry Andric }
1221344a3780SDimitry Andric }
1222344a3780SDimitry Andric }
1223344a3780SDimitry Andric
shouldUseDebugInstrRef() const1224e3b55780SDimitry Andric bool MachineFunction::shouldUseDebugInstrRef() const {
1225c0981da4SDimitry Andric // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1226c0981da4SDimitry Andric // have optimized code inlined into this unoptimized code, however with
1227c0981da4SDimitry Andric // fewer and less aggressive optimizations happening, coverage and accuracy
1228c0981da4SDimitry Andric // should not suffer.
1229b1c73532SDimitry Andric if (getTarget().getOptLevel() == CodeGenOptLevel::None)
1230c0981da4SDimitry Andric return false;
1231c0981da4SDimitry Andric
1232c0981da4SDimitry Andric // Don't use instr-ref if this function is marked optnone.
1233c0981da4SDimitry Andric if (F.hasFnAttribute(Attribute::OptimizeNone))
1234c0981da4SDimitry Andric return false;
1235c0981da4SDimitry Andric
12366f8fc217SDimitry Andric if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
1237c0981da4SDimitry Andric return true;
1238c0981da4SDimitry Andric
1239c0981da4SDimitry Andric return false;
1240c0981da4SDimitry Andric }
1241c0981da4SDimitry Andric
useDebugInstrRef() const1242e3b55780SDimitry Andric bool MachineFunction::useDebugInstrRef() const {
1243e3b55780SDimitry Andric return UseDebugInstrRef;
1244e3b55780SDimitry Andric }
1245e3b55780SDimitry Andric
setUseDebugInstrRef(bool Use)1246e3b55780SDimitry Andric void MachineFunction::setUseDebugInstrRef(bool Use) {
1247e3b55780SDimitry Andric UseDebugInstrRef = Use;
1248e3b55780SDimitry Andric }
1249e3b55780SDimitry Andric
1250c0981da4SDimitry Andric // Use one million as a high / reserved number.
1251c0981da4SDimitry Andric const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1252c0981da4SDimitry Andric
1253b915e9e0SDimitry Andric /// \}
1254b915e9e0SDimitry Andric
1255009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1256009b1c42SEd Schouten // MachineJumpTableInfo implementation
1257009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1258009b1c42SEd Schouten
12593a0822f0SDimitry Andric /// Return the size of each entry in the jump table.
getEntrySize(const DataLayout & TD) const1260522600a2SDimitry Andric unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
12616fe5c7aaSRoman Divacky // The size of a jump table entry is 4 bytes unless the entry is just the
12626fe5c7aaSRoman Divacky // address of a block, in which case it is the pointer size.
12636fe5c7aaSRoman Divacky switch (getEntryKind()) {
12646fe5c7aaSRoman Divacky case MachineJumpTableInfo::EK_BlockAddress:
12656fe5c7aaSRoman Divacky return TD.getPointerSize();
126663faed5bSDimitry Andric case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1267b1c73532SDimitry Andric case MachineJumpTableInfo::EK_LabelDifference64:
126863faed5bSDimitry Andric return 8;
12696fe5c7aaSRoman Divacky case MachineJumpTableInfo::EK_GPRel32BlockAddress:
12706fe5c7aaSRoman Divacky case MachineJumpTableInfo::EK_LabelDifference32:
12716fe5c7aaSRoman Divacky case MachineJumpTableInfo::EK_Custom32:
12726fe5c7aaSRoman Divacky return 4;
1273c6910277SRoman Divacky case MachineJumpTableInfo::EK_Inline:
1274c6910277SRoman Divacky return 0;
12756fe5c7aaSRoman Divacky }
127663faed5bSDimitry Andric llvm_unreachable("Unknown jump table encoding!");
12776fe5c7aaSRoman Divacky }
12786fe5c7aaSRoman Divacky
12793a0822f0SDimitry Andric /// Return the alignment of each entry in the jump table.
getEntryAlignment(const DataLayout & TD) const1280522600a2SDimitry Andric unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
12816fe5c7aaSRoman Divacky // The alignment of a jump table entry is the alignment of int32 unless the
12826fe5c7aaSRoman Divacky // entry is just the address of a block, in which case it is the pointer
12836fe5c7aaSRoman Divacky // alignment.
12846fe5c7aaSRoman Divacky switch (getEntryKind()) {
12856fe5c7aaSRoman Divacky case MachineJumpTableInfo::EK_BlockAddress:
12861d5ae102SDimitry Andric return TD.getPointerABIAlignment(0).value();
128763faed5bSDimitry Andric case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1288b1c73532SDimitry Andric case MachineJumpTableInfo::EK_LabelDifference64:
12891d5ae102SDimitry Andric return TD.getABIIntegerTypeAlignment(64).value();
12906fe5c7aaSRoman Divacky case MachineJumpTableInfo::EK_GPRel32BlockAddress:
12916fe5c7aaSRoman Divacky case MachineJumpTableInfo::EK_LabelDifference32:
12926fe5c7aaSRoman Divacky case MachineJumpTableInfo::EK_Custom32:
12931d5ae102SDimitry Andric return TD.getABIIntegerTypeAlignment(32).value();
1294c6910277SRoman Divacky case MachineJumpTableInfo::EK_Inline:
1295c6910277SRoman Divacky return 1;
12966fe5c7aaSRoman Divacky }
129763faed5bSDimitry Andric llvm_unreachable("Unknown jump table encoding!");
12986fe5c7aaSRoman Divacky }
12996fe5c7aaSRoman Divacky
13003a0822f0SDimitry Andric /// Create a new jump table entry in the jump table info.
createJumpTableIndex(const std::vector<MachineBasicBlock * > & DestBBs)13012f12f10aSRoman Divacky unsigned MachineJumpTableInfo::createJumpTableIndex(
1302009b1c42SEd Schouten const std::vector<MachineBasicBlock*> &DestBBs) {
1303009b1c42SEd Schouten assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1304009b1c42SEd Schouten JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1305009b1c42SEd Schouten return JumpTables.size()-1;
1306009b1c42SEd Schouten }
1307009b1c42SEd Schouten
13083a0822f0SDimitry Andric /// If Old is the target of any jump tables, update the jump tables to branch
13093a0822f0SDimitry Andric /// to New instead.
ReplaceMBBInJumpTables(MachineBasicBlock * Old,MachineBasicBlock * New)13106fe5c7aaSRoman Divacky bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1311009b1c42SEd Schouten MachineBasicBlock *New) {
1312009b1c42SEd Schouten assert(Old != New && "Not making a change?");
1313009b1c42SEd Schouten bool MadeChange = false;
1314907da171SRoman Divacky for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1315907da171SRoman Divacky ReplaceMBBInJumpTable(i, Old, New);
1316907da171SRoman Divacky return MadeChange;
1317907da171SRoman Divacky }
1318907da171SRoman Divacky
1319b60736ecSDimitry Andric /// If MBB is present in any jump tables, remove it.
RemoveMBBFromJumpTables(MachineBasicBlock * MBB)1320b60736ecSDimitry Andric bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1321b60736ecSDimitry Andric bool MadeChange = false;
1322b60736ecSDimitry Andric for (MachineJumpTableEntry &JTE : JumpTables) {
1323b60736ecSDimitry Andric auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1324b60736ecSDimitry Andric MadeChange |= (removeBeginItr != JTE.MBBs.end());
1325b60736ecSDimitry Andric JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1326b60736ecSDimitry Andric }
1327b60736ecSDimitry Andric return MadeChange;
1328b60736ecSDimitry Andric }
1329b60736ecSDimitry Andric
13303a0822f0SDimitry Andric /// If Old is a target of the jump tables, update the jump table to branch to
13313a0822f0SDimitry Andric /// New instead.
ReplaceMBBInJumpTable(unsigned Idx,MachineBasicBlock * Old,MachineBasicBlock * New)13326fe5c7aaSRoman Divacky bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1333907da171SRoman Divacky MachineBasicBlock *Old,
1334907da171SRoman Divacky MachineBasicBlock *New) {
1335907da171SRoman Divacky assert(Old != New && "Not making a change?");
1336907da171SRoman Divacky bool MadeChange = false;
1337907da171SRoman Divacky MachineJumpTableEntry &JTE = JumpTables[Idx];
1338f65dcba8SDimitry Andric for (MachineBasicBlock *&MBB : JTE.MBBs)
1339f65dcba8SDimitry Andric if (MBB == Old) {
1340f65dcba8SDimitry Andric MBB = New;
1341009b1c42SEd Schouten MadeChange = true;
1342009b1c42SEd Schouten }
1343009b1c42SEd Schouten return MadeChange;
1344009b1c42SEd Schouten }
1345009b1c42SEd Schouten
print(raw_ostream & OS) const134659850d08SRoman Divacky void MachineJumpTableInfo::print(raw_ostream &OS) const {
134736bf506aSRoman Divacky if (JumpTables.empty()) return;
134836bf506aSRoman Divacky
134936bf506aSRoman Divacky OS << "Jump Tables:\n";
135036bf506aSRoman Divacky
1351009b1c42SEd Schouten for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1352e6d15924SDimitry Andric OS << printJumpTableEntryReference(i) << ':';
1353f65dcba8SDimitry Andric for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
1354f65dcba8SDimitry Andric OS << ' ' << printMBBReference(*MBB);
1355e6d15924SDimitry Andric if (i != e)
1356e6d15924SDimitry Andric OS << '\n';
1357009b1c42SEd Schouten }
135836bf506aSRoman Divacky
135936bf506aSRoman Divacky OS << '\n';
1360009b1c42SEd Schouten }
1361009b1c42SEd Schouten
1362522600a2SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const136301095a5dSDimitry Andric LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1364522600a2SDimitry Andric #endif
1365009b1c42SEd Schouten
printJumpTableEntryReference(unsigned Idx)1366044eb2f6SDimitry Andric Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1367044eb2f6SDimitry Andric return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1368044eb2f6SDimitry Andric }
1369009b1c42SEd Schouten
1370009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1371009b1c42SEd Schouten // MachineConstantPool implementation
1372009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1373009b1c42SEd Schouten
anchor()137463faed5bSDimitry Andric void MachineConstantPoolValue::anchor() {}
137563faed5bSDimitry Andric
getSizeInBytes(const DataLayout & DL) const1376b60736ecSDimitry Andric unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1377b60736ecSDimitry Andric return DL.getTypeAllocSize(Ty);
1378b60736ecSDimitry Andric }
1379b60736ecSDimitry Andric
getSizeInBytes(const DataLayout & DL) const1380b60736ecSDimitry Andric unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
1381009b1c42SEd Schouten if (isMachineConstantPoolEntry())
1382b60736ecSDimitry Andric return Val.MachineCPVal->getSizeInBytes(DL);
1383b60736ecSDimitry Andric return DL.getTypeAllocSize(Val.ConstVal->getType());
1384009b1c42SEd Schouten }
1385009b1c42SEd Schouten
needsRelocation() const1386dd58ef01SDimitry Andric bool MachineConstantPoolEntry::needsRelocation() const {
138759850d08SRoman Divacky if (isMachineConstantPoolEntry())
1388dd58ef01SDimitry Andric return true;
1389344a3780SDimitry Andric return Val.ConstVal->needsDynamicRelocation();
139059850d08SRoman Divacky }
139159850d08SRoman Divacky
13925ca98fd9SDimitry Andric SectionKind
getSectionKind(const DataLayout * DL) const13935ca98fd9SDimitry Andric MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1394dd58ef01SDimitry Andric if (needsRelocation())
1395dd58ef01SDimitry Andric return SectionKind::getReadOnlyWithRel();
1396b60736ecSDimitry Andric switch (getSizeInBytes(*DL)) {
13975ca98fd9SDimitry Andric case 4:
1398dd58ef01SDimitry Andric return SectionKind::getMergeableConst4();
13995ca98fd9SDimitry Andric case 8:
1400dd58ef01SDimitry Andric return SectionKind::getMergeableConst8();
14015ca98fd9SDimitry Andric case 16:
1402dd58ef01SDimitry Andric return SectionKind::getMergeableConst16();
140301095a5dSDimitry Andric case 32:
140401095a5dSDimitry Andric return SectionKind::getMergeableConst32();
14055ca98fd9SDimitry Andric default:
1406dd58ef01SDimitry Andric return SectionKind::getReadOnly();
14075ca98fd9SDimitry Andric }
14085ca98fd9SDimitry Andric }
14095ca98fd9SDimitry Andric
~MachineConstantPool()1410009b1c42SEd Schouten MachineConstantPool::~MachineConstantPool() {
1411b915e9e0SDimitry Andric // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1412b915e9e0SDimitry Andric // so keep track of which we've deleted to avoid double deletions.
1413b915e9e0SDimitry Andric DenseSet<MachineConstantPoolValue*> Deleted;
141477fc4c14SDimitry Andric for (const MachineConstantPoolEntry &C : Constants)
141577fc4c14SDimitry Andric if (C.isMachineConstantPoolEntry()) {
141677fc4c14SDimitry Andric Deleted.insert(C.Val.MachineCPVal);
141777fc4c14SDimitry Andric delete C.Val.MachineCPVal;
1418b915e9e0SDimitry Andric }
1419344a3780SDimitry Andric for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1420344a3780SDimitry Andric if (Deleted.count(CPV) == 0)
1421344a3780SDimitry Andric delete CPV;
1422009b1c42SEd Schouten }
1423b915e9e0SDimitry Andric }
1424009b1c42SEd Schouten
14253a0822f0SDimitry Andric /// Test whether the given two constants can be allocated the same constant pool
14267fa27ce4SDimitry Andric /// entry referenced by \param A.
CanShareConstantPoolEntry(const Constant * A,const Constant * B,const DataLayout & DL)1427d7f7719eSRoman Divacky static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1428ee8648bdSDimitry Andric const DataLayout &DL) {
142936bf506aSRoman Divacky // Handle the trivial case quickly.
143036bf506aSRoman Divacky if (A == B) return true;
143136bf506aSRoman Divacky
143236bf506aSRoman Divacky // If they have the same type but weren't the same constant, quickly
143336bf506aSRoman Divacky // reject them.
143436bf506aSRoman Divacky if (A->getType() == B->getType()) return false;
143536bf506aSRoman Divacky
143663faed5bSDimitry Andric // We can't handle structs or arrays.
143763faed5bSDimitry Andric if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
143863faed5bSDimitry Andric isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
143963faed5bSDimitry Andric return false;
144063faed5bSDimitry Andric
144136bf506aSRoman Divacky // For now, only support constants with the same size.
1442ee8648bdSDimitry Andric uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1443ee8648bdSDimitry Andric if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
144436bf506aSRoman Divacky return false;
144536bf506aSRoman Divacky
14467fa27ce4SDimitry Andric bool ContainsUndefOrPoisonA = A->containsUndefOrPoisonElement();
14477fa27ce4SDimitry Andric
144863faed5bSDimitry Andric Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
144936bf506aSRoman Divacky
145063faed5bSDimitry Andric // Try constant folding a bitcast of both instructions to an integer. If we
145163faed5bSDimitry Andric // get two identical ConstantInt's, then we are good to share them. We use
145263faed5bSDimitry Andric // the constant folding APIs to do this so that we get the benefit of
1453522600a2SDimitry Andric // DataLayout.
145463faed5bSDimitry Andric if (isa<PointerType>(A->getType()))
145501095a5dSDimitry Andric A = ConstantFoldCastOperand(Instruction::PtrToInt,
145601095a5dSDimitry Andric const_cast<Constant *>(A), IntTy, DL);
145763faed5bSDimitry Andric else if (A->getType() != IntTy)
145801095a5dSDimitry Andric A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
145901095a5dSDimitry Andric IntTy, DL);
146063faed5bSDimitry Andric if (isa<PointerType>(B->getType()))
146101095a5dSDimitry Andric B = ConstantFoldCastOperand(Instruction::PtrToInt,
146201095a5dSDimitry Andric const_cast<Constant *>(B), IntTy, DL);
146363faed5bSDimitry Andric else if (B->getType() != IntTy)
146401095a5dSDimitry Andric B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
146501095a5dSDimitry Andric IntTy, DL);
146636bf506aSRoman Divacky
14677fa27ce4SDimitry Andric if (A != B)
14687fa27ce4SDimitry Andric return false;
14697fa27ce4SDimitry Andric
14707fa27ce4SDimitry Andric // Constants only safely match if A doesn't contain undef/poison.
14717fa27ce4SDimitry Andric // As we'll be reusing A, it doesn't matter if B contain undef/poison.
14727fa27ce4SDimitry Andric // TODO: Handle cases where A and B have the same undef/poison elements.
14737fa27ce4SDimitry Andric // TODO: Merge A and B with mismatching undef/poison elements.
14747fa27ce4SDimitry Andric return !ContainsUndefOrPoisonA;
147536bf506aSRoman Divacky }
147636bf506aSRoman Divacky
14773a0822f0SDimitry Andric /// Create a new entry in the constant pool or return an existing one.
14783a0822f0SDimitry Andric /// User must specify the log2 of the minimum required alignment for the object.
getConstantPoolIndex(const Constant * C,Align Alignment)1479d7f7719eSRoman Divacky unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1480cfca06d7SDimitry Andric Align Alignment) {
1481009b1c42SEd Schouten if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1482009b1c42SEd Schouten
1483009b1c42SEd Schouten // Check to see if we already have this constant.
1484009b1c42SEd Schouten //
1485009b1c42SEd Schouten // FIXME, this could be made much more efficient for large constant pools.
1486009b1c42SEd Schouten for (unsigned i = 0, e = Constants.size(); i != e; ++i)
148736bf506aSRoman Divacky if (!Constants[i].isMachineConstantPoolEntry() &&
1488ee8648bdSDimitry Andric CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1489cfca06d7SDimitry Andric if (Constants[i].getAlign() < Alignment)
149036bf506aSRoman Divacky Constants[i].Alignment = Alignment;
1491009b1c42SEd Schouten return i;
149236bf506aSRoman Divacky }
1493009b1c42SEd Schouten
1494009b1c42SEd Schouten Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1495009b1c42SEd Schouten return Constants.size()-1;
1496009b1c42SEd Schouten }
1497009b1c42SEd Schouten
getConstantPoolIndex(MachineConstantPoolValue * V,Align Alignment)1498009b1c42SEd Schouten unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1499cfca06d7SDimitry Andric Align Alignment) {
1500009b1c42SEd Schouten if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1501009b1c42SEd Schouten
1502009b1c42SEd Schouten // Check to see if we already have this constant.
1503009b1c42SEd Schouten //
1504009b1c42SEd Schouten // FIXME, this could be made much more efficient for large constant pools.
1505009b1c42SEd Schouten int Idx = V->getExistingMachineCPValue(this, Alignment);
1506d0e4e96dSDimitry Andric if (Idx != -1) {
1507d0e4e96dSDimitry Andric MachineCPVsSharingEntries.insert(V);
1508009b1c42SEd Schouten return (unsigned)Idx;
1509d0e4e96dSDimitry Andric }
1510009b1c42SEd Schouten
1511009b1c42SEd Schouten Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1512009b1c42SEd Schouten return Constants.size()-1;
1513009b1c42SEd Schouten }
1514009b1c42SEd Schouten
print(raw_ostream & OS) const1515009b1c42SEd Schouten void MachineConstantPool::print(raw_ostream &OS) const {
151636bf506aSRoman Divacky if (Constants.empty()) return;
151736bf506aSRoman Divacky
151836bf506aSRoman Divacky OS << "Constant Pool:\n";
1519009b1c42SEd Schouten for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
152036bf506aSRoman Divacky OS << " cp#" << i << ": ";
1521009b1c42SEd Schouten if (Constants[i].isMachineConstantPoolEntry())
1522009b1c42SEd Schouten Constants[i].Val.MachineCPVal->print(OS);
1523009b1c42SEd Schouten else
15245ca98fd9SDimitry Andric Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1525cfca06d7SDimitry Andric OS << ", align=" << Constants[i].getAlign().value();
1526009b1c42SEd Schouten OS << "\n";
1527009b1c42SEd Schouten }
1528009b1c42SEd Schouten }
1529009b1c42SEd Schouten
15307fa27ce4SDimitry Andric //===----------------------------------------------------------------------===//
15317fa27ce4SDimitry Andric // Template specialization for MachineFunction implementation of
15327fa27ce4SDimitry Andric // ProfileSummaryInfo::getEntryCount().
15337fa27ce4SDimitry Andric //===----------------------------------------------------------------------===//
15347fa27ce4SDimitry Andric template <>
15357fa27ce4SDimitry Andric std::optional<Function::ProfileCount>
getEntryCount(const llvm::MachineFunction * F) const15367fa27ce4SDimitry Andric ProfileSummaryInfo::getEntryCount<llvm::MachineFunction>(
15377fa27ce4SDimitry Andric const llvm::MachineFunction *F) const {
15387fa27ce4SDimitry Andric return F->getFunction().getEntryCount();
15397fa27ce4SDimitry Andric }
15407fa27ce4SDimitry Andric
1541522600a2SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const154201095a5dSDimitry Andric LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1543522600a2SDimitry Andric #endif
1544