10b57cec5SDimitry Andric //===- MachineFunction.cpp ------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // Collect native machine code information for a function. This allows
100b57cec5SDimitry Andric // target-specific information about the generated code to be stored with each
110b57cec5SDimitry Andric // function.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric
150b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
160b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
190b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
200b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
220b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
230b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
240b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
25fe013be4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
280b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
290b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
300b57cec5SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
310b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
320b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
330b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
340b57cec5SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
35*c9157d92SDimitry Andric #include "llvm/CodeGen/PseudoSourceValueManager.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
375ffd83dbSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
430b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
440b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
450b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
460b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
470b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
480b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
49fe013be4SDimitry Andric #include "llvm/IR/EHPersonalities.h"
500b57cec5SDimitry Andric #include "llvm/IR/Function.h"
510b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
520b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
530b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
540b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
550b57cec5SDimitry Andric #include "llvm/IR/Module.h"
560b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
570b57cec5SDimitry Andric #include "llvm/IR/Value.h"
580b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
590b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
600b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
610b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
620b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
630b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
640b57cec5SDimitry Andric #include "llvm/Support/DOTGraphTraits.h"
650b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
660b57cec5SDimitry Andric #include "llvm/Support/GraphWriter.h"
670b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
680b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
690b57cec5SDimitry Andric #include <algorithm>
700b57cec5SDimitry Andric #include <cassert>
710b57cec5SDimitry Andric #include <cstddef>
720b57cec5SDimitry Andric #include <cstdint>
730b57cec5SDimitry Andric #include <iterator>
740b57cec5SDimitry Andric #include <string>
755ffd83dbSDimitry Andric #include <type_traits>
760b57cec5SDimitry Andric #include <utility>
770b57cec5SDimitry Andric #include <vector>
780b57cec5SDimitry Andric
7904eeddc0SDimitry Andric #include "LiveDebugValues/LiveDebugValues.h"
8004eeddc0SDimitry Andric
810b57cec5SDimitry Andric using namespace llvm;
820b57cec5SDimitry Andric
830b57cec5SDimitry Andric #define DEBUG_TYPE "codegen"
840b57cec5SDimitry Andric
858bcb0991SDimitry Andric static cl::opt<unsigned> AlignAllFunctions(
868bcb0991SDimitry Andric "align-all-functions",
878bcb0991SDimitry Andric cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
888bcb0991SDimitry Andric "means align on 16B boundaries)."),
890b57cec5SDimitry Andric cl::init(0), cl::Hidden);
900b57cec5SDimitry Andric
getPropertyName(MachineFunctionProperties::Property Prop)910b57cec5SDimitry Andric static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
920b57cec5SDimitry Andric using P = MachineFunctionProperties::Property;
930b57cec5SDimitry Andric
940eae32dcSDimitry Andric // clang-format off
950b57cec5SDimitry Andric switch(Prop) {
960b57cec5SDimitry Andric case P::FailedISel: return "FailedISel";
970b57cec5SDimitry Andric case P::IsSSA: return "IsSSA";
980b57cec5SDimitry Andric case P::Legalized: return "Legalized";
990b57cec5SDimitry Andric case P::NoPHIs: return "NoPHIs";
1000b57cec5SDimitry Andric case P::NoVRegs: return "NoVRegs";
1010b57cec5SDimitry Andric case P::RegBankSelected: return "RegBankSelected";
1020b57cec5SDimitry Andric case P::Selected: return "Selected";
1030b57cec5SDimitry Andric case P::TracksLiveness: return "TracksLiveness";
1045ffd83dbSDimitry Andric case P::TiedOpsRewritten: return "TiedOpsRewritten";
105349cc55cSDimitry Andric case P::FailsVerification: return "FailsVerification";
1060eae32dcSDimitry Andric case P::TracksDebugUserValues: return "TracksDebugUserValues";
1070b57cec5SDimitry Andric }
1080eae32dcSDimitry Andric // clang-format on
1090b57cec5SDimitry Andric llvm_unreachable("Invalid machine function property");
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric
setUnsafeStackSize(const Function & F,MachineFrameInfo & FrameInfo)11281ad6265SDimitry Andric void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo) {
11381ad6265SDimitry Andric if (!F.hasFnAttribute(Attribute::SafeStack))
11481ad6265SDimitry Andric return;
11581ad6265SDimitry Andric
11681ad6265SDimitry Andric auto *Existing =
11781ad6265SDimitry Andric dyn_cast_or_null<MDTuple>(F.getMetadata(LLVMContext::MD_annotation));
11881ad6265SDimitry Andric
11981ad6265SDimitry Andric if (!Existing || Existing->getNumOperands() != 2)
12081ad6265SDimitry Andric return;
12181ad6265SDimitry Andric
12281ad6265SDimitry Andric auto *MetadataName = "unsafe-stack-size";
12381ad6265SDimitry Andric if (auto &N = Existing->getOperand(0)) {
124fe013be4SDimitry Andric if (N.equalsStr(MetadataName)) {
12581ad6265SDimitry Andric if (auto &Op = Existing->getOperand(1)) {
12681ad6265SDimitry Andric auto Val = mdconst::extract<ConstantInt>(Op)->getZExtValue();
12781ad6265SDimitry Andric FrameInfo.setUnsafeStackSize(Val);
12881ad6265SDimitry Andric }
12981ad6265SDimitry Andric }
13081ad6265SDimitry Andric }
13181ad6265SDimitry Andric }
13281ad6265SDimitry Andric
1330b57cec5SDimitry Andric // Pin the vtable to this file.
anchor()1340b57cec5SDimitry Andric void MachineFunction::Delegate::anchor() {}
1350b57cec5SDimitry Andric
print(raw_ostream & OS) const1360b57cec5SDimitry Andric void MachineFunctionProperties::print(raw_ostream &OS) const {
1370b57cec5SDimitry Andric const char *Separator = "";
1380b57cec5SDimitry Andric for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
1390b57cec5SDimitry Andric if (!Properties[I])
1400b57cec5SDimitry Andric continue;
1410b57cec5SDimitry Andric OS << Separator << getPropertyName(static_cast<Property>(I));
1420b57cec5SDimitry Andric Separator = ", ";
1430b57cec5SDimitry Andric }
1440b57cec5SDimitry Andric }
1450b57cec5SDimitry Andric
1460b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1470b57cec5SDimitry Andric // MachineFunction implementation
1480b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1490b57cec5SDimitry Andric
1500b57cec5SDimitry Andric // Out-of-line virtual method.
1510b57cec5SDimitry Andric MachineFunctionInfo::~MachineFunctionInfo() = default;
1520b57cec5SDimitry Andric
deleteNode(MachineBasicBlock * MBB)1530b57cec5SDimitry Andric void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
1540eae32dcSDimitry Andric MBB->getParent()->deleteMachineBasicBlock(MBB);
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric
getFnStackAlignment(const TargetSubtargetInfo * STI,const Function & F)15781ad6265SDimitry Andric static inline Align getFnStackAlignment(const TargetSubtargetInfo *STI,
1580b57cec5SDimitry Andric const Function &F) {
159349cc55cSDimitry Andric if (auto MA = F.getFnStackAlign())
16081ad6265SDimitry Andric return *MA;
16181ad6265SDimitry Andric return STI->getFrameLowering()->getStackAlign();
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric
MachineFunction(Function & F,const LLVMTargetMachine & Target,const TargetSubtargetInfo & STI,unsigned FunctionNum,MachineModuleInfo & mmi)1645ffd83dbSDimitry Andric MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
1650b57cec5SDimitry Andric const TargetSubtargetInfo &STI,
1660b57cec5SDimitry Andric unsigned FunctionNum, MachineModuleInfo &mmi)
1670b57cec5SDimitry Andric : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
1680b57cec5SDimitry Andric FunctionNumber = FunctionNum;
1690b57cec5SDimitry Andric init();
1700b57cec5SDimitry Andric }
1710b57cec5SDimitry Andric
handleInsertion(MachineInstr & MI)1720b57cec5SDimitry Andric void MachineFunction::handleInsertion(MachineInstr &MI) {
1730b57cec5SDimitry Andric if (TheDelegate)
1740b57cec5SDimitry Andric TheDelegate->MF_HandleInsertion(MI);
1750b57cec5SDimitry Andric }
1760b57cec5SDimitry Andric
handleRemoval(MachineInstr & MI)1770b57cec5SDimitry Andric void MachineFunction::handleRemoval(MachineInstr &MI) {
1780b57cec5SDimitry Andric if (TheDelegate)
1790b57cec5SDimitry Andric TheDelegate->MF_HandleRemoval(MI);
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric
handleChangeDesc(MachineInstr & MI,const MCInstrDesc & TID)182*c9157d92SDimitry Andric void MachineFunction::handleChangeDesc(MachineInstr &MI,
183*c9157d92SDimitry Andric const MCInstrDesc &TID) {
184*c9157d92SDimitry Andric if (TheDelegate)
185*c9157d92SDimitry Andric TheDelegate->MF_HandleChangeDesc(MI, TID);
186*c9157d92SDimitry Andric }
187*c9157d92SDimitry Andric
init()1880b57cec5SDimitry Andric void MachineFunction::init() {
1890b57cec5SDimitry Andric // Assume the function starts in SSA form with correct liveness.
1900b57cec5SDimitry Andric Properties.set(MachineFunctionProperties::Property::IsSSA);
1910b57cec5SDimitry Andric Properties.set(MachineFunctionProperties::Property::TracksLiveness);
1920b57cec5SDimitry Andric if (STI->getRegisterInfo())
1930b57cec5SDimitry Andric RegInfo = new (Allocator) MachineRegisterInfo(this);
1940b57cec5SDimitry Andric else
1950b57cec5SDimitry Andric RegInfo = nullptr;
1960b57cec5SDimitry Andric
1970b57cec5SDimitry Andric MFInfo = nullptr;
198bdd1243dSDimitry Andric
1990b57cec5SDimitry Andric // We can realign the stack if the target supports it and the user hasn't
2000b57cec5SDimitry Andric // explicitly asked us not to.
2010b57cec5SDimitry Andric bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
2020b57cec5SDimitry Andric !F.hasFnAttribute("no-realign-stack");
2030b57cec5SDimitry Andric FrameInfo = new (Allocator) MachineFrameInfo(
2040b57cec5SDimitry Andric getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
2050b57cec5SDimitry Andric /*ForcedRealign=*/CanRealignSP &&
2060b57cec5SDimitry Andric F.hasFnAttribute(Attribute::StackAlignment));
2070b57cec5SDimitry Andric
20881ad6265SDimitry Andric setUnsafeStackSize(F, *FrameInfo);
20981ad6265SDimitry Andric
2100b57cec5SDimitry Andric if (F.hasFnAttribute(Attribute::StackAlignment))
2115ffd83dbSDimitry Andric FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
2120b57cec5SDimitry Andric
2130b57cec5SDimitry Andric ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
2140b57cec5SDimitry Andric Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
2150b57cec5SDimitry Andric
2160b57cec5SDimitry Andric // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
2170b57cec5SDimitry Andric // FIXME: Use Function::hasOptSize().
2180b57cec5SDimitry Andric if (!F.hasFnAttribute(Attribute::OptimizeForSize))
2190b57cec5SDimitry Andric Alignment = std::max(Alignment,
2200b57cec5SDimitry Andric STI->getTargetLowering()->getPrefFunctionAlignment());
2210b57cec5SDimitry Andric
222fe013be4SDimitry Andric // -fsanitize=function and -fsanitize=kcfi instrument indirect function calls
223fe013be4SDimitry Andric // to load a type hash before the function label. Ensure functions are aligned
224fe013be4SDimitry Andric // by a least 4 to avoid unaligned access, which is especially important for
225fe013be4SDimitry Andric // -mno-unaligned-access.
226fe013be4SDimitry Andric if (F.hasMetadata(LLVMContext::MD_func_sanitize) ||
227fe013be4SDimitry Andric F.getMetadata(LLVMContext::MD_kcfi_type))
228fe013be4SDimitry Andric Alignment = std::max(Alignment, Align(4));
229fe013be4SDimitry Andric
2300b57cec5SDimitry Andric if (AlignAllFunctions)
2318bcb0991SDimitry Andric Alignment = Align(1ULL << AlignAllFunctions);
2320b57cec5SDimitry Andric
2330b57cec5SDimitry Andric JumpTableInfo = nullptr;
2340b57cec5SDimitry Andric
2350b57cec5SDimitry Andric if (isFuncletEHPersonality(classifyEHPersonality(
2360b57cec5SDimitry Andric F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
2370b57cec5SDimitry Andric WinEHInfo = new (Allocator) WinEHFuncInfo();
2380b57cec5SDimitry Andric }
2390b57cec5SDimitry Andric
2400b57cec5SDimitry Andric if (isScopedEHPersonality(classifyEHPersonality(
2410b57cec5SDimitry Andric F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
2420b57cec5SDimitry Andric WasmEHInfo = new (Allocator) WasmEHFuncInfo();
2430b57cec5SDimitry Andric }
2440b57cec5SDimitry Andric
2450b57cec5SDimitry Andric assert(Target.isCompatibleDataLayout(getDataLayout()) &&
2460b57cec5SDimitry Andric "Can't create a MachineFunction using a Module with a "
2470b57cec5SDimitry Andric "Target-incompatible DataLayout attached\n");
2480b57cec5SDimitry Andric
24981ad6265SDimitry Andric PSVManager = std::make_unique<PseudoSourceValueManager>(getTarget());
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric
initTargetMachineFunctionInfo(const TargetSubtargetInfo & STI)252bdd1243dSDimitry Andric void MachineFunction::initTargetMachineFunctionInfo(
253bdd1243dSDimitry Andric const TargetSubtargetInfo &STI) {
254bdd1243dSDimitry Andric assert(!MFInfo && "MachineFunctionInfo already set");
255bdd1243dSDimitry Andric MFInfo = Target.createMachineFunctionInfo(Allocator, F, &STI);
256bdd1243dSDimitry Andric }
257bdd1243dSDimitry Andric
~MachineFunction()2580b57cec5SDimitry Andric MachineFunction::~MachineFunction() {
2590b57cec5SDimitry Andric clear();
2600b57cec5SDimitry Andric }
2610b57cec5SDimitry Andric
clear()2620b57cec5SDimitry Andric void MachineFunction::clear() {
2630b57cec5SDimitry Andric Properties.reset();
2640b57cec5SDimitry Andric // Don't call destructors on MachineInstr and MachineOperand. All of their
2650b57cec5SDimitry Andric // memory comes from the BumpPtrAllocator which is about to be purged.
2660b57cec5SDimitry Andric //
2670b57cec5SDimitry Andric // Do call MachineBasicBlock destructors, it contains std::vectors.
2680b57cec5SDimitry Andric for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
2690b57cec5SDimitry Andric I->Insts.clearAndLeakNodesUnsafely();
2700b57cec5SDimitry Andric MBBNumbering.clear();
2710b57cec5SDimitry Andric
2720b57cec5SDimitry Andric InstructionRecycler.clear(Allocator);
2730b57cec5SDimitry Andric OperandRecycler.clear(Allocator);
2740b57cec5SDimitry Andric BasicBlockRecycler.clear(Allocator);
2750b57cec5SDimitry Andric CodeViewAnnotations.clear();
2760b57cec5SDimitry Andric VariableDbgInfos.clear();
2770b57cec5SDimitry Andric if (RegInfo) {
2780b57cec5SDimitry Andric RegInfo->~MachineRegisterInfo();
2790b57cec5SDimitry Andric Allocator.Deallocate(RegInfo);
2800b57cec5SDimitry Andric }
2810b57cec5SDimitry Andric if (MFInfo) {
2820b57cec5SDimitry Andric MFInfo->~MachineFunctionInfo();
2830b57cec5SDimitry Andric Allocator.Deallocate(MFInfo);
2840b57cec5SDimitry Andric }
2850b57cec5SDimitry Andric
2860b57cec5SDimitry Andric FrameInfo->~MachineFrameInfo();
2870b57cec5SDimitry Andric Allocator.Deallocate(FrameInfo);
2880b57cec5SDimitry Andric
2890b57cec5SDimitry Andric ConstantPool->~MachineConstantPool();
2900b57cec5SDimitry Andric Allocator.Deallocate(ConstantPool);
2910b57cec5SDimitry Andric
2920b57cec5SDimitry Andric if (JumpTableInfo) {
2930b57cec5SDimitry Andric JumpTableInfo->~MachineJumpTableInfo();
2940b57cec5SDimitry Andric Allocator.Deallocate(JumpTableInfo);
2950b57cec5SDimitry Andric }
2960b57cec5SDimitry Andric
2970b57cec5SDimitry Andric if (WinEHInfo) {
2980b57cec5SDimitry Andric WinEHInfo->~WinEHFuncInfo();
2990b57cec5SDimitry Andric Allocator.Deallocate(WinEHInfo);
3000b57cec5SDimitry Andric }
3010b57cec5SDimitry Andric
3020b57cec5SDimitry Andric if (WasmEHInfo) {
3030b57cec5SDimitry Andric WasmEHInfo->~WasmEHFuncInfo();
3040b57cec5SDimitry Andric Allocator.Deallocate(WasmEHInfo);
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric }
3070b57cec5SDimitry Andric
getDataLayout() const3080b57cec5SDimitry Andric const DataLayout &MachineFunction::getDataLayout() const {
3090b57cec5SDimitry Andric return F.getParent()->getDataLayout();
3100b57cec5SDimitry Andric }
3110b57cec5SDimitry Andric
3120b57cec5SDimitry Andric /// Get the JumpTableInfo for this function.
3130b57cec5SDimitry Andric /// If it does not already exist, allocate one.
3140b57cec5SDimitry Andric MachineJumpTableInfo *MachineFunction::
getOrCreateJumpTableInfo(unsigned EntryKind)3150b57cec5SDimitry Andric getOrCreateJumpTableInfo(unsigned EntryKind) {
3160b57cec5SDimitry Andric if (JumpTableInfo) return JumpTableInfo;
3170b57cec5SDimitry Andric
3180b57cec5SDimitry Andric JumpTableInfo = new (Allocator)
3190b57cec5SDimitry Andric MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
3200b57cec5SDimitry Andric return JumpTableInfo;
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric
getDenormalMode(const fltSemantics & FPType) const323480093f4SDimitry Andric DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
324e8d8bef9SDimitry Andric return F.getDenormalMode(FPType);
325480093f4SDimitry Andric }
326480093f4SDimitry Andric
3270b57cec5SDimitry Andric /// Should we be emitting segmented stack stuff for the function
shouldSplitStack() const3280b57cec5SDimitry Andric bool MachineFunction::shouldSplitStack() const {
3290b57cec5SDimitry Andric return getFunction().hasFnAttribute("split-stack");
3300b57cec5SDimitry Andric }
3310b57cec5SDimitry Andric
332bdd1243dSDimitry Andric [[nodiscard]] unsigned
addFrameInst(const MCCFIInstruction & Inst)3330b57cec5SDimitry Andric MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
3340b57cec5SDimitry Andric FrameInstructions.push_back(Inst);
3350b57cec5SDimitry Andric return FrameInstructions.size() - 1;
3360b57cec5SDimitry Andric }
3370b57cec5SDimitry Andric
3380b57cec5SDimitry Andric /// This discards all of the MachineBasicBlock numbers and recomputes them.
3390b57cec5SDimitry Andric /// This guarantees that the MBB numbers are sequential, dense, and match the
3400b57cec5SDimitry Andric /// ordering of the blocks within the function. If a specific MachineBasicBlock
3410b57cec5SDimitry Andric /// is specified, only that block and those after it are renumbered.
RenumberBlocks(MachineBasicBlock * MBB)3420b57cec5SDimitry Andric void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
3430b57cec5SDimitry Andric if (empty()) { MBBNumbering.clear(); return; }
3440b57cec5SDimitry Andric MachineFunction::iterator MBBI, E = end();
3450b57cec5SDimitry Andric if (MBB == nullptr)
3460b57cec5SDimitry Andric MBBI = begin();
3470b57cec5SDimitry Andric else
3480b57cec5SDimitry Andric MBBI = MBB->getIterator();
3490b57cec5SDimitry Andric
3500b57cec5SDimitry Andric // Figure out the block number this should have.
3510b57cec5SDimitry Andric unsigned BlockNo = 0;
3520b57cec5SDimitry Andric if (MBBI != begin())
3530b57cec5SDimitry Andric BlockNo = std::prev(MBBI)->getNumber() + 1;
3540b57cec5SDimitry Andric
3550b57cec5SDimitry Andric for (; MBBI != E; ++MBBI, ++BlockNo) {
3560b57cec5SDimitry Andric if (MBBI->getNumber() != (int)BlockNo) {
3570b57cec5SDimitry Andric // Remove use of the old number.
3580b57cec5SDimitry Andric if (MBBI->getNumber() != -1) {
3590b57cec5SDimitry Andric assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
3600b57cec5SDimitry Andric "MBB number mismatch!");
3610b57cec5SDimitry Andric MBBNumbering[MBBI->getNumber()] = nullptr;
3620b57cec5SDimitry Andric }
3630b57cec5SDimitry Andric
3640b57cec5SDimitry Andric // If BlockNo is already taken, set that block's number to -1.
3650b57cec5SDimitry Andric if (MBBNumbering[BlockNo])
3660b57cec5SDimitry Andric MBBNumbering[BlockNo]->setNumber(-1);
3670b57cec5SDimitry Andric
3680b57cec5SDimitry Andric MBBNumbering[BlockNo] = &*MBBI;
3690b57cec5SDimitry Andric MBBI->setNumber(BlockNo);
3700b57cec5SDimitry Andric }
3710b57cec5SDimitry Andric }
3720b57cec5SDimitry Andric
3730b57cec5SDimitry Andric // Okay, all the blocks are renumbered. If we have compactified the block
3740b57cec5SDimitry Andric // numbering, shrink MBBNumbering now.
3750b57cec5SDimitry Andric assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
3760b57cec5SDimitry Andric MBBNumbering.resize(BlockNo);
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric
3795ffd83dbSDimitry Andric /// This method iterates over the basic blocks and assigns their IsBeginSection
3805ffd83dbSDimitry Andric /// and IsEndSection fields. This must be called after MBB layout is finalized
3815ffd83dbSDimitry Andric /// and the SectionID's are assigned to MBBs.
assignBeginEndSections()3825ffd83dbSDimitry Andric void MachineFunction::assignBeginEndSections() {
3835ffd83dbSDimitry Andric front().setIsBeginSection();
3845ffd83dbSDimitry Andric auto CurrentSectionID = front().getSectionID();
3855ffd83dbSDimitry Andric for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
3865ffd83dbSDimitry Andric if (MBBI->getSectionID() == CurrentSectionID)
3875ffd83dbSDimitry Andric continue;
3885ffd83dbSDimitry Andric MBBI->setIsBeginSection();
3895ffd83dbSDimitry Andric std::prev(MBBI)->setIsEndSection();
3905ffd83dbSDimitry Andric CurrentSectionID = MBBI->getSectionID();
3915ffd83dbSDimitry Andric }
3925ffd83dbSDimitry Andric back().setIsEndSection();
3935ffd83dbSDimitry Andric }
3945ffd83dbSDimitry Andric
3950b57cec5SDimitry Andric /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
CreateMachineInstr(const MCInstrDesc & MCID,DebugLoc DL,bool NoImplicit)3960b57cec5SDimitry Andric MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
3970eae32dcSDimitry Andric DebugLoc DL,
398e8d8bef9SDimitry Andric bool NoImplicit) {
3990b57cec5SDimitry Andric return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
4000eae32dcSDimitry Andric MachineInstr(*this, MCID, std::move(DL), NoImplicit);
4010b57cec5SDimitry Andric }
4020b57cec5SDimitry Andric
4030b57cec5SDimitry Andric /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
4040b57cec5SDimitry Andric /// identical in all ways except the instruction has no parent, prev, or next.
4050b57cec5SDimitry Andric MachineInstr *
CloneMachineInstr(const MachineInstr * Orig)4060b57cec5SDimitry Andric MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
4070b57cec5SDimitry Andric return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
4080b57cec5SDimitry Andric MachineInstr(*this, *Orig);
4090b57cec5SDimitry Andric }
4100b57cec5SDimitry Andric
cloneMachineInstrBundle(MachineBasicBlock & MBB,MachineBasicBlock::iterator InsertBefore,const MachineInstr & Orig)4110eae32dcSDimitry Andric MachineInstr &MachineFunction::cloneMachineInstrBundle(
4120eae32dcSDimitry Andric MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
4130eae32dcSDimitry Andric const MachineInstr &Orig) {
4140b57cec5SDimitry Andric MachineInstr *FirstClone = nullptr;
4150b57cec5SDimitry Andric MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
4160b57cec5SDimitry Andric while (true) {
4170b57cec5SDimitry Andric MachineInstr *Cloned = CloneMachineInstr(&*I);
4180b57cec5SDimitry Andric MBB.insert(InsertBefore, Cloned);
4190b57cec5SDimitry Andric if (FirstClone == nullptr) {
4200b57cec5SDimitry Andric FirstClone = Cloned;
4210b57cec5SDimitry Andric } else {
4220b57cec5SDimitry Andric Cloned->bundleWithPred();
4230b57cec5SDimitry Andric }
4240b57cec5SDimitry Andric
4250b57cec5SDimitry Andric if (!I->isBundledWithSucc())
4260b57cec5SDimitry Andric break;
4270b57cec5SDimitry Andric ++I;
4280b57cec5SDimitry Andric }
4295ffd83dbSDimitry Andric // Copy over call site info to the cloned instruction if needed. If Orig is in
4305ffd83dbSDimitry Andric // a bundle, copyCallSiteInfo takes care of finding the call instruction in
4315ffd83dbSDimitry Andric // the bundle.
4325ffd83dbSDimitry Andric if (Orig.shouldUpdateCallSiteInfo())
4335ffd83dbSDimitry Andric copyCallSiteInfo(&Orig, FirstClone);
4340b57cec5SDimitry Andric return *FirstClone;
4350b57cec5SDimitry Andric }
4360b57cec5SDimitry Andric
4370b57cec5SDimitry Andric /// Delete the given MachineInstr.
4380b57cec5SDimitry Andric ///
4390b57cec5SDimitry Andric /// This function also serves as the MachineInstr destructor - the real
4400b57cec5SDimitry Andric /// ~MachineInstr() destructor must be empty.
deleteMachineInstr(MachineInstr * MI)4410eae32dcSDimitry Andric void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
4420b57cec5SDimitry Andric // Verify that a call site info is at valid state. This assertion should
4430b57cec5SDimitry Andric // be triggered during the implementation of support for the
4440b57cec5SDimitry Andric // call site info of a new architecture. If the assertion is triggered,
4450b57cec5SDimitry Andric // back trace will tell where to insert a call to updateCallSiteInfo().
446fe013be4SDimitry Andric assert((!MI->isCandidateForCallSiteEntry() || !CallSitesInfo.contains(MI)) &&
4470b57cec5SDimitry Andric "Call site info was not updated!");
4480b57cec5SDimitry Andric // Strip it for parts. The operand array and the MI object itself are
4490b57cec5SDimitry Andric // independently recyclable.
4500b57cec5SDimitry Andric if (MI->Operands)
4510b57cec5SDimitry Andric deallocateOperandArray(MI->CapOperands, MI->Operands);
4520b57cec5SDimitry Andric // Don't call ~MachineInstr() which must be trivial anyway because
4530b57cec5SDimitry Andric // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
4540b57cec5SDimitry Andric // destructors.
4550b57cec5SDimitry Andric InstructionRecycler.Deallocate(Allocator, MI);
4560b57cec5SDimitry Andric }
4570b57cec5SDimitry Andric
4580b57cec5SDimitry Andric /// Allocate a new MachineBasicBlock. Use this instead of
4590b57cec5SDimitry Andric /// `new MachineBasicBlock'.
4600b57cec5SDimitry Andric MachineBasicBlock *
CreateMachineBasicBlock(const BasicBlock * BB,std::optional<UniqueBBID> BBID)461*c9157d92SDimitry Andric MachineFunction::CreateMachineBasicBlock(const BasicBlock *BB,
462*c9157d92SDimitry Andric std::optional<UniqueBBID> BBID) {
463bdd1243dSDimitry Andric MachineBasicBlock *MBB =
464bdd1243dSDimitry Andric new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
465*c9157d92SDimitry Andric MachineBasicBlock(*this, BB);
466bdd1243dSDimitry Andric // Set BBID for `-basic-block=sections=labels` and
467bdd1243dSDimitry Andric // `-basic-block-sections=list` to allow robust mapping of profiles to basic
468bdd1243dSDimitry Andric // blocks.
469bdd1243dSDimitry Andric if (Target.getBBSectionsType() == BasicBlockSection::Labels ||
470bdd1243dSDimitry Andric Target.getBBSectionsType() == BasicBlockSection::List)
471*c9157d92SDimitry Andric MBB->setBBID(BBID.has_value() ? *BBID : UniqueBBID{NextBBID++, 0});
472bdd1243dSDimitry Andric return MBB;
4730b57cec5SDimitry Andric }
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric /// Delete the given MachineBasicBlock.
deleteMachineBasicBlock(MachineBasicBlock * MBB)4760eae32dcSDimitry Andric void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
4770b57cec5SDimitry Andric assert(MBB->getParent() == this && "MBB parent mismatch!");
478e8d8bef9SDimitry Andric // Clean up any references to MBB in jump tables before deleting it.
479e8d8bef9SDimitry Andric if (JumpTableInfo)
480e8d8bef9SDimitry Andric JumpTableInfo->RemoveMBBFromJumpTables(MBB);
4810b57cec5SDimitry Andric MBB->~MachineBasicBlock();
4820b57cec5SDimitry Andric BasicBlockRecycler.Deallocate(Allocator, MBB);
4830b57cec5SDimitry Andric }
4840b57cec5SDimitry Andric
getMachineMemOperand(MachinePointerInfo PtrInfo,MachineMemOperand::Flags f,uint64_t s,Align base_alignment,const AAMDNodes & AAInfo,const MDNode * Ranges,SyncScope::ID SSID,AtomicOrdering Ordering,AtomicOrdering FailureOrdering)4850b57cec5SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
4860b57cec5SDimitry Andric MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
4875ffd83dbSDimitry Andric Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
4880b57cec5SDimitry Andric SyncScope::ID SSID, AtomicOrdering Ordering,
4890b57cec5SDimitry Andric AtomicOrdering FailureOrdering) {
4900b57cec5SDimitry Andric return new (Allocator)
4910b57cec5SDimitry Andric MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
4920b57cec5SDimitry Andric SSID, Ordering, FailureOrdering);
4930b57cec5SDimitry Andric }
4940b57cec5SDimitry Andric
getMachineMemOperand(MachinePointerInfo PtrInfo,MachineMemOperand::Flags f,LLT MemTy,Align base_alignment,const AAMDNodes & AAInfo,const MDNode * Ranges,SyncScope::ID SSID,AtomicOrdering Ordering,AtomicOrdering FailureOrdering)495e8d8bef9SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
496fe6060f1SDimitry Andric MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
497fe6060f1SDimitry Andric Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
498fe6060f1SDimitry Andric SyncScope::ID SSID, AtomicOrdering Ordering,
499fe6060f1SDimitry Andric AtomicOrdering FailureOrdering) {
500fe6060f1SDimitry Andric return new (Allocator)
501fe6060f1SDimitry Andric MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
502fe6060f1SDimitry Andric Ordering, FailureOrdering);
503fe6060f1SDimitry Andric }
504fe6060f1SDimitry Andric
getMachineMemOperand(const MachineMemOperand * MMO,const MachinePointerInfo & PtrInfo,uint64_t Size)505fe6060f1SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
506fe6060f1SDimitry Andric const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
507fe6060f1SDimitry Andric return new (Allocator)
508fe6060f1SDimitry Andric MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
509fe6060f1SDimitry Andric AAMDNodes(), nullptr, MMO->getSyncScopeID(),
510fe6060f1SDimitry Andric MMO->getSuccessOrdering(), MMO->getFailureOrdering());
511fe6060f1SDimitry Andric }
512fe6060f1SDimitry Andric
getMachineMemOperand(const MachineMemOperand * MMO,const MachinePointerInfo & PtrInfo,LLT Ty)513fe6060f1SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
514fe6060f1SDimitry Andric const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
515fe6060f1SDimitry Andric return new (Allocator)
516fe6060f1SDimitry Andric MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
517fe6060f1SDimitry Andric AAMDNodes(), nullptr, MMO->getSyncScopeID(),
518fe6060f1SDimitry Andric MMO->getSuccessOrdering(), MMO->getFailureOrdering());
519e8d8bef9SDimitry Andric }
520e8d8bef9SDimitry Andric
5210b57cec5SDimitry Andric MachineMemOperand *
getMachineMemOperand(const MachineMemOperand * MMO,int64_t Offset,LLT Ty)5220b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
523fe6060f1SDimitry Andric int64_t Offset, LLT Ty) {
5240b57cec5SDimitry Andric const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
5250b57cec5SDimitry Andric
5260b57cec5SDimitry Andric // If there is no pointer value, the offset isn't tracked so we need to adjust
5270b57cec5SDimitry Andric // the base alignment.
5285ffd83dbSDimitry Andric Align Alignment = PtrInfo.V.isNull()
5295ffd83dbSDimitry Andric ? commonAlignment(MMO->getBaseAlign(), Offset)
5305ffd83dbSDimitry Andric : MMO->getBaseAlign();
5310b57cec5SDimitry Andric
532e8d8bef9SDimitry Andric // Do not preserve ranges, since we don't necessarily know what the high bits
533e8d8bef9SDimitry Andric // are anymore.
534fe6060f1SDimitry Andric return new (Allocator) MachineMemOperand(
535fe6060f1SDimitry Andric PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
536fe6060f1SDimitry Andric MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
537fe6060f1SDimitry Andric MMO->getSuccessOrdering(), MMO->getFailureOrdering());
5380b57cec5SDimitry Andric }
5390b57cec5SDimitry Andric
5400b57cec5SDimitry Andric MachineMemOperand *
getMachineMemOperand(const MachineMemOperand * MMO,const AAMDNodes & AAInfo)5410b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
5420b57cec5SDimitry Andric const AAMDNodes &AAInfo) {
5430b57cec5SDimitry Andric MachinePointerInfo MPI = MMO->getValue() ?
5440b57cec5SDimitry Andric MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
5450b57cec5SDimitry Andric MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
5460b57cec5SDimitry Andric
5475ffd83dbSDimitry Andric return new (Allocator) MachineMemOperand(
5485ffd83dbSDimitry Andric MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
549fe6060f1SDimitry Andric MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
5505ffd83dbSDimitry Andric MMO->getFailureOrdering());
5510b57cec5SDimitry Andric }
5520b57cec5SDimitry Andric
5530b57cec5SDimitry Andric MachineMemOperand *
getMachineMemOperand(const MachineMemOperand * MMO,MachineMemOperand::Flags Flags)5540b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
5550b57cec5SDimitry Andric MachineMemOperand::Flags Flags) {
5560b57cec5SDimitry Andric return new (Allocator) MachineMemOperand(
5575ffd83dbSDimitry Andric MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
5580b57cec5SDimitry Andric MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
559fe6060f1SDimitry Andric MMO->getSuccessOrdering(), MMO->getFailureOrdering());
5600b57cec5SDimitry Andric }
5610b57cec5SDimitry Andric
createMIExtraInfo(ArrayRef<MachineMemOperand * > MMOs,MCSymbol * PreInstrSymbol,MCSymbol * PostInstrSymbol,MDNode * HeapAllocMarker,MDNode * PCSections,uint32_t CFIType)562480093f4SDimitry Andric MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
563c14a5a88SDimitry Andric ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
564bdd1243dSDimitry Andric MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections,
565bdd1243dSDimitry Andric uint32_t CFIType) {
566c14a5a88SDimitry Andric return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
567bdd1243dSDimitry Andric PostInstrSymbol, HeapAllocMarker,
568bdd1243dSDimitry Andric PCSections, CFIType);
5690b57cec5SDimitry Andric }
5700b57cec5SDimitry Andric
createExternalSymbolName(StringRef Name)5710b57cec5SDimitry Andric const char *MachineFunction::createExternalSymbolName(StringRef Name) {
5720b57cec5SDimitry Andric char *Dest = Allocator.Allocate<char>(Name.size() + 1);
5730b57cec5SDimitry Andric llvm::copy(Name, Dest);
5740b57cec5SDimitry Andric Dest[Name.size()] = 0;
5750b57cec5SDimitry Andric return Dest;
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric
allocateRegMask()5780b57cec5SDimitry Andric uint32_t *MachineFunction::allocateRegMask() {
5790b57cec5SDimitry Andric unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
5800b57cec5SDimitry Andric unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
5810b57cec5SDimitry Andric uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
5820b57cec5SDimitry Andric memset(Mask, 0, Size * sizeof(Mask[0]));
5830b57cec5SDimitry Andric return Mask;
5840b57cec5SDimitry Andric }
5850b57cec5SDimitry Andric
allocateShuffleMask(ArrayRef<int> Mask)586480093f4SDimitry Andric ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
587480093f4SDimitry Andric int* AllocMask = Allocator.Allocate<int>(Mask.size());
588480093f4SDimitry Andric copy(Mask, AllocMask);
589480093f4SDimitry Andric return {AllocMask, Mask.size()};
590480093f4SDimitry Andric }
591480093f4SDimitry Andric
5920b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const5930b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineFunction::dump() const {
5940b57cec5SDimitry Andric print(dbgs());
5950b57cec5SDimitry Andric }
5960b57cec5SDimitry Andric #endif
5970b57cec5SDimitry Andric
getName() const5980b57cec5SDimitry Andric StringRef MachineFunction::getName() const {
5990b57cec5SDimitry Andric return getFunction().getName();
6000b57cec5SDimitry Andric }
6010b57cec5SDimitry Andric
print(raw_ostream & OS,const SlotIndexes * Indexes) const6020b57cec5SDimitry Andric void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
6030b57cec5SDimitry Andric OS << "# Machine code for function " << getName() << ": ";
6040b57cec5SDimitry Andric getProperties().print(OS);
6050b57cec5SDimitry Andric OS << '\n';
6060b57cec5SDimitry Andric
6070b57cec5SDimitry Andric // Print Frame Information
6080b57cec5SDimitry Andric FrameInfo->print(*this, OS);
6090b57cec5SDimitry Andric
6100b57cec5SDimitry Andric // Print JumpTable Information
6110b57cec5SDimitry Andric if (JumpTableInfo)
6120b57cec5SDimitry Andric JumpTableInfo->print(OS);
6130b57cec5SDimitry Andric
6140b57cec5SDimitry Andric // Print Constant Pool
6150b57cec5SDimitry Andric ConstantPool->print(OS);
6160b57cec5SDimitry Andric
6170b57cec5SDimitry Andric const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
6180b57cec5SDimitry Andric
6190b57cec5SDimitry Andric if (RegInfo && !RegInfo->livein_empty()) {
6200b57cec5SDimitry Andric OS << "Function Live Ins: ";
6210b57cec5SDimitry Andric for (MachineRegisterInfo::livein_iterator
6220b57cec5SDimitry Andric I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
6230b57cec5SDimitry Andric OS << printReg(I->first, TRI);
6240b57cec5SDimitry Andric if (I->second)
6250b57cec5SDimitry Andric OS << " in " << printReg(I->second, TRI);
6260b57cec5SDimitry Andric if (std::next(I) != E)
6270b57cec5SDimitry Andric OS << ", ";
6280b57cec5SDimitry Andric }
6290b57cec5SDimitry Andric OS << '\n';
6300b57cec5SDimitry Andric }
6310b57cec5SDimitry Andric
6320b57cec5SDimitry Andric ModuleSlotTracker MST(getFunction().getParent());
6330b57cec5SDimitry Andric MST.incorporateFunction(getFunction());
6340b57cec5SDimitry Andric for (const auto &BB : *this) {
6350b57cec5SDimitry Andric OS << '\n';
6360b57cec5SDimitry Andric // If we print the whole function, print it at its most verbose level.
6370b57cec5SDimitry Andric BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
6380b57cec5SDimitry Andric }
6390b57cec5SDimitry Andric
6400b57cec5SDimitry Andric OS << "\n# End machine code for function " << getName() << ".\n\n";
6410b57cec5SDimitry Andric }
6420b57cec5SDimitry Andric
643480093f4SDimitry Andric /// True if this function needs frame moves for debug or exceptions.
needsFrameMoves() const644480093f4SDimitry Andric bool MachineFunction::needsFrameMoves() const {
645480093f4SDimitry Andric return getMMI().hasDebugInfo() ||
646480093f4SDimitry Andric getTarget().Options.ForceDwarfFrameSection ||
647480093f4SDimitry Andric F.needsUnwindTableEntry();
648480093f4SDimitry Andric }
649480093f4SDimitry Andric
6500b57cec5SDimitry Andric namespace llvm {
6510b57cec5SDimitry Andric
6520b57cec5SDimitry Andric template<>
6530b57cec5SDimitry Andric struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
DOTGraphTraitsllvm::DOTGraphTraits6540b57cec5SDimitry Andric DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
6550b57cec5SDimitry Andric
getGraphNamellvm::DOTGraphTraits6560b57cec5SDimitry Andric static std::string getGraphName(const MachineFunction *F) {
6570b57cec5SDimitry Andric return ("CFG for '" + F->getName() + "' function").str();
6580b57cec5SDimitry Andric }
6590b57cec5SDimitry Andric
getNodeLabelllvm::DOTGraphTraits6600b57cec5SDimitry Andric std::string getNodeLabel(const MachineBasicBlock *Node,
6610b57cec5SDimitry Andric const MachineFunction *Graph) {
6620b57cec5SDimitry Andric std::string OutStr;
6630b57cec5SDimitry Andric {
6640b57cec5SDimitry Andric raw_string_ostream OSS(OutStr);
6650b57cec5SDimitry Andric
6660b57cec5SDimitry Andric if (isSimple()) {
6670b57cec5SDimitry Andric OSS << printMBBReference(*Node);
6680b57cec5SDimitry Andric if (const BasicBlock *BB = Node->getBasicBlock())
6690b57cec5SDimitry Andric OSS << ": " << BB->getName();
6700b57cec5SDimitry Andric } else
6710b57cec5SDimitry Andric Node->print(OSS);
6720b57cec5SDimitry Andric }
6730b57cec5SDimitry Andric
6740b57cec5SDimitry Andric if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
6750b57cec5SDimitry Andric
6760b57cec5SDimitry Andric // Process string output to make it nicer...
6770b57cec5SDimitry Andric for (unsigned i = 0; i != OutStr.length(); ++i)
6780b57cec5SDimitry Andric if (OutStr[i] == '\n') { // Left justify
6790b57cec5SDimitry Andric OutStr[i] = '\\';
6800b57cec5SDimitry Andric OutStr.insert(OutStr.begin()+i+1, 'l');
6810b57cec5SDimitry Andric }
6820b57cec5SDimitry Andric return OutStr;
6830b57cec5SDimitry Andric }
6840b57cec5SDimitry Andric };
6850b57cec5SDimitry Andric
6860b57cec5SDimitry Andric } // end namespace llvm
6870b57cec5SDimitry Andric
viewCFG() const6880b57cec5SDimitry Andric void MachineFunction::viewCFG() const
6890b57cec5SDimitry Andric {
6900b57cec5SDimitry Andric #ifndef NDEBUG
6910b57cec5SDimitry Andric ViewGraph(this, "mf" + getName());
6920b57cec5SDimitry Andric #else
6930b57cec5SDimitry Andric errs() << "MachineFunction::viewCFG is only available in debug builds on "
6940b57cec5SDimitry Andric << "systems with Graphviz or gv!\n";
6950b57cec5SDimitry Andric #endif // NDEBUG
6960b57cec5SDimitry Andric }
6970b57cec5SDimitry Andric
viewCFGOnly() const6980b57cec5SDimitry Andric void MachineFunction::viewCFGOnly() const
6990b57cec5SDimitry Andric {
7000b57cec5SDimitry Andric #ifndef NDEBUG
7010b57cec5SDimitry Andric ViewGraph(this, "mf" + getName(), true);
7020b57cec5SDimitry Andric #else
7030b57cec5SDimitry Andric errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
7040b57cec5SDimitry Andric << "systems with Graphviz or gv!\n";
7050b57cec5SDimitry Andric #endif // NDEBUG
7060b57cec5SDimitry Andric }
7070b57cec5SDimitry Andric
7080b57cec5SDimitry Andric /// Add the specified physical register as a live-in value and
7090b57cec5SDimitry Andric /// create a corresponding virtual register for it.
addLiveIn(MCRegister PReg,const TargetRegisterClass * RC)7105ffd83dbSDimitry Andric Register MachineFunction::addLiveIn(MCRegister PReg,
7110b57cec5SDimitry Andric const TargetRegisterClass *RC) {
7120b57cec5SDimitry Andric MachineRegisterInfo &MRI = getRegInfo();
7135ffd83dbSDimitry Andric Register VReg = MRI.getLiveInVirtReg(PReg);
7140b57cec5SDimitry Andric if (VReg) {
7150b57cec5SDimitry Andric const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
7160b57cec5SDimitry Andric (void)VRegRC;
7170b57cec5SDimitry Andric // A physical register can be added several times.
7180b57cec5SDimitry Andric // Between two calls, the register class of the related virtual register
7190b57cec5SDimitry Andric // may have been constrained to match some operation constraints.
7200b57cec5SDimitry Andric // In that case, check that the current register class includes the
7210b57cec5SDimitry Andric // physical register and is a sub class of the specified RC.
7220b57cec5SDimitry Andric assert((VRegRC == RC || (VRegRC->contains(PReg) &&
7230b57cec5SDimitry Andric RC->hasSubClassEq(VRegRC))) &&
7240b57cec5SDimitry Andric "Register class mismatch!");
7250b57cec5SDimitry Andric return VReg;
7260b57cec5SDimitry Andric }
7270b57cec5SDimitry Andric VReg = MRI.createVirtualRegister(RC);
7280b57cec5SDimitry Andric MRI.addLiveIn(PReg, VReg);
7290b57cec5SDimitry Andric return VReg;
7300b57cec5SDimitry Andric }
7310b57cec5SDimitry Andric
7320b57cec5SDimitry Andric /// Return the MCSymbol for the specified non-empty jump table.
7330b57cec5SDimitry Andric /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
7340b57cec5SDimitry Andric /// normal 'L' label is returned.
getJTISymbol(unsigned JTI,MCContext & Ctx,bool isLinkerPrivate) const7350b57cec5SDimitry Andric MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
7360b57cec5SDimitry Andric bool isLinkerPrivate) const {
7370b57cec5SDimitry Andric const DataLayout &DL = getDataLayout();
7380b57cec5SDimitry Andric assert(JumpTableInfo && "No jump tables");
7390b57cec5SDimitry Andric assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
7400b57cec5SDimitry Andric
7410b57cec5SDimitry Andric StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
7420b57cec5SDimitry Andric : DL.getPrivateGlobalPrefix();
7430b57cec5SDimitry Andric SmallString<60> Name;
7440b57cec5SDimitry Andric raw_svector_ostream(Name)
7450b57cec5SDimitry Andric << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
7460b57cec5SDimitry Andric return Ctx.getOrCreateSymbol(Name);
7470b57cec5SDimitry Andric }
7480b57cec5SDimitry Andric
7490b57cec5SDimitry Andric /// Return a function-local symbol to represent the PIC base.
getPICBaseSymbol() const7500b57cec5SDimitry Andric MCSymbol *MachineFunction::getPICBaseSymbol() const {
7510b57cec5SDimitry Andric const DataLayout &DL = getDataLayout();
7520b57cec5SDimitry Andric return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
7530b57cec5SDimitry Andric Twine(getFunctionNumber()) + "$pb");
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric
7560b57cec5SDimitry Andric /// \name Exception Handling
7570b57cec5SDimitry Andric /// \{
7580b57cec5SDimitry Andric
7590b57cec5SDimitry Andric LandingPadInfo &
getOrCreateLandingPadInfo(MachineBasicBlock * LandingPad)7600b57cec5SDimitry Andric MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
7610b57cec5SDimitry Andric unsigned N = LandingPads.size();
7620b57cec5SDimitry Andric for (unsigned i = 0; i < N; ++i) {
7630b57cec5SDimitry Andric LandingPadInfo &LP = LandingPads[i];
7640b57cec5SDimitry Andric if (LP.LandingPadBlock == LandingPad)
7650b57cec5SDimitry Andric return LP;
7660b57cec5SDimitry Andric }
7670b57cec5SDimitry Andric
7680b57cec5SDimitry Andric LandingPads.push_back(LandingPadInfo(LandingPad));
7690b57cec5SDimitry Andric return LandingPads[N];
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric
addInvoke(MachineBasicBlock * LandingPad,MCSymbol * BeginLabel,MCSymbol * EndLabel)7720b57cec5SDimitry Andric void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
7730b57cec5SDimitry Andric MCSymbol *BeginLabel, MCSymbol *EndLabel) {
7740b57cec5SDimitry Andric LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
7750b57cec5SDimitry Andric LP.BeginLabels.push_back(BeginLabel);
7760b57cec5SDimitry Andric LP.EndLabels.push_back(EndLabel);
7770b57cec5SDimitry Andric }
7780b57cec5SDimitry Andric
addLandingPad(MachineBasicBlock * LandingPad)7790b57cec5SDimitry Andric MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
7800b57cec5SDimitry Andric MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
7810b57cec5SDimitry Andric LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
7820b57cec5SDimitry Andric LP.LandingPadLabel = LandingPadLabel;
7830b57cec5SDimitry Andric
7840b57cec5SDimitry Andric const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
7850b57cec5SDimitry Andric if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
786bdd1243dSDimitry Andric // If there's no typeid list specified, then "cleanup" is implicit.
787bdd1243dSDimitry Andric // Otherwise, id 0 is reserved for the cleanup action.
788bdd1243dSDimitry Andric if (LPI->isCleanup() && LPI->getNumClauses() != 0)
789bdd1243dSDimitry Andric LP.TypeIds.push_back(0);
7900b57cec5SDimitry Andric
7910b57cec5SDimitry Andric // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
7920b57cec5SDimitry Andric // correct, but we need to do it this way because of how the DWARF EH
7930b57cec5SDimitry Andric // emitter processes the clauses.
7940b57cec5SDimitry Andric for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
7950b57cec5SDimitry Andric Value *Val = LPI->getClause(I - 1);
7960b57cec5SDimitry Andric if (LPI->isCatch(I - 1)) {
797bdd1243dSDimitry Andric LP.TypeIds.push_back(
798bdd1243dSDimitry Andric getTypeIDFor(dyn_cast<GlobalValue>(Val->stripPointerCasts())));
7990b57cec5SDimitry Andric } else {
8000b57cec5SDimitry Andric // Add filters in a list.
8010b57cec5SDimitry Andric auto *CVal = cast<Constant>(Val);
802bdd1243dSDimitry Andric SmallVector<unsigned, 4> FilterList;
803349cc55cSDimitry Andric for (const Use &U : CVal->operands())
804bdd1243dSDimitry Andric FilterList.push_back(
805bdd1243dSDimitry Andric getTypeIDFor(cast<GlobalValue>(U->stripPointerCasts())));
8060b57cec5SDimitry Andric
807bdd1243dSDimitry Andric LP.TypeIds.push_back(getFilterIDFor(FilterList));
8080b57cec5SDimitry Andric }
8090b57cec5SDimitry Andric }
8100b57cec5SDimitry Andric
8110b57cec5SDimitry Andric } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
812bdd1243dSDimitry Andric for (unsigned I = CPI->arg_size(); I != 0; --I) {
813bdd1243dSDimitry Andric auto *TypeInfo =
814bdd1243dSDimitry Andric dyn_cast<GlobalValue>(CPI->getArgOperand(I - 1)->stripPointerCasts());
815bdd1243dSDimitry Andric LP.TypeIds.push_back(getTypeIDFor(TypeInfo));
8160b57cec5SDimitry Andric }
8170b57cec5SDimitry Andric
8180b57cec5SDimitry Andric } else {
8190b57cec5SDimitry Andric assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
8200b57cec5SDimitry Andric }
8210b57cec5SDimitry Andric
8220b57cec5SDimitry Andric return LandingPadLabel;
8230b57cec5SDimitry Andric }
8240b57cec5SDimitry Andric
setCallSiteLandingPad(MCSymbol * Sym,ArrayRef<unsigned> Sites)8250b57cec5SDimitry Andric void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
8260b57cec5SDimitry Andric ArrayRef<unsigned> Sites) {
8270b57cec5SDimitry Andric LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
8280b57cec5SDimitry Andric }
8290b57cec5SDimitry Andric
getTypeIDFor(const GlobalValue * TI)8300b57cec5SDimitry Andric unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
8310b57cec5SDimitry Andric for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
8320b57cec5SDimitry Andric if (TypeInfos[i] == TI) return i + 1;
8330b57cec5SDimitry Andric
8340b57cec5SDimitry Andric TypeInfos.push_back(TI);
8350b57cec5SDimitry Andric return TypeInfos.size();
8360b57cec5SDimitry Andric }
8370b57cec5SDimitry Andric
getFilterIDFor(ArrayRef<unsigned> TyIds)838bdd1243dSDimitry Andric int MachineFunction::getFilterIDFor(ArrayRef<unsigned> TyIds) {
8390b57cec5SDimitry Andric // If the new filter coincides with the tail of an existing filter, then
8400b57cec5SDimitry Andric // re-use the existing filter. Folding filters more than this requires
8410b57cec5SDimitry Andric // re-ordering filters and/or their elements - probably not worth it.
842fe6060f1SDimitry Andric for (unsigned i : FilterEnds) {
843fe6060f1SDimitry Andric unsigned j = TyIds.size();
8440b57cec5SDimitry Andric
8450b57cec5SDimitry Andric while (i && j)
8460b57cec5SDimitry Andric if (FilterIds[--i] != TyIds[--j])
8470b57cec5SDimitry Andric goto try_next;
8480b57cec5SDimitry Andric
8490b57cec5SDimitry Andric if (!j)
8500b57cec5SDimitry Andric // The new filter coincides with range [i, end) of the existing filter.
8510b57cec5SDimitry Andric return -(1 + i);
8520b57cec5SDimitry Andric
8530b57cec5SDimitry Andric try_next:;
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric
8560b57cec5SDimitry Andric // Add the new filter.
8570b57cec5SDimitry Andric int FilterID = -(1 + FilterIds.size());
8580b57cec5SDimitry Andric FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
859e8d8bef9SDimitry Andric llvm::append_range(FilterIds, TyIds);
8600b57cec5SDimitry Andric FilterEnds.push_back(FilterIds.size());
8610b57cec5SDimitry Andric FilterIds.push_back(0); // terminator
8620b57cec5SDimitry Andric return FilterID;
8630b57cec5SDimitry Andric }
8640b57cec5SDimitry Andric
865480093f4SDimitry Andric MachineFunction::CallSiteInfoMap::iterator
getCallSiteInfo(const MachineInstr * MI)866480093f4SDimitry Andric MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
8675ffd83dbSDimitry Andric assert(MI->isCandidateForCallSiteEntry() &&
8685ffd83dbSDimitry Andric "Call site info refers only to call (MI) candidates");
8690b57cec5SDimitry Andric
8705ffd83dbSDimitry Andric if (!Target.Options.EmitCallSiteInfo)
871480093f4SDimitry Andric return CallSitesInfo.end();
872480093f4SDimitry Andric return CallSitesInfo.find(MI);
8730b57cec5SDimitry Andric }
8740b57cec5SDimitry Andric
8755ffd83dbSDimitry Andric /// Return the call machine instruction or find a call within bundle.
getCallInstr(const MachineInstr * MI)8765ffd83dbSDimitry Andric static const MachineInstr *getCallInstr(const MachineInstr *MI) {
8775ffd83dbSDimitry Andric if (!MI->isBundle())
8785ffd83dbSDimitry Andric return MI;
8790b57cec5SDimitry Andric
880fcaf7f86SDimitry Andric for (const auto &BMI : make_range(getBundleStart(MI->getIterator()),
8815ffd83dbSDimitry Andric getBundleEnd(MI->getIterator())))
8825ffd83dbSDimitry Andric if (BMI.isCandidateForCallSiteEntry())
8835ffd83dbSDimitry Andric return &BMI;
8848bcb0991SDimitry Andric
8855ffd83dbSDimitry Andric llvm_unreachable("Unexpected bundle without a call site candidate");
8868bcb0991SDimitry Andric }
8878bcb0991SDimitry Andric
eraseCallSiteInfo(const MachineInstr * MI)8888bcb0991SDimitry Andric void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
8895ffd83dbSDimitry Andric assert(MI->shouldUpdateCallSiteInfo() &&
8905ffd83dbSDimitry Andric "Call site info refers only to call (MI) candidates or "
8915ffd83dbSDimitry Andric "candidates inside bundles");
8925ffd83dbSDimitry Andric
8935ffd83dbSDimitry Andric const MachineInstr *CallMI = getCallInstr(MI);
8945ffd83dbSDimitry Andric CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
8958bcb0991SDimitry Andric if (CSIt == CallSitesInfo.end())
8968bcb0991SDimitry Andric return;
8978bcb0991SDimitry Andric CallSitesInfo.erase(CSIt);
8988bcb0991SDimitry Andric }
8998bcb0991SDimitry Andric
copyCallSiteInfo(const MachineInstr * Old,const MachineInstr * New)9008bcb0991SDimitry Andric void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
9018bcb0991SDimitry Andric const MachineInstr *New) {
9025ffd83dbSDimitry Andric assert(Old->shouldUpdateCallSiteInfo() &&
9035ffd83dbSDimitry Andric "Call site info refers only to call (MI) candidates or "
9045ffd83dbSDimitry Andric "candidates inside bundles");
9058bcb0991SDimitry Andric
9065ffd83dbSDimitry Andric if (!New->isCandidateForCallSiteEntry())
9075ffd83dbSDimitry Andric return eraseCallSiteInfo(Old);
9085ffd83dbSDimitry Andric
9095ffd83dbSDimitry Andric const MachineInstr *OldCallMI = getCallInstr(Old);
9105ffd83dbSDimitry Andric CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9118bcb0991SDimitry Andric if (CSIt == CallSitesInfo.end())
9128bcb0991SDimitry Andric return;
9138bcb0991SDimitry Andric
9148bcb0991SDimitry Andric CallSiteInfo CSInfo = CSIt->second;
9150b57cec5SDimitry Andric CallSitesInfo[New] = CSInfo;
9160b57cec5SDimitry Andric }
9170b57cec5SDimitry Andric
moveCallSiteInfo(const MachineInstr * Old,const MachineInstr * New)9185ffd83dbSDimitry Andric void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
9195ffd83dbSDimitry Andric const MachineInstr *New) {
9205ffd83dbSDimitry Andric assert(Old->shouldUpdateCallSiteInfo() &&
9215ffd83dbSDimitry Andric "Call site info refers only to call (MI) candidates or "
9225ffd83dbSDimitry Andric "candidates inside bundles");
9235ffd83dbSDimitry Andric
9245ffd83dbSDimitry Andric if (!New->isCandidateForCallSiteEntry())
9255ffd83dbSDimitry Andric return eraseCallSiteInfo(Old);
9265ffd83dbSDimitry Andric
9275ffd83dbSDimitry Andric const MachineInstr *OldCallMI = getCallInstr(Old);
9285ffd83dbSDimitry Andric CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9295ffd83dbSDimitry Andric if (CSIt == CallSitesInfo.end())
9305ffd83dbSDimitry Andric return;
9315ffd83dbSDimitry Andric
9325ffd83dbSDimitry Andric CallSiteInfo CSInfo = std::move(CSIt->second);
9335ffd83dbSDimitry Andric CallSitesInfo.erase(CSIt);
9345ffd83dbSDimitry Andric CallSitesInfo[New] = CSInfo;
9355ffd83dbSDimitry Andric }
9365ffd83dbSDimitry Andric
setDebugInstrNumberingCount(unsigned Num)937e8d8bef9SDimitry Andric void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
938e8d8bef9SDimitry Andric DebugInstrNumberingCount = Num;
939e8d8bef9SDimitry Andric }
940e8d8bef9SDimitry Andric
makeDebugValueSubstitution(DebugInstrOperandPair A,DebugInstrOperandPair B,unsigned Subreg)941e8d8bef9SDimitry Andric void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
942fe6060f1SDimitry Andric DebugInstrOperandPair B,
943fe6060f1SDimitry Andric unsigned Subreg) {
944fe6060f1SDimitry Andric // Catch any accidental self-loops.
945fe6060f1SDimitry Andric assert(A.first != B.first);
946349cc55cSDimitry Andric // Don't allow any substitutions _from_ the memory operand number.
947349cc55cSDimitry Andric assert(A.second != DebugOperandMemNumber);
948349cc55cSDimitry Andric
949fe6060f1SDimitry Andric DebugValueSubstitutions.push_back({A, B, Subreg});
950e8d8bef9SDimitry Andric }
951e8d8bef9SDimitry Andric
substituteDebugValuesForInst(const MachineInstr & Old,MachineInstr & New,unsigned MaxOperand)952e8d8bef9SDimitry Andric void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
953e8d8bef9SDimitry Andric MachineInstr &New,
954e8d8bef9SDimitry Andric unsigned MaxOperand) {
955e8d8bef9SDimitry Andric // If the Old instruction wasn't tracked at all, there is no work to do.
956e8d8bef9SDimitry Andric unsigned OldInstrNum = Old.peekDebugInstrNum();
957e8d8bef9SDimitry Andric if (!OldInstrNum)
958e8d8bef9SDimitry Andric return;
959e8d8bef9SDimitry Andric
960e8d8bef9SDimitry Andric // Iterate over all operands looking for defs to create substitutions for.
961e8d8bef9SDimitry Andric // Avoid creating new instr numbers unless we create a new substitution.
962e8d8bef9SDimitry Andric // While this has no functional effect, it risks confusing someone reading
963e8d8bef9SDimitry Andric // MIR output.
964e8d8bef9SDimitry Andric // Examine all the operands, or the first N specified by the caller.
965e8d8bef9SDimitry Andric MaxOperand = std::min(MaxOperand, Old.getNumOperands());
966fe6060f1SDimitry Andric for (unsigned int I = 0; I < MaxOperand; ++I) {
967e8d8bef9SDimitry Andric const auto &OldMO = Old.getOperand(I);
968e8d8bef9SDimitry Andric auto &NewMO = New.getOperand(I);
969e8d8bef9SDimitry Andric (void)NewMO;
970e8d8bef9SDimitry Andric
971e8d8bef9SDimitry Andric if (!OldMO.isReg() || !OldMO.isDef())
972e8d8bef9SDimitry Andric continue;
973e8d8bef9SDimitry Andric assert(NewMO.isDef());
974e8d8bef9SDimitry Andric
975e8d8bef9SDimitry Andric unsigned NewInstrNum = New.getDebugInstrNum();
976e8d8bef9SDimitry Andric makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
977e8d8bef9SDimitry Andric std::make_pair(NewInstrNum, I));
978e8d8bef9SDimitry Andric }
979e8d8bef9SDimitry Andric }
980e8d8bef9SDimitry Andric
salvageCopySSA(MachineInstr & MI,DenseMap<Register,DebugInstrOperandPair> & DbgPHICache)98181ad6265SDimitry Andric auto MachineFunction::salvageCopySSA(
98281ad6265SDimitry Andric MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache)
98381ad6265SDimitry Andric -> DebugInstrOperandPair {
98481ad6265SDimitry Andric const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
98581ad6265SDimitry Andric
98681ad6265SDimitry Andric // Check whether this copy-like instruction has already been salvaged into
98781ad6265SDimitry Andric // an operand pair.
98881ad6265SDimitry Andric Register Dest;
98981ad6265SDimitry Andric if (auto CopyDstSrc = TII.isCopyInstr(MI)) {
99081ad6265SDimitry Andric Dest = CopyDstSrc->Destination->getReg();
99181ad6265SDimitry Andric } else {
99281ad6265SDimitry Andric assert(MI.isSubregToReg());
99381ad6265SDimitry Andric Dest = MI.getOperand(0).getReg();
99481ad6265SDimitry Andric }
99581ad6265SDimitry Andric
99681ad6265SDimitry Andric auto CacheIt = DbgPHICache.find(Dest);
99781ad6265SDimitry Andric if (CacheIt != DbgPHICache.end())
99881ad6265SDimitry Andric return CacheIt->second;
99981ad6265SDimitry Andric
100081ad6265SDimitry Andric // Calculate the instruction number to use, or install a DBG_PHI.
100181ad6265SDimitry Andric auto OperandPair = salvageCopySSAImpl(MI);
100281ad6265SDimitry Andric DbgPHICache.insert({Dest, OperandPair});
100381ad6265SDimitry Andric return OperandPair;
100481ad6265SDimitry Andric }
100581ad6265SDimitry Andric
salvageCopySSAImpl(MachineInstr & MI)100681ad6265SDimitry Andric auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI)
1007fe6060f1SDimitry Andric -> DebugInstrOperandPair {
1008fe6060f1SDimitry Andric MachineRegisterInfo &MRI = getRegInfo();
1009fe6060f1SDimitry Andric const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1010fe6060f1SDimitry Andric const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1011fe6060f1SDimitry Andric
1012fe6060f1SDimitry Andric // Chase the value read by a copy-like instruction back to the instruction
1013fe6060f1SDimitry Andric // that ultimately _defines_ that value. This may pass:
1014fe6060f1SDimitry Andric // * Through multiple intermediate copies, including subregister moves /
1015fe6060f1SDimitry Andric // copies,
1016fe6060f1SDimitry Andric // * Copies from physical registers that must then be traced back to the
1017fe6060f1SDimitry Andric // defining instruction,
1018fe6060f1SDimitry Andric // * Or, physical registers may be live-in to (only) the entry block, which
1019fe6060f1SDimitry Andric // requires a DBG_PHI to be created.
1020fe6060f1SDimitry Andric // We can pursue this problem in that order: trace back through copies,
1021fe6060f1SDimitry Andric // optionally through a physical register, to a defining instruction. We
1022fe6060f1SDimitry Andric // should never move from physreg to vreg. As we're still in SSA form, no need
1023fe6060f1SDimitry Andric // to worry about partial definitions of registers.
1024fe6060f1SDimitry Andric
1025fe6060f1SDimitry Andric // Helper lambda to interpret a copy-like instruction. Takes instruction,
1026fe6060f1SDimitry Andric // returns the register read and any subregister identifying which part is
1027fe6060f1SDimitry Andric // read.
1028fe6060f1SDimitry Andric auto GetRegAndSubreg =
1029fe6060f1SDimitry Andric [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1030fe6060f1SDimitry Andric Register NewReg, OldReg;
1031fe6060f1SDimitry Andric unsigned SubReg;
1032fe6060f1SDimitry Andric if (Cpy.isCopy()) {
1033fe6060f1SDimitry Andric OldReg = Cpy.getOperand(0).getReg();
1034fe6060f1SDimitry Andric NewReg = Cpy.getOperand(1).getReg();
1035fe6060f1SDimitry Andric SubReg = Cpy.getOperand(1).getSubReg();
1036fe6060f1SDimitry Andric } else if (Cpy.isSubregToReg()) {
1037fe6060f1SDimitry Andric OldReg = Cpy.getOperand(0).getReg();
1038fe6060f1SDimitry Andric NewReg = Cpy.getOperand(2).getReg();
1039fe6060f1SDimitry Andric SubReg = Cpy.getOperand(3).getImm();
1040fe6060f1SDimitry Andric } else {
1041fe6060f1SDimitry Andric auto CopyDetails = *TII.isCopyInstr(Cpy);
1042fe6060f1SDimitry Andric const MachineOperand &Src = *CopyDetails.Source;
1043fe6060f1SDimitry Andric const MachineOperand &Dest = *CopyDetails.Destination;
1044fe6060f1SDimitry Andric OldReg = Dest.getReg();
1045fe6060f1SDimitry Andric NewReg = Src.getReg();
1046fe6060f1SDimitry Andric SubReg = Src.getSubReg();
1047fe6060f1SDimitry Andric }
1048fe6060f1SDimitry Andric
1049fe6060f1SDimitry Andric return {NewReg, SubReg};
1050fe6060f1SDimitry Andric };
1051fe6060f1SDimitry Andric
1052fe6060f1SDimitry Andric // First seek either the defining instruction, or a copy from a physreg.
1053fe6060f1SDimitry Andric // During search, the current state is the current copy instruction, and which
1054fe6060f1SDimitry Andric // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1055fe6060f1SDimitry Andric // deal with those later.
1056fe6060f1SDimitry Andric auto State = GetRegAndSubreg(MI);
1057fe6060f1SDimitry Andric auto CurInst = MI.getIterator();
1058fe6060f1SDimitry Andric SmallVector<unsigned, 4> SubregsSeen;
1059fe6060f1SDimitry Andric while (true) {
1060fe6060f1SDimitry Andric // If we've found a copy from a physreg, first portion of search is over.
1061fe6060f1SDimitry Andric if (!State.first.isVirtual())
1062fe6060f1SDimitry Andric break;
1063fe6060f1SDimitry Andric
1064fe6060f1SDimitry Andric // Record any subregister qualifier.
1065fe6060f1SDimitry Andric if (State.second)
1066fe6060f1SDimitry Andric SubregsSeen.push_back(State.second);
1067fe6060f1SDimitry Andric
1068fe6060f1SDimitry Andric assert(MRI.hasOneDef(State.first));
1069fe6060f1SDimitry Andric MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1070fe6060f1SDimitry Andric CurInst = Inst.getIterator();
1071fe6060f1SDimitry Andric
1072fe6060f1SDimitry Andric // Any non-copy instruction is the defining instruction we're seeking.
1073fe6060f1SDimitry Andric if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1074fe6060f1SDimitry Andric break;
1075fe6060f1SDimitry Andric State = GetRegAndSubreg(Inst);
1076fe6060f1SDimitry Andric };
1077fe6060f1SDimitry Andric
1078fe6060f1SDimitry Andric // Helper lambda to apply additional subregister substitutions to a known
1079fe6060f1SDimitry Andric // instruction/operand pair. Adds new (fake) substitutions so that we can
1080fe6060f1SDimitry Andric // record the subregister. FIXME: this isn't very space efficient if multiple
1081fe6060f1SDimitry Andric // values are tracked back through the same copies; cache something later.
1082fe6060f1SDimitry Andric auto ApplySubregisters =
1083fe6060f1SDimitry Andric [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1084fe6060f1SDimitry Andric for (unsigned Subreg : reverse(SubregsSeen)) {
1085fe6060f1SDimitry Andric // Fetch a new instruction number, not attached to an actual instruction.
1086fe6060f1SDimitry Andric unsigned NewInstrNumber = getNewDebugInstrNum();
1087fe6060f1SDimitry Andric // Add a substitution from the "new" number to the known one, with a
1088fe6060f1SDimitry Andric // qualifying subreg.
1089fe6060f1SDimitry Andric makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1090fe6060f1SDimitry Andric // Return the new number; to find the underlying value, consumers need to
1091fe6060f1SDimitry Andric // deal with the qualifying subreg.
1092fe6060f1SDimitry Andric P = {NewInstrNumber, 0};
1093fe6060f1SDimitry Andric }
1094fe6060f1SDimitry Andric return P;
1095fe6060f1SDimitry Andric };
1096fe6060f1SDimitry Andric
1097fe6060f1SDimitry Andric // If we managed to find the defining instruction after COPYs, return an
1098fe6060f1SDimitry Andric // instruction / operand pair after adding subregister qualifiers.
1099fe6060f1SDimitry Andric if (State.first.isVirtual()) {
1100fe6060f1SDimitry Andric // Virtual register def -- we can just look up where this happens.
1101fe6060f1SDimitry Andric MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
1102fe013be4SDimitry Andric for (auto &MO : Inst->all_defs()) {
1103fe013be4SDimitry Andric if (MO.getReg() != State.first)
1104fe6060f1SDimitry Andric continue;
1105fe013be4SDimitry Andric return ApplySubregisters({Inst->getDebugInstrNum(), MO.getOperandNo()});
1106fe6060f1SDimitry Andric }
1107fe6060f1SDimitry Andric
1108fe6060f1SDimitry Andric llvm_unreachable("Vreg def with no corresponding operand?");
1109fe6060f1SDimitry Andric }
1110fe6060f1SDimitry Andric
1111fe6060f1SDimitry Andric // Our search ended in a copy from a physreg: walk back up the function
1112fe6060f1SDimitry Andric // looking for whatever defines the physreg.
1113fe6060f1SDimitry Andric assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1114fe6060f1SDimitry Andric State = GetRegAndSubreg(*CurInst);
1115fe6060f1SDimitry Andric Register RegToSeek = State.first;
1116fe6060f1SDimitry Andric
1117fe6060f1SDimitry Andric auto RMII = CurInst->getReverseIterator();
1118fe6060f1SDimitry Andric auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1119fe6060f1SDimitry Andric for (auto &ToExamine : PrevInstrs) {
1120fe013be4SDimitry Andric for (auto &MO : ToExamine.all_defs()) {
1121fe6060f1SDimitry Andric // Test for operand that defines something aliasing RegToSeek.
1122fe013be4SDimitry Andric if (!TRI.regsOverlap(RegToSeek, MO.getReg()))
1123fe6060f1SDimitry Andric continue;
1124fe6060f1SDimitry Andric
1125fe6060f1SDimitry Andric return ApplySubregisters(
1126fe013be4SDimitry Andric {ToExamine.getDebugInstrNum(), MO.getOperandNo()});
1127fe6060f1SDimitry Andric }
1128fe6060f1SDimitry Andric }
1129fe6060f1SDimitry Andric
1130fe6060f1SDimitry Andric MachineBasicBlock &InsertBB = *CurInst->getParent();
1131fe6060f1SDimitry Andric
1132fe6060f1SDimitry Andric // We reached the start of the block before finding a defining instruction.
113381ad6265SDimitry Andric // There are numerous scenarios where this can happen:
113481ad6265SDimitry Andric // * Constant physical registers,
113581ad6265SDimitry Andric // * Several intrinsics that allow LLVM-IR to read arbitary registers,
113681ad6265SDimitry Andric // * Arguments in the entry block,
113781ad6265SDimitry Andric // * Exception handling landing pads.
113881ad6265SDimitry Andric // Validating all of them is too difficult, so just insert a DBG_PHI reading
113981ad6265SDimitry Andric // the variable value at this position, rather than checking it makes sense.
1140fe6060f1SDimitry Andric
1141fe6060f1SDimitry Andric // Create DBG_PHI for specified physreg.
1142fe6060f1SDimitry Andric auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1143fe6060f1SDimitry Andric TII.get(TargetOpcode::DBG_PHI));
1144349cc55cSDimitry Andric Builder.addReg(State.first);
1145fe6060f1SDimitry Andric unsigned NewNum = getNewDebugInstrNum();
1146fe6060f1SDimitry Andric Builder.addImm(NewNum);
1147fe6060f1SDimitry Andric return ApplySubregisters({NewNum, 0u});
1148fe6060f1SDimitry Andric }
1149fe6060f1SDimitry Andric
finalizeDebugInstrRefs()1150fe6060f1SDimitry Andric void MachineFunction::finalizeDebugInstrRefs() {
1151fe6060f1SDimitry Andric auto *TII = getSubtarget().getInstrInfo();
1152fe6060f1SDimitry Andric
11534824e7fdSDimitry Andric auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1154bdd1243dSDimitry Andric const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE_LIST);
1155fe6060f1SDimitry Andric MI.setDesc(RefII);
1156bdd1243dSDimitry Andric MI.setDebugValueUndef();
1157fe6060f1SDimitry Andric };
1158fe6060f1SDimitry Andric
115981ad6265SDimitry Andric DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs;
1160fe6060f1SDimitry Andric for (auto &MBB : *this) {
1161fe6060f1SDimitry Andric for (auto &MI : MBB) {
1162bdd1243dSDimitry Andric if (!MI.isDebugRef())
1163fe6060f1SDimitry Andric continue;
1164fe6060f1SDimitry Andric
1165bdd1243dSDimitry Andric bool IsValidRef = true;
1166bdd1243dSDimitry Andric
1167bdd1243dSDimitry Andric for (MachineOperand &MO : MI.debug_operands()) {
1168bdd1243dSDimitry Andric if (!MO.isReg())
1169bdd1243dSDimitry Andric continue;
1170bdd1243dSDimitry Andric
1171bdd1243dSDimitry Andric Register Reg = MO.getReg();
1172fe6060f1SDimitry Andric
1173fe6060f1SDimitry Andric // Some vregs can be deleted as redundant in the meantime. Mark those
11744824e7fdSDimitry Andric // as DBG_VALUE $noreg. Additionally, some normal instructions are
11754824e7fdSDimitry Andric // quickly deleted, leaving dangling references to vregs with no def.
11764824e7fdSDimitry Andric if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
1177bdd1243dSDimitry Andric IsValidRef = false;
1178bdd1243dSDimitry Andric break;
1179fe6060f1SDimitry Andric }
1180fe6060f1SDimitry Andric
1181fe6060f1SDimitry Andric assert(Reg.isVirtual());
1182fe6060f1SDimitry Andric MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1183fe6060f1SDimitry Andric
1184fe6060f1SDimitry Andric // If we've found a copy-like instruction, follow it back to the
1185fe6060f1SDimitry Andric // instruction that defines the source value, see salvageCopySSA docs
1186fe6060f1SDimitry Andric // for why this is important.
1187fe6060f1SDimitry Andric if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
118881ad6265SDimitry Andric auto Result = salvageCopySSA(DefMI, ArgDbgPHIs);
1189bdd1243dSDimitry Andric MO.ChangeToDbgInstrRef(Result.first, Result.second);
1190fe6060f1SDimitry Andric } else {
1191fe6060f1SDimitry Andric // Otherwise, identify the operand number that the VReg refers to.
1192fe6060f1SDimitry Andric unsigned OperandIdx = 0;
1193bdd1243dSDimitry Andric for (const auto &DefMO : DefMI.operands()) {
1194bdd1243dSDimitry Andric if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg)
1195fe6060f1SDimitry Andric break;
1196fe6060f1SDimitry Andric ++OperandIdx;
1197fe6060f1SDimitry Andric }
1198fe6060f1SDimitry Andric assert(OperandIdx < DefMI.getNumOperands());
1199fe6060f1SDimitry Andric
1200fe6060f1SDimitry Andric // Morph this instr ref to point at the given instruction and operand.
1201fe6060f1SDimitry Andric unsigned ID = DefMI.getDebugInstrNum();
1202bdd1243dSDimitry Andric MO.ChangeToDbgInstrRef(ID, OperandIdx);
1203fe6060f1SDimitry Andric }
1204fe6060f1SDimitry Andric }
1205bdd1243dSDimitry Andric
1206bdd1243dSDimitry Andric if (!IsValidRef)
1207bdd1243dSDimitry Andric MakeUndefDbgValue(MI);
1208bdd1243dSDimitry Andric }
1209fe6060f1SDimitry Andric }
1210fe6060f1SDimitry Andric }
1211fe6060f1SDimitry Andric
shouldUseDebugInstrRef() const1212bdd1243dSDimitry Andric bool MachineFunction::shouldUseDebugInstrRef() const {
1213349cc55cSDimitry Andric // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1214349cc55cSDimitry Andric // have optimized code inlined into this unoptimized code, however with
1215349cc55cSDimitry Andric // fewer and less aggressive optimizations happening, coverage and accuracy
1216349cc55cSDimitry Andric // should not suffer.
1217*c9157d92SDimitry Andric if (getTarget().getOptLevel() == CodeGenOptLevel::None)
1218349cc55cSDimitry Andric return false;
1219349cc55cSDimitry Andric
1220349cc55cSDimitry Andric // Don't use instr-ref if this function is marked optnone.
1221349cc55cSDimitry Andric if (F.hasFnAttribute(Attribute::OptimizeNone))
1222349cc55cSDimitry Andric return false;
1223349cc55cSDimitry Andric
122404eeddc0SDimitry Andric if (llvm::debuginfoShouldUseDebugInstrRef(getTarget().getTargetTriple()))
1225349cc55cSDimitry Andric return true;
1226349cc55cSDimitry Andric
1227349cc55cSDimitry Andric return false;
1228349cc55cSDimitry Andric }
1229349cc55cSDimitry Andric
useDebugInstrRef() const1230bdd1243dSDimitry Andric bool MachineFunction::useDebugInstrRef() const {
1231bdd1243dSDimitry Andric return UseDebugInstrRef;
1232bdd1243dSDimitry Andric }
1233bdd1243dSDimitry Andric
setUseDebugInstrRef(bool Use)1234bdd1243dSDimitry Andric void MachineFunction::setUseDebugInstrRef(bool Use) {
1235bdd1243dSDimitry Andric UseDebugInstrRef = Use;
1236bdd1243dSDimitry Andric }
1237bdd1243dSDimitry Andric
1238349cc55cSDimitry Andric // Use one million as a high / reserved number.
1239349cc55cSDimitry Andric const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1240349cc55cSDimitry Andric
12410b57cec5SDimitry Andric /// \}
12420b57cec5SDimitry Andric
12430b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12440b57cec5SDimitry Andric // MachineJumpTableInfo implementation
12450b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12460b57cec5SDimitry Andric
12470b57cec5SDimitry Andric /// Return the size of each entry in the jump table.
getEntrySize(const DataLayout & TD) const12480b57cec5SDimitry Andric unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
12490b57cec5SDimitry Andric // The size of a jump table entry is 4 bytes unless the entry is just the
12500b57cec5SDimitry Andric // address of a block, in which case it is the pointer size.
12510b57cec5SDimitry Andric switch (getEntryKind()) {
12520b57cec5SDimitry Andric case MachineJumpTableInfo::EK_BlockAddress:
12530b57cec5SDimitry Andric return TD.getPointerSize();
12540b57cec5SDimitry Andric case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1255*c9157d92SDimitry Andric case MachineJumpTableInfo::EK_LabelDifference64:
12560b57cec5SDimitry Andric return 8;
12570b57cec5SDimitry Andric case MachineJumpTableInfo::EK_GPRel32BlockAddress:
12580b57cec5SDimitry Andric case MachineJumpTableInfo::EK_LabelDifference32:
12590b57cec5SDimitry Andric case MachineJumpTableInfo::EK_Custom32:
12600b57cec5SDimitry Andric return 4;
12610b57cec5SDimitry Andric case MachineJumpTableInfo::EK_Inline:
12620b57cec5SDimitry Andric return 0;
12630b57cec5SDimitry Andric }
12640b57cec5SDimitry Andric llvm_unreachable("Unknown jump table encoding!");
12650b57cec5SDimitry Andric }
12660b57cec5SDimitry Andric
12670b57cec5SDimitry Andric /// Return the alignment of each entry in the jump table.
getEntryAlignment(const DataLayout & TD) const12680b57cec5SDimitry Andric unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
12690b57cec5SDimitry Andric // The alignment of a jump table entry is the alignment of int32 unless the
12700b57cec5SDimitry Andric // entry is just the address of a block, in which case it is the pointer
12710b57cec5SDimitry Andric // alignment.
12720b57cec5SDimitry Andric switch (getEntryKind()) {
12730b57cec5SDimitry Andric case MachineJumpTableInfo::EK_BlockAddress:
12748bcb0991SDimitry Andric return TD.getPointerABIAlignment(0).value();
12750b57cec5SDimitry Andric case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1276*c9157d92SDimitry Andric case MachineJumpTableInfo::EK_LabelDifference64:
12778bcb0991SDimitry Andric return TD.getABIIntegerTypeAlignment(64).value();
12780b57cec5SDimitry Andric case MachineJumpTableInfo::EK_GPRel32BlockAddress:
12790b57cec5SDimitry Andric case MachineJumpTableInfo::EK_LabelDifference32:
12800b57cec5SDimitry Andric case MachineJumpTableInfo::EK_Custom32:
12818bcb0991SDimitry Andric return TD.getABIIntegerTypeAlignment(32).value();
12820b57cec5SDimitry Andric case MachineJumpTableInfo::EK_Inline:
12830b57cec5SDimitry Andric return 1;
12840b57cec5SDimitry Andric }
12850b57cec5SDimitry Andric llvm_unreachable("Unknown jump table encoding!");
12860b57cec5SDimitry Andric }
12870b57cec5SDimitry Andric
12880b57cec5SDimitry Andric /// Create a new jump table entry in the jump table info.
createJumpTableIndex(const std::vector<MachineBasicBlock * > & DestBBs)12890b57cec5SDimitry Andric unsigned MachineJumpTableInfo::createJumpTableIndex(
12900b57cec5SDimitry Andric const std::vector<MachineBasicBlock*> &DestBBs) {
12910b57cec5SDimitry Andric assert(!DestBBs.empty() && "Cannot create an empty jump table!");
12920b57cec5SDimitry Andric JumpTables.push_back(MachineJumpTableEntry(DestBBs));
12930b57cec5SDimitry Andric return JumpTables.size()-1;
12940b57cec5SDimitry Andric }
12950b57cec5SDimitry Andric
12960b57cec5SDimitry Andric /// If Old is the target of any jump tables, update the jump tables to branch
12970b57cec5SDimitry Andric /// to New instead.
ReplaceMBBInJumpTables(MachineBasicBlock * Old,MachineBasicBlock * New)12980b57cec5SDimitry Andric bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
12990b57cec5SDimitry Andric MachineBasicBlock *New) {
13000b57cec5SDimitry Andric assert(Old != New && "Not making a change?");
13010b57cec5SDimitry Andric bool MadeChange = false;
13020b57cec5SDimitry Andric for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
13030b57cec5SDimitry Andric ReplaceMBBInJumpTable(i, Old, New);
13040b57cec5SDimitry Andric return MadeChange;
13050b57cec5SDimitry Andric }
13060b57cec5SDimitry Andric
1307e8d8bef9SDimitry Andric /// If MBB is present in any jump tables, remove it.
RemoveMBBFromJumpTables(MachineBasicBlock * MBB)1308e8d8bef9SDimitry Andric bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1309e8d8bef9SDimitry Andric bool MadeChange = false;
1310e8d8bef9SDimitry Andric for (MachineJumpTableEntry &JTE : JumpTables) {
1311e8d8bef9SDimitry Andric auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1312e8d8bef9SDimitry Andric MadeChange |= (removeBeginItr != JTE.MBBs.end());
1313e8d8bef9SDimitry Andric JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1314e8d8bef9SDimitry Andric }
1315e8d8bef9SDimitry Andric return MadeChange;
1316e8d8bef9SDimitry Andric }
1317e8d8bef9SDimitry Andric
13180b57cec5SDimitry Andric /// If Old is a target of the jump tables, update the jump table to branch to
13190b57cec5SDimitry Andric /// New instead.
ReplaceMBBInJumpTable(unsigned Idx,MachineBasicBlock * Old,MachineBasicBlock * New)13200b57cec5SDimitry Andric bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
13210b57cec5SDimitry Andric MachineBasicBlock *Old,
13220b57cec5SDimitry Andric MachineBasicBlock *New) {
13230b57cec5SDimitry Andric assert(Old != New && "Not making a change?");
13240b57cec5SDimitry Andric bool MadeChange = false;
13250b57cec5SDimitry Andric MachineJumpTableEntry &JTE = JumpTables[Idx];
13264824e7fdSDimitry Andric for (MachineBasicBlock *&MBB : JTE.MBBs)
13274824e7fdSDimitry Andric if (MBB == Old) {
13284824e7fdSDimitry Andric MBB = New;
13290b57cec5SDimitry Andric MadeChange = true;
13300b57cec5SDimitry Andric }
13310b57cec5SDimitry Andric return MadeChange;
13320b57cec5SDimitry Andric }
13330b57cec5SDimitry Andric
print(raw_ostream & OS) const13340b57cec5SDimitry Andric void MachineJumpTableInfo::print(raw_ostream &OS) const {
13350b57cec5SDimitry Andric if (JumpTables.empty()) return;
13360b57cec5SDimitry Andric
13370b57cec5SDimitry Andric OS << "Jump Tables:\n";
13380b57cec5SDimitry Andric
13390b57cec5SDimitry Andric for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
13400b57cec5SDimitry Andric OS << printJumpTableEntryReference(i) << ':';
13414824e7fdSDimitry Andric for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
13424824e7fdSDimitry Andric OS << ' ' << printMBBReference(*MBB);
13430b57cec5SDimitry Andric if (i != e)
13440b57cec5SDimitry Andric OS << '\n';
13450b57cec5SDimitry Andric }
13460b57cec5SDimitry Andric
13470b57cec5SDimitry Andric OS << '\n';
13480b57cec5SDimitry Andric }
13490b57cec5SDimitry Andric
13500b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const13510b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
13520b57cec5SDimitry Andric #endif
13530b57cec5SDimitry Andric
printJumpTableEntryReference(unsigned Idx)13540b57cec5SDimitry Andric Printable llvm::printJumpTableEntryReference(unsigned Idx) {
13550b57cec5SDimitry Andric return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
13560b57cec5SDimitry Andric }
13570b57cec5SDimitry Andric
13580b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13590b57cec5SDimitry Andric // MachineConstantPool implementation
13600b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13610b57cec5SDimitry Andric
anchor()13620b57cec5SDimitry Andric void MachineConstantPoolValue::anchor() {}
13630b57cec5SDimitry Andric
getSizeInBytes(const DataLayout & DL) const1364e8d8bef9SDimitry Andric unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1365e8d8bef9SDimitry Andric return DL.getTypeAllocSize(Ty);
1366e8d8bef9SDimitry Andric }
1367e8d8bef9SDimitry Andric
getSizeInBytes(const DataLayout & DL) const1368e8d8bef9SDimitry Andric unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
13690b57cec5SDimitry Andric if (isMachineConstantPoolEntry())
1370e8d8bef9SDimitry Andric return Val.MachineCPVal->getSizeInBytes(DL);
1371e8d8bef9SDimitry Andric return DL.getTypeAllocSize(Val.ConstVal->getType());
13720b57cec5SDimitry Andric }
13730b57cec5SDimitry Andric
needsRelocation() const13740b57cec5SDimitry Andric bool MachineConstantPoolEntry::needsRelocation() const {
13750b57cec5SDimitry Andric if (isMachineConstantPoolEntry())
13760b57cec5SDimitry Andric return true;
1377fe6060f1SDimitry Andric return Val.ConstVal->needsDynamicRelocation();
13780b57cec5SDimitry Andric }
13790b57cec5SDimitry Andric
13800b57cec5SDimitry Andric SectionKind
getSectionKind(const DataLayout * DL) const13810b57cec5SDimitry Andric MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
13820b57cec5SDimitry Andric if (needsRelocation())
13830b57cec5SDimitry Andric return SectionKind::getReadOnlyWithRel();
1384e8d8bef9SDimitry Andric switch (getSizeInBytes(*DL)) {
13850b57cec5SDimitry Andric case 4:
13860b57cec5SDimitry Andric return SectionKind::getMergeableConst4();
13870b57cec5SDimitry Andric case 8:
13880b57cec5SDimitry Andric return SectionKind::getMergeableConst8();
13890b57cec5SDimitry Andric case 16:
13900b57cec5SDimitry Andric return SectionKind::getMergeableConst16();
13910b57cec5SDimitry Andric case 32:
13920b57cec5SDimitry Andric return SectionKind::getMergeableConst32();
13930b57cec5SDimitry Andric default:
13940b57cec5SDimitry Andric return SectionKind::getReadOnly();
13950b57cec5SDimitry Andric }
13960b57cec5SDimitry Andric }
13970b57cec5SDimitry Andric
~MachineConstantPool()13980b57cec5SDimitry Andric MachineConstantPool::~MachineConstantPool() {
13990b57cec5SDimitry Andric // A constant may be a member of both Constants and MachineCPVsSharingEntries,
14000b57cec5SDimitry Andric // so keep track of which we've deleted to avoid double deletions.
14010b57cec5SDimitry Andric DenseSet<MachineConstantPoolValue*> Deleted;
14020eae32dcSDimitry Andric for (const MachineConstantPoolEntry &C : Constants)
14030eae32dcSDimitry Andric if (C.isMachineConstantPoolEntry()) {
14040eae32dcSDimitry Andric Deleted.insert(C.Val.MachineCPVal);
14050eae32dcSDimitry Andric delete C.Val.MachineCPVal;
14060b57cec5SDimitry Andric }
1407fe6060f1SDimitry Andric for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1408fe6060f1SDimitry Andric if (Deleted.count(CPV) == 0)
1409fe6060f1SDimitry Andric delete CPV;
14100b57cec5SDimitry Andric }
14110b57cec5SDimitry Andric }
14120b57cec5SDimitry Andric
14130b57cec5SDimitry Andric /// Test whether the given two constants can be allocated the same constant pool
1414fe013be4SDimitry Andric /// entry referenced by \param A.
CanShareConstantPoolEntry(const Constant * A,const Constant * B,const DataLayout & DL)14150b57cec5SDimitry Andric static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
14160b57cec5SDimitry Andric const DataLayout &DL) {
14170b57cec5SDimitry Andric // Handle the trivial case quickly.
14180b57cec5SDimitry Andric if (A == B) return true;
14190b57cec5SDimitry Andric
14200b57cec5SDimitry Andric // If they have the same type but weren't the same constant, quickly
14210b57cec5SDimitry Andric // reject them.
14220b57cec5SDimitry Andric if (A->getType() == B->getType()) return false;
14230b57cec5SDimitry Andric
14240b57cec5SDimitry Andric // We can't handle structs or arrays.
14250b57cec5SDimitry Andric if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
14260b57cec5SDimitry Andric isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
14270b57cec5SDimitry Andric return false;
14280b57cec5SDimitry Andric
14290b57cec5SDimitry Andric // For now, only support constants with the same size.
14300b57cec5SDimitry Andric uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
14310b57cec5SDimitry Andric if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
14320b57cec5SDimitry Andric return false;
14330b57cec5SDimitry Andric
1434fe013be4SDimitry Andric bool ContainsUndefOrPoisonA = A->containsUndefOrPoisonElement();
1435fe013be4SDimitry Andric
14360b57cec5SDimitry Andric Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
14370b57cec5SDimitry Andric
14380b57cec5SDimitry Andric // Try constant folding a bitcast of both instructions to an integer. If we
14390b57cec5SDimitry Andric // get two identical ConstantInt's, then we are good to share them. We use
14400b57cec5SDimitry Andric // the constant folding APIs to do this so that we get the benefit of
14410b57cec5SDimitry Andric // DataLayout.
14420b57cec5SDimitry Andric if (isa<PointerType>(A->getType()))
14430b57cec5SDimitry Andric A = ConstantFoldCastOperand(Instruction::PtrToInt,
14440b57cec5SDimitry Andric const_cast<Constant *>(A), IntTy, DL);
14450b57cec5SDimitry Andric else if (A->getType() != IntTy)
14460b57cec5SDimitry Andric A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
14470b57cec5SDimitry Andric IntTy, DL);
14480b57cec5SDimitry Andric if (isa<PointerType>(B->getType()))
14490b57cec5SDimitry Andric B = ConstantFoldCastOperand(Instruction::PtrToInt,
14500b57cec5SDimitry Andric const_cast<Constant *>(B), IntTy, DL);
14510b57cec5SDimitry Andric else if (B->getType() != IntTy)
14520b57cec5SDimitry Andric B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
14530b57cec5SDimitry Andric IntTy, DL);
14540b57cec5SDimitry Andric
1455fe013be4SDimitry Andric if (A != B)
1456fe013be4SDimitry Andric return false;
1457fe013be4SDimitry Andric
1458fe013be4SDimitry Andric // Constants only safely match if A doesn't contain undef/poison.
1459fe013be4SDimitry Andric // As we'll be reusing A, it doesn't matter if B contain undef/poison.
1460fe013be4SDimitry Andric // TODO: Handle cases where A and B have the same undef/poison elements.
1461fe013be4SDimitry Andric // TODO: Merge A and B with mismatching undef/poison elements.
1462fe013be4SDimitry Andric return !ContainsUndefOrPoisonA;
14630b57cec5SDimitry Andric }
14640b57cec5SDimitry Andric
14650b57cec5SDimitry Andric /// Create a new entry in the constant pool or return an existing one.
14660b57cec5SDimitry Andric /// User must specify the log2 of the minimum required alignment for the object.
getConstantPoolIndex(const Constant * C,Align Alignment)14670b57cec5SDimitry Andric unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
14685ffd83dbSDimitry Andric Align Alignment) {
14690b57cec5SDimitry Andric if (Alignment > PoolAlignment) PoolAlignment = Alignment;
14700b57cec5SDimitry Andric
14710b57cec5SDimitry Andric // Check to see if we already have this constant.
14720b57cec5SDimitry Andric //
14730b57cec5SDimitry Andric // FIXME, this could be made much more efficient for large constant pools.
14740b57cec5SDimitry Andric for (unsigned i = 0, e = Constants.size(); i != e; ++i)
14750b57cec5SDimitry Andric if (!Constants[i].isMachineConstantPoolEntry() &&
14760b57cec5SDimitry Andric CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
14775ffd83dbSDimitry Andric if (Constants[i].getAlign() < Alignment)
14780b57cec5SDimitry Andric Constants[i].Alignment = Alignment;
14790b57cec5SDimitry Andric return i;
14800b57cec5SDimitry Andric }
14810b57cec5SDimitry Andric
14820b57cec5SDimitry Andric Constants.push_back(MachineConstantPoolEntry(C, Alignment));
14830b57cec5SDimitry Andric return Constants.size()-1;
14840b57cec5SDimitry Andric }
14850b57cec5SDimitry Andric
getConstantPoolIndex(MachineConstantPoolValue * V,Align Alignment)14860b57cec5SDimitry Andric unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
14875ffd83dbSDimitry Andric Align Alignment) {
14880b57cec5SDimitry Andric if (Alignment > PoolAlignment) PoolAlignment = Alignment;
14890b57cec5SDimitry Andric
14900b57cec5SDimitry Andric // Check to see if we already have this constant.
14910b57cec5SDimitry Andric //
14920b57cec5SDimitry Andric // FIXME, this could be made much more efficient for large constant pools.
14930b57cec5SDimitry Andric int Idx = V->getExistingMachineCPValue(this, Alignment);
14940b57cec5SDimitry Andric if (Idx != -1) {
14950b57cec5SDimitry Andric MachineCPVsSharingEntries.insert(V);
14960b57cec5SDimitry Andric return (unsigned)Idx;
14970b57cec5SDimitry Andric }
14980b57cec5SDimitry Andric
14990b57cec5SDimitry Andric Constants.push_back(MachineConstantPoolEntry(V, Alignment));
15000b57cec5SDimitry Andric return Constants.size()-1;
15010b57cec5SDimitry Andric }
15020b57cec5SDimitry Andric
print(raw_ostream & OS) const15030b57cec5SDimitry Andric void MachineConstantPool::print(raw_ostream &OS) const {
15040b57cec5SDimitry Andric if (Constants.empty()) return;
15050b57cec5SDimitry Andric
15060b57cec5SDimitry Andric OS << "Constant Pool:\n";
15070b57cec5SDimitry Andric for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
15080b57cec5SDimitry Andric OS << " cp#" << i << ": ";
15090b57cec5SDimitry Andric if (Constants[i].isMachineConstantPoolEntry())
15100b57cec5SDimitry Andric Constants[i].Val.MachineCPVal->print(OS);
15110b57cec5SDimitry Andric else
15120b57cec5SDimitry Andric Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
15135ffd83dbSDimitry Andric OS << ", align=" << Constants[i].getAlign().value();
15140b57cec5SDimitry Andric OS << "\n";
15150b57cec5SDimitry Andric }
15160b57cec5SDimitry Andric }
15170b57cec5SDimitry Andric
1518fe013be4SDimitry Andric //===----------------------------------------------------------------------===//
1519fe013be4SDimitry Andric // Template specialization for MachineFunction implementation of
1520fe013be4SDimitry Andric // ProfileSummaryInfo::getEntryCount().
1521fe013be4SDimitry Andric //===----------------------------------------------------------------------===//
1522fe013be4SDimitry Andric template <>
1523fe013be4SDimitry Andric std::optional<Function::ProfileCount>
getEntryCount(const llvm::MachineFunction * F) const1524fe013be4SDimitry Andric ProfileSummaryInfo::getEntryCount<llvm::MachineFunction>(
1525fe013be4SDimitry Andric const llvm::MachineFunction *F) const {
1526fe013be4SDimitry Andric return F->getFunction().getEntryCount();
1527fe013be4SDimitry Andric }
1528fe013be4SDimitry Andric
15290b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
dump() const15300b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
15310b57cec5SDimitry Andric #endif
1532