1*0b57cec5SDimitry Andric //===- MachineFunction.cpp ------------------------------------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // Collect native machine code information for a function.  This allows
10*0b57cec5SDimitry Andric // target-specific information about the generated code to be stored with each
11*0b57cec5SDimitry Andric // function.
12*0b57cec5SDimitry Andric //
13*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
14*0b57cec5SDimitry Andric 
15*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/BitVector.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/DenseSet.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
21*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
22*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
23*0b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
24*0b57cec5SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
25*0b57cec5SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
26*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
27*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineConstantPool.h"
28*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
29*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
30*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineJumpTableInfo.h"
31*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
32*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
33*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
34*0b57cec5SDimitry Andric #include "llvm/CodeGen/PseudoSourceValue.h"
35*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetFrameLowering.h"
365ffd83dbSDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
37*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
38*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
39*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
40*0b57cec5SDimitry Andric #include "llvm/CodeGen/WasmEHFuncInfo.h"
41*0b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
42*0b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
43*0b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
44*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
45*0b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
46*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
47*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
48*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
49*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
50*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
51*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
52*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
53*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
54*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
55*0b57cec5SDimitry Andric #include "llvm/IR/ModuleSlotTracker.h"
56*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
57*0b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
58*0b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
59*0b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
60*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
61*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
62*0b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
63*0b57cec5SDimitry Andric #include "llvm/Support/DOTGraphTraits.h"
64*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
65*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
66*0b57cec5SDimitry Andric #include "llvm/Support/GraphWriter.h"
67*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
68*0b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
69*0b57cec5SDimitry Andric #include <algorithm>
70*0b57cec5SDimitry Andric #include <cassert>
71*0b57cec5SDimitry Andric #include <cstddef>
72*0b57cec5SDimitry Andric #include <cstdint>
73*0b57cec5SDimitry Andric #include <iterator>
74*0b57cec5SDimitry Andric #include <string>
755ffd83dbSDimitry Andric #include <type_traits>
76*0b57cec5SDimitry Andric #include <utility>
77*0b57cec5SDimitry Andric #include <vector>
78*0b57cec5SDimitry Andric 
79*0b57cec5SDimitry Andric using namespace llvm;
80*0b57cec5SDimitry Andric 
81*0b57cec5SDimitry Andric #define DEBUG_TYPE "codegen"
82*0b57cec5SDimitry Andric 
838bcb0991SDimitry Andric static cl::opt<unsigned> AlignAllFunctions(
848bcb0991SDimitry Andric     "align-all-functions",
858bcb0991SDimitry Andric     cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
868bcb0991SDimitry Andric              "means align on 16B boundaries)."),
87*0b57cec5SDimitry Andric     cl::init(0), cl::Hidden);
88*0b57cec5SDimitry Andric 
89*0b57cec5SDimitry Andric static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
90*0b57cec5SDimitry Andric   using P = MachineFunctionProperties::Property;
91*0b57cec5SDimitry Andric 
92*0b57cec5SDimitry Andric   switch(Prop) {
93*0b57cec5SDimitry Andric   case P::FailedISel: return "FailedISel";
94*0b57cec5SDimitry Andric   case P::IsSSA: return "IsSSA";
95*0b57cec5SDimitry Andric   case P::Legalized: return "Legalized";
96*0b57cec5SDimitry Andric   case P::NoPHIs: return "NoPHIs";
97*0b57cec5SDimitry Andric   case P::NoVRegs: return "NoVRegs";
98*0b57cec5SDimitry Andric   case P::RegBankSelected: return "RegBankSelected";
99*0b57cec5SDimitry Andric   case P::Selected: return "Selected";
100*0b57cec5SDimitry Andric   case P::TracksLiveness: return "TracksLiveness";
1015ffd83dbSDimitry Andric   case P::TiedOpsRewritten: return "TiedOpsRewritten";
102349cc55cSDimitry Andric   case P::FailsVerification: return "FailsVerification";
103*0b57cec5SDimitry Andric   }
104*0b57cec5SDimitry Andric   llvm_unreachable("Invalid machine function property");
105*0b57cec5SDimitry Andric }
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric // Pin the vtable to this file.
108*0b57cec5SDimitry Andric void MachineFunction::Delegate::anchor() {}
109*0b57cec5SDimitry Andric 
110*0b57cec5SDimitry Andric void MachineFunctionProperties::print(raw_ostream &OS) const {
111*0b57cec5SDimitry Andric   const char *Separator = "";
112*0b57cec5SDimitry Andric   for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
113*0b57cec5SDimitry Andric     if (!Properties[I])
114*0b57cec5SDimitry Andric       continue;
115*0b57cec5SDimitry Andric     OS << Separator << getPropertyName(static_cast<Property>(I));
116*0b57cec5SDimitry Andric     Separator = ", ";
117*0b57cec5SDimitry Andric   }
118*0b57cec5SDimitry Andric }
119*0b57cec5SDimitry Andric 
120*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
121*0b57cec5SDimitry Andric // MachineFunction implementation
122*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
123*0b57cec5SDimitry Andric 
124*0b57cec5SDimitry Andric // Out-of-line virtual method.
125*0b57cec5SDimitry Andric MachineFunctionInfo::~MachineFunctionInfo() = default;
126*0b57cec5SDimitry Andric 
127*0b57cec5SDimitry Andric void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
128*0b57cec5SDimitry Andric   MBB->getParent()->DeleteMachineBasicBlock(MBB);
129*0b57cec5SDimitry Andric }
130*0b57cec5SDimitry Andric 
131*0b57cec5SDimitry Andric static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
132*0b57cec5SDimitry Andric                                            const Function &F) {
133349cc55cSDimitry Andric   if (auto MA = F.getFnStackAlign())
134349cc55cSDimitry Andric     return MA->value();
1355ffd83dbSDimitry Andric   return STI->getFrameLowering()->getStackAlign().value();
136*0b57cec5SDimitry Andric }
137*0b57cec5SDimitry Andric 
1385ffd83dbSDimitry Andric MachineFunction::MachineFunction(Function &F, const LLVMTargetMachine &Target,
139*0b57cec5SDimitry Andric                                  const TargetSubtargetInfo &STI,
140*0b57cec5SDimitry Andric                                  unsigned FunctionNum, MachineModuleInfo &mmi)
141*0b57cec5SDimitry Andric     : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
142*0b57cec5SDimitry Andric   FunctionNumber = FunctionNum;
143*0b57cec5SDimitry Andric   init();
144*0b57cec5SDimitry Andric }
145*0b57cec5SDimitry Andric 
146*0b57cec5SDimitry Andric void MachineFunction::handleInsertion(MachineInstr &MI) {
147*0b57cec5SDimitry Andric   if (TheDelegate)
148*0b57cec5SDimitry Andric     TheDelegate->MF_HandleInsertion(MI);
149*0b57cec5SDimitry Andric }
150*0b57cec5SDimitry Andric 
151*0b57cec5SDimitry Andric void MachineFunction::handleRemoval(MachineInstr &MI) {
152*0b57cec5SDimitry Andric   if (TheDelegate)
153*0b57cec5SDimitry Andric     TheDelegate->MF_HandleRemoval(MI);
154*0b57cec5SDimitry Andric }
155*0b57cec5SDimitry Andric 
156*0b57cec5SDimitry Andric void MachineFunction::init() {
157*0b57cec5SDimitry Andric   // Assume the function starts in SSA form with correct liveness.
158*0b57cec5SDimitry Andric   Properties.set(MachineFunctionProperties::Property::IsSSA);
159*0b57cec5SDimitry Andric   Properties.set(MachineFunctionProperties::Property::TracksLiveness);
160*0b57cec5SDimitry Andric   if (STI->getRegisterInfo())
161*0b57cec5SDimitry Andric     RegInfo = new (Allocator) MachineRegisterInfo(this);
162*0b57cec5SDimitry Andric   else
163*0b57cec5SDimitry Andric     RegInfo = nullptr;
164*0b57cec5SDimitry Andric 
165*0b57cec5SDimitry Andric   MFInfo = nullptr;
166*0b57cec5SDimitry Andric   // We can realign the stack if the target supports it and the user hasn't
167*0b57cec5SDimitry Andric   // explicitly asked us not to.
168*0b57cec5SDimitry Andric   bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
169*0b57cec5SDimitry Andric                       !F.hasFnAttribute("no-realign-stack");
170*0b57cec5SDimitry Andric   FrameInfo = new (Allocator) MachineFrameInfo(
171*0b57cec5SDimitry Andric       getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
172*0b57cec5SDimitry Andric       /*ForcedRealign=*/CanRealignSP &&
173*0b57cec5SDimitry Andric           F.hasFnAttribute(Attribute::StackAlignment));
174*0b57cec5SDimitry Andric 
175*0b57cec5SDimitry Andric   if (F.hasFnAttribute(Attribute::StackAlignment))
1765ffd83dbSDimitry Andric     FrameInfo->ensureMaxAlignment(*F.getFnStackAlign());
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
179*0b57cec5SDimitry Andric   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
180*0b57cec5SDimitry Andric 
181*0b57cec5SDimitry Andric   // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
182*0b57cec5SDimitry Andric   // FIXME: Use Function::hasOptSize().
183*0b57cec5SDimitry Andric   if (!F.hasFnAttribute(Attribute::OptimizeForSize))
184*0b57cec5SDimitry Andric     Alignment = std::max(Alignment,
185*0b57cec5SDimitry Andric                          STI->getTargetLowering()->getPrefFunctionAlignment());
186*0b57cec5SDimitry Andric 
187*0b57cec5SDimitry Andric   if (AlignAllFunctions)
1888bcb0991SDimitry Andric     Alignment = Align(1ULL << AlignAllFunctions);
189*0b57cec5SDimitry Andric 
190*0b57cec5SDimitry Andric   JumpTableInfo = nullptr;
191*0b57cec5SDimitry Andric 
192*0b57cec5SDimitry Andric   if (isFuncletEHPersonality(classifyEHPersonality(
193*0b57cec5SDimitry Andric           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
194*0b57cec5SDimitry Andric     WinEHInfo = new (Allocator) WinEHFuncInfo();
195*0b57cec5SDimitry Andric   }
196*0b57cec5SDimitry Andric 
197*0b57cec5SDimitry Andric   if (isScopedEHPersonality(classifyEHPersonality(
198*0b57cec5SDimitry Andric           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
199*0b57cec5SDimitry Andric     WasmEHInfo = new (Allocator) WasmEHFuncInfo();
200*0b57cec5SDimitry Andric   }
201*0b57cec5SDimitry Andric 
202*0b57cec5SDimitry Andric   assert(Target.isCompatibleDataLayout(getDataLayout()) &&
203*0b57cec5SDimitry Andric          "Can't create a MachineFunction using a Module with a "
204*0b57cec5SDimitry Andric          "Target-incompatible DataLayout attached\n");
205*0b57cec5SDimitry Andric 
206*0b57cec5SDimitry Andric   PSVManager =
2078bcb0991SDimitry Andric     std::make_unique<PseudoSourceValueManager>(*(getSubtarget().
208*0b57cec5SDimitry Andric                                                   getInstrInfo()));
209*0b57cec5SDimitry Andric }
210*0b57cec5SDimitry Andric 
211*0b57cec5SDimitry Andric MachineFunction::~MachineFunction() {
212*0b57cec5SDimitry Andric   clear();
213*0b57cec5SDimitry Andric }
214*0b57cec5SDimitry Andric 
215*0b57cec5SDimitry Andric void MachineFunction::clear() {
216*0b57cec5SDimitry Andric   Properties.reset();
217*0b57cec5SDimitry Andric   // Don't call destructors on MachineInstr and MachineOperand. All of their
218*0b57cec5SDimitry Andric   // memory comes from the BumpPtrAllocator which is about to be purged.
219*0b57cec5SDimitry Andric   //
220*0b57cec5SDimitry Andric   // Do call MachineBasicBlock destructors, it contains std::vectors.
221*0b57cec5SDimitry Andric   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
222*0b57cec5SDimitry Andric     I->Insts.clearAndLeakNodesUnsafely();
223*0b57cec5SDimitry Andric   MBBNumbering.clear();
224*0b57cec5SDimitry Andric 
225*0b57cec5SDimitry Andric   InstructionRecycler.clear(Allocator);
226*0b57cec5SDimitry Andric   OperandRecycler.clear(Allocator);
227*0b57cec5SDimitry Andric   BasicBlockRecycler.clear(Allocator);
228*0b57cec5SDimitry Andric   CodeViewAnnotations.clear();
229*0b57cec5SDimitry Andric   VariableDbgInfos.clear();
230*0b57cec5SDimitry Andric   if (RegInfo) {
231*0b57cec5SDimitry Andric     RegInfo->~MachineRegisterInfo();
232*0b57cec5SDimitry Andric     Allocator.Deallocate(RegInfo);
233*0b57cec5SDimitry Andric   }
234*0b57cec5SDimitry Andric   if (MFInfo) {
235*0b57cec5SDimitry Andric     MFInfo->~MachineFunctionInfo();
236*0b57cec5SDimitry Andric     Allocator.Deallocate(MFInfo);
237*0b57cec5SDimitry Andric   }
238*0b57cec5SDimitry Andric 
239*0b57cec5SDimitry Andric   FrameInfo->~MachineFrameInfo();
240*0b57cec5SDimitry Andric   Allocator.Deallocate(FrameInfo);
241*0b57cec5SDimitry Andric 
242*0b57cec5SDimitry Andric   ConstantPool->~MachineConstantPool();
243*0b57cec5SDimitry Andric   Allocator.Deallocate(ConstantPool);
244*0b57cec5SDimitry Andric 
245*0b57cec5SDimitry Andric   if (JumpTableInfo) {
246*0b57cec5SDimitry Andric     JumpTableInfo->~MachineJumpTableInfo();
247*0b57cec5SDimitry Andric     Allocator.Deallocate(JumpTableInfo);
248*0b57cec5SDimitry Andric   }
249*0b57cec5SDimitry Andric 
250*0b57cec5SDimitry Andric   if (WinEHInfo) {
251*0b57cec5SDimitry Andric     WinEHInfo->~WinEHFuncInfo();
252*0b57cec5SDimitry Andric     Allocator.Deallocate(WinEHInfo);
253*0b57cec5SDimitry Andric   }
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric   if (WasmEHInfo) {
256*0b57cec5SDimitry Andric     WasmEHInfo->~WasmEHFuncInfo();
257*0b57cec5SDimitry Andric     Allocator.Deallocate(WasmEHInfo);
258*0b57cec5SDimitry Andric   }
259*0b57cec5SDimitry Andric }
260*0b57cec5SDimitry Andric 
261*0b57cec5SDimitry Andric const DataLayout &MachineFunction::getDataLayout() const {
262*0b57cec5SDimitry Andric   return F.getParent()->getDataLayout();
263*0b57cec5SDimitry Andric }
264*0b57cec5SDimitry Andric 
265*0b57cec5SDimitry Andric /// Get the JumpTableInfo for this function.
266*0b57cec5SDimitry Andric /// If it does not already exist, allocate one.
267*0b57cec5SDimitry Andric MachineJumpTableInfo *MachineFunction::
268*0b57cec5SDimitry Andric getOrCreateJumpTableInfo(unsigned EntryKind) {
269*0b57cec5SDimitry Andric   if (JumpTableInfo) return JumpTableInfo;
270*0b57cec5SDimitry Andric 
271*0b57cec5SDimitry Andric   JumpTableInfo = new (Allocator)
272*0b57cec5SDimitry Andric     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
273*0b57cec5SDimitry Andric   return JumpTableInfo;
274*0b57cec5SDimitry Andric }
275*0b57cec5SDimitry Andric 
276480093f4SDimitry Andric DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
277e8d8bef9SDimitry Andric   return F.getDenormalMode(FPType);
278480093f4SDimitry Andric }
279480093f4SDimitry Andric 
280*0b57cec5SDimitry Andric /// Should we be emitting segmented stack stuff for the function
281*0b57cec5SDimitry Andric bool MachineFunction::shouldSplitStack() const {
282*0b57cec5SDimitry Andric   return getFunction().hasFnAttribute("split-stack");
283*0b57cec5SDimitry Andric }
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric LLVM_NODISCARD unsigned
286*0b57cec5SDimitry Andric MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
287*0b57cec5SDimitry Andric   FrameInstructions.push_back(Inst);
288*0b57cec5SDimitry Andric   return FrameInstructions.size() - 1;
289*0b57cec5SDimitry Andric }
290*0b57cec5SDimitry Andric 
291*0b57cec5SDimitry Andric /// This discards all of the MachineBasicBlock numbers and recomputes them.
292*0b57cec5SDimitry Andric /// This guarantees that the MBB numbers are sequential, dense, and match the
293*0b57cec5SDimitry Andric /// ordering of the blocks within the function.  If a specific MachineBasicBlock
294*0b57cec5SDimitry Andric /// is specified, only that block and those after it are renumbered.
295*0b57cec5SDimitry Andric void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
296*0b57cec5SDimitry Andric   if (empty()) { MBBNumbering.clear(); return; }
297*0b57cec5SDimitry Andric   MachineFunction::iterator MBBI, E = end();
298*0b57cec5SDimitry Andric   if (MBB == nullptr)
299*0b57cec5SDimitry Andric     MBBI = begin();
300*0b57cec5SDimitry Andric   else
301*0b57cec5SDimitry Andric     MBBI = MBB->getIterator();
302*0b57cec5SDimitry Andric 
303*0b57cec5SDimitry Andric   // Figure out the block number this should have.
304*0b57cec5SDimitry Andric   unsigned BlockNo = 0;
305*0b57cec5SDimitry Andric   if (MBBI != begin())
306*0b57cec5SDimitry Andric     BlockNo = std::prev(MBBI)->getNumber() + 1;
307*0b57cec5SDimitry Andric 
308*0b57cec5SDimitry Andric   for (; MBBI != E; ++MBBI, ++BlockNo) {
309*0b57cec5SDimitry Andric     if (MBBI->getNumber() != (int)BlockNo) {
310*0b57cec5SDimitry Andric       // Remove use of the old number.
311*0b57cec5SDimitry Andric       if (MBBI->getNumber() != -1) {
312*0b57cec5SDimitry Andric         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
313*0b57cec5SDimitry Andric                "MBB number mismatch!");
314*0b57cec5SDimitry Andric         MBBNumbering[MBBI->getNumber()] = nullptr;
315*0b57cec5SDimitry Andric       }
316*0b57cec5SDimitry Andric 
317*0b57cec5SDimitry Andric       // If BlockNo is already taken, set that block's number to -1.
318*0b57cec5SDimitry Andric       if (MBBNumbering[BlockNo])
319*0b57cec5SDimitry Andric         MBBNumbering[BlockNo]->setNumber(-1);
320*0b57cec5SDimitry Andric 
321*0b57cec5SDimitry Andric       MBBNumbering[BlockNo] = &*MBBI;
322*0b57cec5SDimitry Andric       MBBI->setNumber(BlockNo);
323*0b57cec5SDimitry Andric     }
324*0b57cec5SDimitry Andric   }
325*0b57cec5SDimitry Andric 
326*0b57cec5SDimitry Andric   // Okay, all the blocks are renumbered.  If we have compactified the block
327*0b57cec5SDimitry Andric   // numbering, shrink MBBNumbering now.
328*0b57cec5SDimitry Andric   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
329*0b57cec5SDimitry Andric   MBBNumbering.resize(BlockNo);
330*0b57cec5SDimitry Andric }
331*0b57cec5SDimitry Andric 
3325ffd83dbSDimitry Andric /// This method iterates over the basic blocks and assigns their IsBeginSection
3335ffd83dbSDimitry Andric /// and IsEndSection fields. This must be called after MBB layout is finalized
3345ffd83dbSDimitry Andric /// and the SectionID's are assigned to MBBs.
3355ffd83dbSDimitry Andric void MachineFunction::assignBeginEndSections() {
3365ffd83dbSDimitry Andric   front().setIsBeginSection();
3375ffd83dbSDimitry Andric   auto CurrentSectionID = front().getSectionID();
3385ffd83dbSDimitry Andric   for (auto MBBI = std::next(begin()), E = end(); MBBI != E; ++MBBI) {
3395ffd83dbSDimitry Andric     if (MBBI->getSectionID() == CurrentSectionID)
3405ffd83dbSDimitry Andric       continue;
3415ffd83dbSDimitry Andric     MBBI->setIsBeginSection();
3425ffd83dbSDimitry Andric     std::prev(MBBI)->setIsEndSection();
3435ffd83dbSDimitry Andric     CurrentSectionID = MBBI->getSectionID();
3445ffd83dbSDimitry Andric   }
3455ffd83dbSDimitry Andric   back().setIsEndSection();
3465ffd83dbSDimitry Andric }
3475ffd83dbSDimitry Andric 
348*0b57cec5SDimitry Andric /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
349*0b57cec5SDimitry Andric MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
350*0b57cec5SDimitry Andric                                                   const DebugLoc &DL,
351e8d8bef9SDimitry Andric                                                   bool NoImplicit) {
352*0b57cec5SDimitry Andric   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
353e8d8bef9SDimitry Andric       MachineInstr(*this, MCID, DL, NoImplicit);
354*0b57cec5SDimitry Andric }
355*0b57cec5SDimitry Andric 
356*0b57cec5SDimitry Andric /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
357*0b57cec5SDimitry Andric /// identical in all ways except the instruction has no parent, prev, or next.
358*0b57cec5SDimitry Andric MachineInstr *
359*0b57cec5SDimitry Andric MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
360*0b57cec5SDimitry Andric   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
361*0b57cec5SDimitry Andric              MachineInstr(*this, *Orig);
362*0b57cec5SDimitry Andric }
363*0b57cec5SDimitry Andric 
364*0b57cec5SDimitry Andric MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
365*0b57cec5SDimitry Andric     MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
366*0b57cec5SDimitry Andric   MachineInstr *FirstClone = nullptr;
367*0b57cec5SDimitry Andric   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
368*0b57cec5SDimitry Andric   while (true) {
369*0b57cec5SDimitry Andric     MachineInstr *Cloned = CloneMachineInstr(&*I);
370*0b57cec5SDimitry Andric     MBB.insert(InsertBefore, Cloned);
371*0b57cec5SDimitry Andric     if (FirstClone == nullptr) {
372*0b57cec5SDimitry Andric       FirstClone = Cloned;
373*0b57cec5SDimitry Andric     } else {
374*0b57cec5SDimitry Andric       Cloned->bundleWithPred();
375*0b57cec5SDimitry Andric     }
376*0b57cec5SDimitry Andric 
377*0b57cec5SDimitry Andric     if (!I->isBundledWithSucc())
378*0b57cec5SDimitry Andric       break;
379*0b57cec5SDimitry Andric     ++I;
380*0b57cec5SDimitry Andric   }
3815ffd83dbSDimitry Andric   // Copy over call site info to the cloned instruction if needed. If Orig is in
3825ffd83dbSDimitry Andric   // a bundle, copyCallSiteInfo takes care of finding the call instruction in
3835ffd83dbSDimitry Andric   // the bundle.
3845ffd83dbSDimitry Andric   if (Orig.shouldUpdateCallSiteInfo())
3855ffd83dbSDimitry Andric     copyCallSiteInfo(&Orig, FirstClone);
386*0b57cec5SDimitry Andric   return *FirstClone;
387*0b57cec5SDimitry Andric }
388*0b57cec5SDimitry Andric 
389*0b57cec5SDimitry Andric /// Delete the given MachineInstr.
390*0b57cec5SDimitry Andric ///
391*0b57cec5SDimitry Andric /// This function also serves as the MachineInstr destructor - the real
392*0b57cec5SDimitry Andric /// ~MachineInstr() destructor must be empty.
393*0b57cec5SDimitry Andric void
394*0b57cec5SDimitry Andric MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
395*0b57cec5SDimitry Andric   // Verify that a call site info is at valid state. This assertion should
396*0b57cec5SDimitry Andric   // be triggered during the implementation of support for the
397*0b57cec5SDimitry Andric   // call site info of a new architecture. If the assertion is triggered,
398*0b57cec5SDimitry Andric   // back trace will tell where to insert a call to updateCallSiteInfo().
3995ffd83dbSDimitry Andric   assert((!MI->isCandidateForCallSiteEntry() ||
400*0b57cec5SDimitry Andric           CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
401*0b57cec5SDimitry Andric          "Call site info was not updated!");
402*0b57cec5SDimitry Andric   // Strip it for parts. The operand array and the MI object itself are
403*0b57cec5SDimitry Andric   // independently recyclable.
404*0b57cec5SDimitry Andric   if (MI->Operands)
405*0b57cec5SDimitry Andric     deallocateOperandArray(MI->CapOperands, MI->Operands);
406*0b57cec5SDimitry Andric   // Don't call ~MachineInstr() which must be trivial anyway because
407*0b57cec5SDimitry Andric   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
408*0b57cec5SDimitry Andric   // destructors.
409*0b57cec5SDimitry Andric   InstructionRecycler.Deallocate(Allocator, MI);
410*0b57cec5SDimitry Andric }
411*0b57cec5SDimitry Andric 
412*0b57cec5SDimitry Andric /// Allocate a new MachineBasicBlock. Use this instead of
413*0b57cec5SDimitry Andric /// `new MachineBasicBlock'.
414*0b57cec5SDimitry Andric MachineBasicBlock *
415*0b57cec5SDimitry Andric MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
416*0b57cec5SDimitry Andric   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
417*0b57cec5SDimitry Andric              MachineBasicBlock(*this, bb);
418*0b57cec5SDimitry Andric }
419*0b57cec5SDimitry Andric 
420*0b57cec5SDimitry Andric /// Delete the given MachineBasicBlock.
421*0b57cec5SDimitry Andric void
422*0b57cec5SDimitry Andric MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
423*0b57cec5SDimitry Andric   assert(MBB->getParent() == this && "MBB parent mismatch!");
424e8d8bef9SDimitry Andric   // Clean up any references to MBB in jump tables before deleting it.
425e8d8bef9SDimitry Andric   if (JumpTableInfo)
426e8d8bef9SDimitry Andric     JumpTableInfo->RemoveMBBFromJumpTables(MBB);
427*0b57cec5SDimitry Andric   MBB->~MachineBasicBlock();
428*0b57cec5SDimitry Andric   BasicBlockRecycler.Deallocate(Allocator, MBB);
429*0b57cec5SDimitry Andric }
430*0b57cec5SDimitry Andric 
431*0b57cec5SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
432*0b57cec5SDimitry Andric     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
4335ffd83dbSDimitry Andric     Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
434*0b57cec5SDimitry Andric     SyncScope::ID SSID, AtomicOrdering Ordering,
435*0b57cec5SDimitry Andric     AtomicOrdering FailureOrdering) {
436*0b57cec5SDimitry Andric   return new (Allocator)
437*0b57cec5SDimitry Andric       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
438*0b57cec5SDimitry Andric                         SSID, Ordering, FailureOrdering);
439*0b57cec5SDimitry Andric }
440*0b57cec5SDimitry Andric 
441e8d8bef9SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
442fe6060f1SDimitry Andric     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
443fe6060f1SDimitry Andric     Align base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
444fe6060f1SDimitry Andric     SyncScope::ID SSID, AtomicOrdering Ordering,
445fe6060f1SDimitry Andric     AtomicOrdering FailureOrdering) {
446fe6060f1SDimitry Andric   return new (Allocator)
447fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, f, MemTy, base_alignment, AAInfo, Ranges, SSID,
448fe6060f1SDimitry Andric                         Ordering, FailureOrdering);
449fe6060f1SDimitry Andric }
450fe6060f1SDimitry Andric 
451fe6060f1SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
452fe6060f1SDimitry Andric     const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, uint64_t Size) {
453fe6060f1SDimitry Andric   return new (Allocator)
454fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
455fe6060f1SDimitry Andric                         AAMDNodes(), nullptr, MMO->getSyncScopeID(),
456fe6060f1SDimitry Andric                         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
457fe6060f1SDimitry Andric }
458fe6060f1SDimitry Andric 
459fe6060f1SDimitry Andric MachineMemOperand *MachineFunction::getMachineMemOperand(
460fe6060f1SDimitry Andric     const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
461fe6060f1SDimitry Andric   return new (Allocator)
462fe6060f1SDimitry Andric       MachineMemOperand(PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
463fe6060f1SDimitry Andric                         AAMDNodes(), nullptr, MMO->getSyncScopeID(),
464fe6060f1SDimitry Andric                         MMO->getSuccessOrdering(), MMO->getFailureOrdering());
465e8d8bef9SDimitry Andric }
466e8d8bef9SDimitry Andric 
467*0b57cec5SDimitry Andric MachineMemOperand *
468*0b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
469fe6060f1SDimitry Andric                                       int64_t Offset, LLT Ty) {
470*0b57cec5SDimitry Andric   const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
471*0b57cec5SDimitry Andric 
472*0b57cec5SDimitry Andric   // If there is no pointer value, the offset isn't tracked so we need to adjust
473*0b57cec5SDimitry Andric   // the base alignment.
4745ffd83dbSDimitry Andric   Align Alignment = PtrInfo.V.isNull()
4755ffd83dbSDimitry Andric                         ? commonAlignment(MMO->getBaseAlign(), Offset)
4765ffd83dbSDimitry Andric                         : MMO->getBaseAlign();
477*0b57cec5SDimitry Andric 
478e8d8bef9SDimitry Andric   // Do not preserve ranges, since we don't necessarily know what the high bits
479e8d8bef9SDimitry Andric   // are anymore.
480fe6060f1SDimitry Andric   return new (Allocator) MachineMemOperand(
481fe6060f1SDimitry Andric       PtrInfo.getWithOffset(Offset), MMO->getFlags(), Ty, Alignment,
482fe6060f1SDimitry Andric       MMO->getAAInfo(), nullptr, MMO->getSyncScopeID(),
483fe6060f1SDimitry Andric       MMO->getSuccessOrdering(), MMO->getFailureOrdering());
484*0b57cec5SDimitry Andric }
485*0b57cec5SDimitry Andric 
486*0b57cec5SDimitry Andric MachineMemOperand *
487*0b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
488*0b57cec5SDimitry Andric                                       const AAMDNodes &AAInfo) {
489*0b57cec5SDimitry Andric   MachinePointerInfo MPI = MMO->getValue() ?
490*0b57cec5SDimitry Andric              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
491*0b57cec5SDimitry Andric              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
492*0b57cec5SDimitry Andric 
4935ffd83dbSDimitry Andric   return new (Allocator) MachineMemOperand(
4945ffd83dbSDimitry Andric       MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(), AAInfo,
495fe6060f1SDimitry Andric       MMO->getRanges(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
4965ffd83dbSDimitry Andric       MMO->getFailureOrdering());
497*0b57cec5SDimitry Andric }
498*0b57cec5SDimitry Andric 
499*0b57cec5SDimitry Andric MachineMemOperand *
500*0b57cec5SDimitry Andric MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
501*0b57cec5SDimitry Andric                                       MachineMemOperand::Flags Flags) {
502*0b57cec5SDimitry Andric   return new (Allocator) MachineMemOperand(
5035ffd83dbSDimitry Andric       MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
504*0b57cec5SDimitry Andric       MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
505fe6060f1SDimitry Andric       MMO->getSuccessOrdering(), MMO->getFailureOrdering());
506*0b57cec5SDimitry Andric }
507*0b57cec5SDimitry Andric 
508480093f4SDimitry Andric MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
509c14a5a88SDimitry Andric     ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
510c14a5a88SDimitry Andric     MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) {
511c14a5a88SDimitry Andric   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
512c14a5a88SDimitry Andric                                          PostInstrSymbol, HeapAllocMarker);
513*0b57cec5SDimitry Andric }
514*0b57cec5SDimitry Andric 
515*0b57cec5SDimitry Andric const char *MachineFunction::createExternalSymbolName(StringRef Name) {
516*0b57cec5SDimitry Andric   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
517*0b57cec5SDimitry Andric   llvm::copy(Name, Dest);
518*0b57cec5SDimitry Andric   Dest[Name.size()] = 0;
519*0b57cec5SDimitry Andric   return Dest;
520*0b57cec5SDimitry Andric }
521*0b57cec5SDimitry Andric 
522*0b57cec5SDimitry Andric uint32_t *MachineFunction::allocateRegMask() {
523*0b57cec5SDimitry Andric   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
524*0b57cec5SDimitry Andric   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
525*0b57cec5SDimitry Andric   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
526*0b57cec5SDimitry Andric   memset(Mask, 0, Size * sizeof(Mask[0]));
527*0b57cec5SDimitry Andric   return Mask;
528*0b57cec5SDimitry Andric }
529*0b57cec5SDimitry Andric 
530480093f4SDimitry Andric ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
531480093f4SDimitry Andric   int* AllocMask = Allocator.Allocate<int>(Mask.size());
532480093f4SDimitry Andric   copy(Mask, AllocMask);
533480093f4SDimitry Andric   return {AllocMask, Mask.size()};
534480093f4SDimitry Andric }
535480093f4SDimitry Andric 
536*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
537*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineFunction::dump() const {
538*0b57cec5SDimitry Andric   print(dbgs());
539*0b57cec5SDimitry Andric }
540*0b57cec5SDimitry Andric #endif
541*0b57cec5SDimitry Andric 
542*0b57cec5SDimitry Andric StringRef MachineFunction::getName() const {
543*0b57cec5SDimitry Andric   return getFunction().getName();
544*0b57cec5SDimitry Andric }
545*0b57cec5SDimitry Andric 
546*0b57cec5SDimitry Andric void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
547*0b57cec5SDimitry Andric   OS << "# Machine code for function " << getName() << ": ";
548*0b57cec5SDimitry Andric   getProperties().print(OS);
549*0b57cec5SDimitry Andric   OS << '\n';
550*0b57cec5SDimitry Andric 
551*0b57cec5SDimitry Andric   // Print Frame Information
552*0b57cec5SDimitry Andric   FrameInfo->print(*this, OS);
553*0b57cec5SDimitry Andric 
554*0b57cec5SDimitry Andric   // Print JumpTable Information
555*0b57cec5SDimitry Andric   if (JumpTableInfo)
556*0b57cec5SDimitry Andric     JumpTableInfo->print(OS);
557*0b57cec5SDimitry Andric 
558*0b57cec5SDimitry Andric   // Print Constant Pool
559*0b57cec5SDimitry Andric   ConstantPool->print(OS);
560*0b57cec5SDimitry Andric 
561*0b57cec5SDimitry Andric   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
562*0b57cec5SDimitry Andric 
563*0b57cec5SDimitry Andric   if (RegInfo && !RegInfo->livein_empty()) {
564*0b57cec5SDimitry Andric     OS << "Function Live Ins: ";
565*0b57cec5SDimitry Andric     for (MachineRegisterInfo::livein_iterator
566*0b57cec5SDimitry Andric          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
567*0b57cec5SDimitry Andric       OS << printReg(I->first, TRI);
568*0b57cec5SDimitry Andric       if (I->second)
569*0b57cec5SDimitry Andric         OS << " in " << printReg(I->second, TRI);
570*0b57cec5SDimitry Andric       if (std::next(I) != E)
571*0b57cec5SDimitry Andric         OS << ", ";
572*0b57cec5SDimitry Andric     }
573*0b57cec5SDimitry Andric     OS << '\n';
574*0b57cec5SDimitry Andric   }
575*0b57cec5SDimitry Andric 
576*0b57cec5SDimitry Andric   ModuleSlotTracker MST(getFunction().getParent());
577*0b57cec5SDimitry Andric   MST.incorporateFunction(getFunction());
578*0b57cec5SDimitry Andric   for (const auto &BB : *this) {
579*0b57cec5SDimitry Andric     OS << '\n';
580*0b57cec5SDimitry Andric     // If we print the whole function, print it at its most verbose level.
581*0b57cec5SDimitry Andric     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
582*0b57cec5SDimitry Andric   }
583*0b57cec5SDimitry Andric 
584*0b57cec5SDimitry Andric   OS << "\n# End machine code for function " << getName() << ".\n\n";
585*0b57cec5SDimitry Andric }
586*0b57cec5SDimitry Andric 
587480093f4SDimitry Andric /// True if this function needs frame moves for debug or exceptions.
588480093f4SDimitry Andric bool MachineFunction::needsFrameMoves() const {
589480093f4SDimitry Andric   return getMMI().hasDebugInfo() ||
590480093f4SDimitry Andric          getTarget().Options.ForceDwarfFrameSection ||
591480093f4SDimitry Andric          F.needsUnwindTableEntry();
592480093f4SDimitry Andric }
593480093f4SDimitry Andric 
594*0b57cec5SDimitry Andric namespace llvm {
595*0b57cec5SDimitry Andric 
596*0b57cec5SDimitry Andric   template<>
597*0b57cec5SDimitry Andric   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
598*0b57cec5SDimitry Andric     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
599*0b57cec5SDimitry Andric 
600*0b57cec5SDimitry Andric     static std::string getGraphName(const MachineFunction *F) {
601*0b57cec5SDimitry Andric       return ("CFG for '" + F->getName() + "' function").str();
602*0b57cec5SDimitry Andric     }
603*0b57cec5SDimitry Andric 
604*0b57cec5SDimitry Andric     std::string getNodeLabel(const MachineBasicBlock *Node,
605*0b57cec5SDimitry Andric                              const MachineFunction *Graph) {
606*0b57cec5SDimitry Andric       std::string OutStr;
607*0b57cec5SDimitry Andric       {
608*0b57cec5SDimitry Andric         raw_string_ostream OSS(OutStr);
609*0b57cec5SDimitry Andric 
610*0b57cec5SDimitry Andric         if (isSimple()) {
611*0b57cec5SDimitry Andric           OSS << printMBBReference(*Node);
612*0b57cec5SDimitry Andric           if (const BasicBlock *BB = Node->getBasicBlock())
613*0b57cec5SDimitry Andric             OSS << ": " << BB->getName();
614*0b57cec5SDimitry Andric         } else
615*0b57cec5SDimitry Andric           Node->print(OSS);
616*0b57cec5SDimitry Andric       }
617*0b57cec5SDimitry Andric 
618*0b57cec5SDimitry Andric       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
619*0b57cec5SDimitry Andric 
620*0b57cec5SDimitry Andric       // Process string output to make it nicer...
621*0b57cec5SDimitry Andric       for (unsigned i = 0; i != OutStr.length(); ++i)
622*0b57cec5SDimitry Andric         if (OutStr[i] == '\n') {                            // Left justify
623*0b57cec5SDimitry Andric           OutStr[i] = '\\';
624*0b57cec5SDimitry Andric           OutStr.insert(OutStr.begin()+i+1, 'l');
625*0b57cec5SDimitry Andric         }
626*0b57cec5SDimitry Andric       return OutStr;
627*0b57cec5SDimitry Andric     }
628*0b57cec5SDimitry Andric   };
629*0b57cec5SDimitry Andric 
630*0b57cec5SDimitry Andric } // end namespace llvm
631*0b57cec5SDimitry Andric 
632*0b57cec5SDimitry Andric void MachineFunction::viewCFG() const
633*0b57cec5SDimitry Andric {
634*0b57cec5SDimitry Andric #ifndef NDEBUG
635*0b57cec5SDimitry Andric   ViewGraph(this, "mf" + getName());
636*0b57cec5SDimitry Andric #else
637*0b57cec5SDimitry Andric   errs() << "MachineFunction::viewCFG is only available in debug builds on "
638*0b57cec5SDimitry Andric          << "systems with Graphviz or gv!\n";
639*0b57cec5SDimitry Andric #endif // NDEBUG
640*0b57cec5SDimitry Andric }
641*0b57cec5SDimitry Andric 
642*0b57cec5SDimitry Andric void MachineFunction::viewCFGOnly() const
643*0b57cec5SDimitry Andric {
644*0b57cec5SDimitry Andric #ifndef NDEBUG
645*0b57cec5SDimitry Andric   ViewGraph(this, "mf" + getName(), true);
646*0b57cec5SDimitry Andric #else
647*0b57cec5SDimitry Andric   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
648*0b57cec5SDimitry Andric          << "systems with Graphviz or gv!\n";
649*0b57cec5SDimitry Andric #endif // NDEBUG
650*0b57cec5SDimitry Andric }
651*0b57cec5SDimitry Andric 
652*0b57cec5SDimitry Andric /// Add the specified physical register as a live-in value and
653*0b57cec5SDimitry Andric /// create a corresponding virtual register for it.
6545ffd83dbSDimitry Andric Register MachineFunction::addLiveIn(MCRegister PReg,
655*0b57cec5SDimitry Andric                                     const TargetRegisterClass *RC) {
656*0b57cec5SDimitry Andric   MachineRegisterInfo &MRI = getRegInfo();
6575ffd83dbSDimitry Andric   Register VReg = MRI.getLiveInVirtReg(PReg);
658*0b57cec5SDimitry Andric   if (VReg) {
659*0b57cec5SDimitry Andric     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
660*0b57cec5SDimitry Andric     (void)VRegRC;
661*0b57cec5SDimitry Andric     // A physical register can be added several times.
662*0b57cec5SDimitry Andric     // Between two calls, the register class of the related virtual register
663*0b57cec5SDimitry Andric     // may have been constrained to match some operation constraints.
664*0b57cec5SDimitry Andric     // In that case, check that the current register class includes the
665*0b57cec5SDimitry Andric     // physical register and is a sub class of the specified RC.
666*0b57cec5SDimitry Andric     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
667*0b57cec5SDimitry Andric                              RC->hasSubClassEq(VRegRC))) &&
668*0b57cec5SDimitry Andric             "Register class mismatch!");
669*0b57cec5SDimitry Andric     return VReg;
670*0b57cec5SDimitry Andric   }
671*0b57cec5SDimitry Andric   VReg = MRI.createVirtualRegister(RC);
672*0b57cec5SDimitry Andric   MRI.addLiveIn(PReg, VReg);
673*0b57cec5SDimitry Andric   return VReg;
674*0b57cec5SDimitry Andric }
675*0b57cec5SDimitry Andric 
676*0b57cec5SDimitry Andric /// Return the MCSymbol for the specified non-empty jump table.
677*0b57cec5SDimitry Andric /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
678*0b57cec5SDimitry Andric /// normal 'L' label is returned.
679*0b57cec5SDimitry Andric MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
680*0b57cec5SDimitry Andric                                         bool isLinkerPrivate) const {
681*0b57cec5SDimitry Andric   const DataLayout &DL = getDataLayout();
682*0b57cec5SDimitry Andric   assert(JumpTableInfo && "No jump tables");
683*0b57cec5SDimitry Andric   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
684*0b57cec5SDimitry Andric 
685*0b57cec5SDimitry Andric   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
686*0b57cec5SDimitry Andric                                      : DL.getPrivateGlobalPrefix();
687*0b57cec5SDimitry Andric   SmallString<60> Name;
688*0b57cec5SDimitry Andric   raw_svector_ostream(Name)
689*0b57cec5SDimitry Andric     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
690*0b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol(Name);
691*0b57cec5SDimitry Andric }
692*0b57cec5SDimitry Andric 
693*0b57cec5SDimitry Andric /// Return a function-local symbol to represent the PIC base.
694*0b57cec5SDimitry Andric MCSymbol *MachineFunction::getPICBaseSymbol() const {
695*0b57cec5SDimitry Andric   const DataLayout &DL = getDataLayout();
696*0b57cec5SDimitry Andric   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
697*0b57cec5SDimitry Andric                                Twine(getFunctionNumber()) + "$pb");
698*0b57cec5SDimitry Andric }
699*0b57cec5SDimitry Andric 
700*0b57cec5SDimitry Andric /// \name Exception Handling
701*0b57cec5SDimitry Andric /// \{
702*0b57cec5SDimitry Andric 
703*0b57cec5SDimitry Andric LandingPadInfo &
704*0b57cec5SDimitry Andric MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
705*0b57cec5SDimitry Andric   unsigned N = LandingPads.size();
706*0b57cec5SDimitry Andric   for (unsigned i = 0; i < N; ++i) {
707*0b57cec5SDimitry Andric     LandingPadInfo &LP = LandingPads[i];
708*0b57cec5SDimitry Andric     if (LP.LandingPadBlock == LandingPad)
709*0b57cec5SDimitry Andric       return LP;
710*0b57cec5SDimitry Andric   }
711*0b57cec5SDimitry Andric 
712*0b57cec5SDimitry Andric   LandingPads.push_back(LandingPadInfo(LandingPad));
713*0b57cec5SDimitry Andric   return LandingPads[N];
714*0b57cec5SDimitry Andric }
715*0b57cec5SDimitry Andric 
716*0b57cec5SDimitry Andric void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
717*0b57cec5SDimitry Andric                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
718*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
719*0b57cec5SDimitry Andric   LP.BeginLabels.push_back(BeginLabel);
720*0b57cec5SDimitry Andric   LP.EndLabels.push_back(EndLabel);
721*0b57cec5SDimitry Andric }
722*0b57cec5SDimitry Andric 
723*0b57cec5SDimitry Andric MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
724*0b57cec5SDimitry Andric   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
725*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
726*0b57cec5SDimitry Andric   LP.LandingPadLabel = LandingPadLabel;
727*0b57cec5SDimitry Andric 
728*0b57cec5SDimitry Andric   const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
729*0b57cec5SDimitry Andric   if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
730*0b57cec5SDimitry Andric     if (const auto *PF =
731*0b57cec5SDimitry Andric             dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
732*0b57cec5SDimitry Andric       getMMI().addPersonality(PF);
733*0b57cec5SDimitry Andric 
734*0b57cec5SDimitry Andric     if (LPI->isCleanup())
735*0b57cec5SDimitry Andric       addCleanup(LandingPad);
736*0b57cec5SDimitry Andric 
737*0b57cec5SDimitry Andric     // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
738*0b57cec5SDimitry Andric     //        correct, but we need to do it this way because of how the DWARF EH
739*0b57cec5SDimitry Andric     //        emitter processes the clauses.
740*0b57cec5SDimitry Andric     for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
741*0b57cec5SDimitry Andric       Value *Val = LPI->getClause(I - 1);
742*0b57cec5SDimitry Andric       if (LPI->isCatch(I - 1)) {
743*0b57cec5SDimitry Andric         addCatchTypeInfo(LandingPad,
744*0b57cec5SDimitry Andric                          dyn_cast<GlobalValue>(Val->stripPointerCasts()));
745*0b57cec5SDimitry Andric       } else {
746*0b57cec5SDimitry Andric         // Add filters in a list.
747*0b57cec5SDimitry Andric         auto *CVal = cast<Constant>(Val);
748*0b57cec5SDimitry Andric         SmallVector<const GlobalValue *, 4> FilterList;
749349cc55cSDimitry Andric         for (const Use &U : CVal->operands())
750349cc55cSDimitry Andric           FilterList.push_back(cast<GlobalValue>(U->stripPointerCasts()));
751*0b57cec5SDimitry Andric 
752*0b57cec5SDimitry Andric         addFilterTypeInfo(LandingPad, FilterList);
753*0b57cec5SDimitry Andric       }
754*0b57cec5SDimitry Andric     }
755*0b57cec5SDimitry Andric 
756*0b57cec5SDimitry Andric   } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
757*0b57cec5SDimitry Andric     for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
758*0b57cec5SDimitry Andric       Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
759*0b57cec5SDimitry Andric       addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
760*0b57cec5SDimitry Andric     }
761*0b57cec5SDimitry Andric 
762*0b57cec5SDimitry Andric   } else {
763*0b57cec5SDimitry Andric     assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
764*0b57cec5SDimitry Andric   }
765*0b57cec5SDimitry Andric 
766*0b57cec5SDimitry Andric   return LandingPadLabel;
767*0b57cec5SDimitry Andric }
768*0b57cec5SDimitry Andric 
769*0b57cec5SDimitry Andric void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
770*0b57cec5SDimitry Andric                                        ArrayRef<const GlobalValue *> TyInfo) {
771*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
772*0b57cec5SDimitry Andric   for (unsigned N = TyInfo.size(); N; --N)
773*0b57cec5SDimitry Andric     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
774*0b57cec5SDimitry Andric }
775*0b57cec5SDimitry Andric 
776*0b57cec5SDimitry Andric void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
777*0b57cec5SDimitry Andric                                         ArrayRef<const GlobalValue *> TyInfo) {
778*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
779*0b57cec5SDimitry Andric   std::vector<unsigned> IdsInFilter(TyInfo.size());
780*0b57cec5SDimitry Andric   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
781*0b57cec5SDimitry Andric     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
782*0b57cec5SDimitry Andric   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
783*0b57cec5SDimitry Andric }
784*0b57cec5SDimitry Andric 
785*0b57cec5SDimitry Andric void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
786*0b57cec5SDimitry Andric                                       bool TidyIfNoBeginLabels) {
787*0b57cec5SDimitry Andric   for (unsigned i = 0; i != LandingPads.size(); ) {
788*0b57cec5SDimitry Andric     LandingPadInfo &LandingPad = LandingPads[i];
789*0b57cec5SDimitry Andric     if (LandingPad.LandingPadLabel &&
790*0b57cec5SDimitry Andric         !LandingPad.LandingPadLabel->isDefined() &&
791*0b57cec5SDimitry Andric         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
792*0b57cec5SDimitry Andric       LandingPad.LandingPadLabel = nullptr;
793*0b57cec5SDimitry Andric 
794*0b57cec5SDimitry Andric     // Special case: we *should* emit LPs with null LP MBB. This indicates
795*0b57cec5SDimitry Andric     // "nounwind" case.
796*0b57cec5SDimitry Andric     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
797*0b57cec5SDimitry Andric       LandingPads.erase(LandingPads.begin() + i);
798*0b57cec5SDimitry Andric       continue;
799*0b57cec5SDimitry Andric     }
800*0b57cec5SDimitry Andric 
801*0b57cec5SDimitry Andric     if (TidyIfNoBeginLabels) {
802*0b57cec5SDimitry Andric       for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
803*0b57cec5SDimitry Andric         MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
804*0b57cec5SDimitry Andric         MCSymbol *EndLabel = LandingPad.EndLabels[j];
805*0b57cec5SDimitry Andric         if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
806*0b57cec5SDimitry Andric             (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
807*0b57cec5SDimitry Andric           continue;
808*0b57cec5SDimitry Andric 
809*0b57cec5SDimitry Andric         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
810*0b57cec5SDimitry Andric         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
811*0b57cec5SDimitry Andric         --j;
812*0b57cec5SDimitry Andric         --e;
813*0b57cec5SDimitry Andric       }
814*0b57cec5SDimitry Andric 
815*0b57cec5SDimitry Andric       // Remove landing pads with no try-ranges.
816*0b57cec5SDimitry Andric       if (LandingPads[i].BeginLabels.empty()) {
817*0b57cec5SDimitry Andric         LandingPads.erase(LandingPads.begin() + i);
818*0b57cec5SDimitry Andric         continue;
819*0b57cec5SDimitry Andric       }
820*0b57cec5SDimitry Andric     }
821*0b57cec5SDimitry Andric 
822*0b57cec5SDimitry Andric     // If there is no landing pad, ensure that the list of typeids is empty.
823*0b57cec5SDimitry Andric     // If the only typeid is a cleanup, this is the same as having no typeids.
824*0b57cec5SDimitry Andric     if (!LandingPad.LandingPadBlock ||
825*0b57cec5SDimitry Andric         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
826*0b57cec5SDimitry Andric       LandingPad.TypeIds.clear();
827*0b57cec5SDimitry Andric     ++i;
828*0b57cec5SDimitry Andric   }
829*0b57cec5SDimitry Andric }
830*0b57cec5SDimitry Andric 
831*0b57cec5SDimitry Andric void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
832*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
833*0b57cec5SDimitry Andric   LP.TypeIds.push_back(0);
834*0b57cec5SDimitry Andric }
835*0b57cec5SDimitry Andric 
836*0b57cec5SDimitry Andric void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
837*0b57cec5SDimitry Andric                                          const Function *Filter,
838*0b57cec5SDimitry Andric                                          const BlockAddress *RecoverBA) {
839*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
840*0b57cec5SDimitry Andric   SEHHandler Handler;
841*0b57cec5SDimitry Andric   Handler.FilterOrFinally = Filter;
842*0b57cec5SDimitry Andric   Handler.RecoverBA = RecoverBA;
843*0b57cec5SDimitry Andric   LP.SEHHandlers.push_back(Handler);
844*0b57cec5SDimitry Andric }
845*0b57cec5SDimitry Andric 
846*0b57cec5SDimitry Andric void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
847*0b57cec5SDimitry Andric                                            const Function *Cleanup) {
848*0b57cec5SDimitry Andric   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
849*0b57cec5SDimitry Andric   SEHHandler Handler;
850*0b57cec5SDimitry Andric   Handler.FilterOrFinally = Cleanup;
851*0b57cec5SDimitry Andric   Handler.RecoverBA = nullptr;
852*0b57cec5SDimitry Andric   LP.SEHHandlers.push_back(Handler);
853*0b57cec5SDimitry Andric }
854*0b57cec5SDimitry Andric 
855*0b57cec5SDimitry Andric void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
856*0b57cec5SDimitry Andric                                             ArrayRef<unsigned> Sites) {
857*0b57cec5SDimitry Andric   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
858*0b57cec5SDimitry Andric }
859*0b57cec5SDimitry Andric 
860*0b57cec5SDimitry Andric unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
861*0b57cec5SDimitry Andric   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
862*0b57cec5SDimitry Andric     if (TypeInfos[i] == TI) return i + 1;
863*0b57cec5SDimitry Andric 
864*0b57cec5SDimitry Andric   TypeInfos.push_back(TI);
865*0b57cec5SDimitry Andric   return TypeInfos.size();
866*0b57cec5SDimitry Andric }
867*0b57cec5SDimitry Andric 
868*0b57cec5SDimitry Andric int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
869*0b57cec5SDimitry Andric   // If the new filter coincides with the tail of an existing filter, then
870*0b57cec5SDimitry Andric   // re-use the existing filter.  Folding filters more than this requires
871*0b57cec5SDimitry Andric   // re-ordering filters and/or their elements - probably not worth it.
872fe6060f1SDimitry Andric   for (unsigned i : FilterEnds) {
873fe6060f1SDimitry Andric     unsigned j = TyIds.size();
874*0b57cec5SDimitry Andric 
875*0b57cec5SDimitry Andric     while (i && j)
876*0b57cec5SDimitry Andric       if (FilterIds[--i] != TyIds[--j])
877*0b57cec5SDimitry Andric         goto try_next;
878*0b57cec5SDimitry Andric 
879*0b57cec5SDimitry Andric     if (!j)
880*0b57cec5SDimitry Andric       // The new filter coincides with range [i, end) of the existing filter.
881*0b57cec5SDimitry Andric       return -(1 + i);
882*0b57cec5SDimitry Andric 
883*0b57cec5SDimitry Andric try_next:;
884*0b57cec5SDimitry Andric   }
885*0b57cec5SDimitry Andric 
886*0b57cec5SDimitry Andric   // Add the new filter.
887*0b57cec5SDimitry Andric   int FilterID = -(1 + FilterIds.size());
888*0b57cec5SDimitry Andric   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
889e8d8bef9SDimitry Andric   llvm::append_range(FilterIds, TyIds);
890*0b57cec5SDimitry Andric   FilterEnds.push_back(FilterIds.size());
891*0b57cec5SDimitry Andric   FilterIds.push_back(0); // terminator
892*0b57cec5SDimitry Andric   return FilterID;
893*0b57cec5SDimitry Andric }
894*0b57cec5SDimitry Andric 
895480093f4SDimitry Andric MachineFunction::CallSiteInfoMap::iterator
896480093f4SDimitry Andric MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
8975ffd83dbSDimitry Andric   assert(MI->isCandidateForCallSiteEntry() &&
8985ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates");
899*0b57cec5SDimitry Andric 
9005ffd83dbSDimitry Andric   if (!Target.Options.EmitCallSiteInfo)
901480093f4SDimitry Andric     return CallSitesInfo.end();
902480093f4SDimitry Andric   return CallSitesInfo.find(MI);
903*0b57cec5SDimitry Andric }
904*0b57cec5SDimitry Andric 
9055ffd83dbSDimitry Andric /// Return the call machine instruction or find a call within bundle.
9065ffd83dbSDimitry Andric static const MachineInstr *getCallInstr(const MachineInstr *MI) {
9075ffd83dbSDimitry Andric   if (!MI->isBundle())
9085ffd83dbSDimitry Andric     return MI;
909*0b57cec5SDimitry Andric 
9105ffd83dbSDimitry Andric   for (auto &BMI : make_range(getBundleStart(MI->getIterator()),
9115ffd83dbSDimitry Andric                               getBundleEnd(MI->getIterator())))
9125ffd83dbSDimitry Andric     if (BMI.isCandidateForCallSiteEntry())
9135ffd83dbSDimitry Andric       return &BMI;
9148bcb0991SDimitry Andric 
9155ffd83dbSDimitry Andric   llvm_unreachable("Unexpected bundle without a call site candidate");
9168bcb0991SDimitry Andric }
9178bcb0991SDimitry Andric 
9188bcb0991SDimitry Andric void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
9195ffd83dbSDimitry Andric   assert(MI->shouldUpdateCallSiteInfo() &&
9205ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
9215ffd83dbSDimitry Andric          "candidates inside bundles");
9225ffd83dbSDimitry Andric 
9235ffd83dbSDimitry Andric   const MachineInstr *CallMI = getCallInstr(MI);
9245ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
9258bcb0991SDimitry Andric   if (CSIt == CallSitesInfo.end())
9268bcb0991SDimitry Andric     return;
9278bcb0991SDimitry Andric   CallSitesInfo.erase(CSIt);
9288bcb0991SDimitry Andric }
9298bcb0991SDimitry Andric 
9308bcb0991SDimitry Andric void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
9318bcb0991SDimitry Andric                                        const MachineInstr *New) {
9325ffd83dbSDimitry Andric   assert(Old->shouldUpdateCallSiteInfo() &&
9335ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
9345ffd83dbSDimitry Andric          "candidates inside bundles");
9358bcb0991SDimitry Andric 
9365ffd83dbSDimitry Andric   if (!New->isCandidateForCallSiteEntry())
9375ffd83dbSDimitry Andric     return eraseCallSiteInfo(Old);
9385ffd83dbSDimitry Andric 
9395ffd83dbSDimitry Andric   const MachineInstr *OldCallMI = getCallInstr(Old);
9405ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9418bcb0991SDimitry Andric   if (CSIt == CallSitesInfo.end())
9428bcb0991SDimitry Andric     return;
9438bcb0991SDimitry Andric 
9448bcb0991SDimitry Andric   CallSiteInfo CSInfo = CSIt->second;
945*0b57cec5SDimitry Andric   CallSitesInfo[New] = CSInfo;
946*0b57cec5SDimitry Andric }
947*0b57cec5SDimitry Andric 
9485ffd83dbSDimitry Andric void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
9495ffd83dbSDimitry Andric                                        const MachineInstr *New) {
9505ffd83dbSDimitry Andric   assert(Old->shouldUpdateCallSiteInfo() &&
9515ffd83dbSDimitry Andric          "Call site info refers only to call (MI) candidates or "
9525ffd83dbSDimitry Andric          "candidates inside bundles");
9535ffd83dbSDimitry Andric 
9545ffd83dbSDimitry Andric   if (!New->isCandidateForCallSiteEntry())
9555ffd83dbSDimitry Andric     return eraseCallSiteInfo(Old);
9565ffd83dbSDimitry Andric 
9575ffd83dbSDimitry Andric   const MachineInstr *OldCallMI = getCallInstr(Old);
9585ffd83dbSDimitry Andric   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
9595ffd83dbSDimitry Andric   if (CSIt == CallSitesInfo.end())
9605ffd83dbSDimitry Andric     return;
9615ffd83dbSDimitry Andric 
9625ffd83dbSDimitry Andric   CallSiteInfo CSInfo = std::move(CSIt->second);
9635ffd83dbSDimitry Andric   CallSitesInfo.erase(CSIt);
9645ffd83dbSDimitry Andric   CallSitesInfo[New] = CSInfo;
9655ffd83dbSDimitry Andric }
9665ffd83dbSDimitry Andric 
967e8d8bef9SDimitry Andric void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
968e8d8bef9SDimitry Andric   DebugInstrNumberingCount = Num;
969e8d8bef9SDimitry Andric }
970e8d8bef9SDimitry Andric 
971e8d8bef9SDimitry Andric void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
972fe6060f1SDimitry Andric                                                  DebugInstrOperandPair B,
973fe6060f1SDimitry Andric                                                  unsigned Subreg) {
974fe6060f1SDimitry Andric   // Catch any accidental self-loops.
975fe6060f1SDimitry Andric   assert(A.first != B.first);
976349cc55cSDimitry Andric   // Don't allow any substitutions _from_ the memory operand number.
977349cc55cSDimitry Andric   assert(A.second != DebugOperandMemNumber);
978349cc55cSDimitry Andric 
979fe6060f1SDimitry Andric   DebugValueSubstitutions.push_back({A, B, Subreg});
980e8d8bef9SDimitry Andric }
981e8d8bef9SDimitry Andric 
982e8d8bef9SDimitry Andric void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
983e8d8bef9SDimitry Andric                                                    MachineInstr &New,
984e8d8bef9SDimitry Andric                                                    unsigned MaxOperand) {
985e8d8bef9SDimitry Andric   // If the Old instruction wasn't tracked at all, there is no work to do.
986e8d8bef9SDimitry Andric   unsigned OldInstrNum = Old.peekDebugInstrNum();
987e8d8bef9SDimitry Andric   if (!OldInstrNum)
988e8d8bef9SDimitry Andric     return;
989e8d8bef9SDimitry Andric 
990e8d8bef9SDimitry Andric   // Iterate over all operands looking for defs to create substitutions for.
991e8d8bef9SDimitry Andric   // Avoid creating new instr numbers unless we create a new substitution.
992e8d8bef9SDimitry Andric   // While this has no functional effect, it risks confusing someone reading
993e8d8bef9SDimitry Andric   // MIR output.
994e8d8bef9SDimitry Andric   // Examine all the operands, or the first N specified by the caller.
995e8d8bef9SDimitry Andric   MaxOperand = std::min(MaxOperand, Old.getNumOperands());
996fe6060f1SDimitry Andric   for (unsigned int I = 0; I < MaxOperand; ++I) {
997e8d8bef9SDimitry Andric     const auto &OldMO = Old.getOperand(I);
998e8d8bef9SDimitry Andric     auto &NewMO = New.getOperand(I);
999e8d8bef9SDimitry Andric     (void)NewMO;
1000e8d8bef9SDimitry Andric 
1001e8d8bef9SDimitry Andric     if (!OldMO.isReg() || !OldMO.isDef())
1002e8d8bef9SDimitry Andric       continue;
1003e8d8bef9SDimitry Andric     assert(NewMO.isDef());
1004e8d8bef9SDimitry Andric 
1005e8d8bef9SDimitry Andric     unsigned NewInstrNum = New.getDebugInstrNum();
1006e8d8bef9SDimitry Andric     makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
1007e8d8bef9SDimitry Andric                                std::make_pair(NewInstrNum, I));
1008e8d8bef9SDimitry Andric   }
1009e8d8bef9SDimitry Andric }
1010e8d8bef9SDimitry Andric 
1011fe6060f1SDimitry Andric auto MachineFunction::salvageCopySSA(MachineInstr &MI)
1012fe6060f1SDimitry Andric     -> DebugInstrOperandPair {
1013fe6060f1SDimitry Andric   MachineRegisterInfo &MRI = getRegInfo();
1014fe6060f1SDimitry Andric   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1015fe6060f1SDimitry Andric   const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1016fe6060f1SDimitry Andric 
1017fe6060f1SDimitry Andric   // Chase the value read by a copy-like instruction back to the instruction
1018fe6060f1SDimitry Andric   // that ultimately _defines_ that value. This may pass:
1019fe6060f1SDimitry Andric   //  * Through multiple intermediate copies, including subregister moves /
1020fe6060f1SDimitry Andric   //    copies,
1021fe6060f1SDimitry Andric   //  * Copies from physical registers that must then be traced back to the
1022fe6060f1SDimitry Andric   //    defining instruction,
1023fe6060f1SDimitry Andric   //  * Or, physical registers may be live-in to (only) the entry block, which
1024fe6060f1SDimitry Andric   //    requires a DBG_PHI to be created.
1025fe6060f1SDimitry Andric   // We can pursue this problem in that order: trace back through copies,
1026fe6060f1SDimitry Andric   // optionally through a physical register, to a defining instruction. We
1027fe6060f1SDimitry Andric   // should never move from physreg to vreg. As we're still in SSA form, no need
1028fe6060f1SDimitry Andric   // to worry about partial definitions of registers.
1029fe6060f1SDimitry Andric 
1030fe6060f1SDimitry Andric   // Helper lambda to interpret a copy-like instruction. Takes instruction,
1031fe6060f1SDimitry Andric   // returns the register read and any subregister identifying which part is
1032fe6060f1SDimitry Andric   // read.
1033fe6060f1SDimitry Andric   auto GetRegAndSubreg =
1034fe6060f1SDimitry Andric       [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1035fe6060f1SDimitry Andric     Register NewReg, OldReg;
1036fe6060f1SDimitry Andric     unsigned SubReg;
1037fe6060f1SDimitry Andric     if (Cpy.isCopy()) {
1038fe6060f1SDimitry Andric       OldReg = Cpy.getOperand(0).getReg();
1039fe6060f1SDimitry Andric       NewReg = Cpy.getOperand(1).getReg();
1040fe6060f1SDimitry Andric       SubReg = Cpy.getOperand(1).getSubReg();
1041fe6060f1SDimitry Andric     } else if (Cpy.isSubregToReg()) {
1042fe6060f1SDimitry Andric       OldReg = Cpy.getOperand(0).getReg();
1043fe6060f1SDimitry Andric       NewReg = Cpy.getOperand(2).getReg();
1044fe6060f1SDimitry Andric       SubReg = Cpy.getOperand(3).getImm();
1045fe6060f1SDimitry Andric     } else {
1046fe6060f1SDimitry Andric       auto CopyDetails = *TII.isCopyInstr(Cpy);
1047fe6060f1SDimitry Andric       const MachineOperand &Src = *CopyDetails.Source;
1048fe6060f1SDimitry Andric       const MachineOperand &Dest = *CopyDetails.Destination;
1049fe6060f1SDimitry Andric       OldReg = Dest.getReg();
1050fe6060f1SDimitry Andric       NewReg = Src.getReg();
1051fe6060f1SDimitry Andric       SubReg = Src.getSubReg();
1052fe6060f1SDimitry Andric     }
1053fe6060f1SDimitry Andric 
1054fe6060f1SDimitry Andric     return {NewReg, SubReg};
1055fe6060f1SDimitry Andric   };
1056fe6060f1SDimitry Andric 
1057fe6060f1SDimitry Andric   // First seek either the defining instruction, or a copy from a physreg.
1058fe6060f1SDimitry Andric   // During search, the current state is the current copy instruction, and which
1059fe6060f1SDimitry Andric   // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1060fe6060f1SDimitry Andric   // deal with those later.
1061fe6060f1SDimitry Andric   auto State = GetRegAndSubreg(MI);
1062fe6060f1SDimitry Andric   auto CurInst = MI.getIterator();
1063fe6060f1SDimitry Andric   SmallVector<unsigned, 4> SubregsSeen;
1064fe6060f1SDimitry Andric   while (true) {
1065fe6060f1SDimitry Andric     // If we've found a copy from a physreg, first portion of search is over.
1066fe6060f1SDimitry Andric     if (!State.first.isVirtual())
1067fe6060f1SDimitry Andric       break;
1068fe6060f1SDimitry Andric 
1069fe6060f1SDimitry Andric     // Record any subregister qualifier.
1070fe6060f1SDimitry Andric     if (State.second)
1071fe6060f1SDimitry Andric       SubregsSeen.push_back(State.second);
1072fe6060f1SDimitry Andric 
1073fe6060f1SDimitry Andric     assert(MRI.hasOneDef(State.first));
1074fe6060f1SDimitry Andric     MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1075fe6060f1SDimitry Andric     CurInst = Inst.getIterator();
1076fe6060f1SDimitry Andric 
1077fe6060f1SDimitry Andric     // Any non-copy instruction is the defining instruction we're seeking.
1078fe6060f1SDimitry Andric     if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1079fe6060f1SDimitry Andric       break;
1080fe6060f1SDimitry Andric     State = GetRegAndSubreg(Inst);
1081fe6060f1SDimitry Andric   };
1082fe6060f1SDimitry Andric 
1083fe6060f1SDimitry Andric   // Helper lambda to apply additional subregister substitutions to a known
1084fe6060f1SDimitry Andric   // instruction/operand pair. Adds new (fake) substitutions so that we can
1085fe6060f1SDimitry Andric   // record the subregister. FIXME: this isn't very space efficient if multiple
1086fe6060f1SDimitry Andric   // values are tracked back through the same copies; cache something later.
1087fe6060f1SDimitry Andric   auto ApplySubregisters =
1088fe6060f1SDimitry Andric       [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1089fe6060f1SDimitry Andric     for (unsigned Subreg : reverse(SubregsSeen)) {
1090fe6060f1SDimitry Andric       // Fetch a new instruction number, not attached to an actual instruction.
1091fe6060f1SDimitry Andric       unsigned NewInstrNumber = getNewDebugInstrNum();
1092fe6060f1SDimitry Andric       // Add a substitution from the "new" number to the known one, with a
1093fe6060f1SDimitry Andric       // qualifying subreg.
1094fe6060f1SDimitry Andric       makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1095fe6060f1SDimitry Andric       // Return the new number; to find the underlying value, consumers need to
1096fe6060f1SDimitry Andric       // deal with the qualifying subreg.
1097fe6060f1SDimitry Andric       P = {NewInstrNumber, 0};
1098fe6060f1SDimitry Andric     }
1099fe6060f1SDimitry Andric     return P;
1100fe6060f1SDimitry Andric   };
1101fe6060f1SDimitry Andric 
1102fe6060f1SDimitry Andric   // If we managed to find the defining instruction after COPYs, return an
1103fe6060f1SDimitry Andric   // instruction / operand pair after adding subregister qualifiers.
1104fe6060f1SDimitry Andric   if (State.first.isVirtual()) {
1105fe6060f1SDimitry Andric     // Virtual register def -- we can just look up where this happens.
1106fe6060f1SDimitry Andric     MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
1107fe6060f1SDimitry Andric     for (auto &MO : Inst->operands()) {
1108fe6060f1SDimitry Andric       if (!MO.isReg() || !MO.isDef() || MO.getReg() != State.first)
1109fe6060f1SDimitry Andric         continue;
1110fe6060f1SDimitry Andric       return ApplySubregisters(
1111fe6060f1SDimitry Andric           {Inst->getDebugInstrNum(), Inst->getOperandNo(&MO)});
1112fe6060f1SDimitry Andric     }
1113fe6060f1SDimitry Andric 
1114fe6060f1SDimitry Andric     llvm_unreachable("Vreg def with no corresponding operand?");
1115fe6060f1SDimitry Andric   }
1116fe6060f1SDimitry Andric 
1117fe6060f1SDimitry Andric   // Our search ended in a copy from a physreg: walk back up the function
1118fe6060f1SDimitry Andric   // looking for whatever defines the physreg.
1119fe6060f1SDimitry Andric   assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1120fe6060f1SDimitry Andric   State = GetRegAndSubreg(*CurInst);
1121fe6060f1SDimitry Andric   Register RegToSeek = State.first;
1122fe6060f1SDimitry Andric 
1123fe6060f1SDimitry Andric   auto RMII = CurInst->getReverseIterator();
1124fe6060f1SDimitry Andric   auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1125fe6060f1SDimitry Andric   for (auto &ToExamine : PrevInstrs) {
1126fe6060f1SDimitry Andric     for (auto &MO : ToExamine.operands()) {
1127fe6060f1SDimitry Andric       // Test for operand that defines something aliasing RegToSeek.
1128fe6060f1SDimitry Andric       if (!MO.isReg() || !MO.isDef() ||
1129fe6060f1SDimitry Andric           !TRI.regsOverlap(RegToSeek, MO.getReg()))
1130fe6060f1SDimitry Andric         continue;
1131fe6060f1SDimitry Andric 
1132fe6060f1SDimitry Andric       return ApplySubregisters(
1133fe6060f1SDimitry Andric           {ToExamine.getDebugInstrNum(), ToExamine.getOperandNo(&MO)});
1134fe6060f1SDimitry Andric     }
1135fe6060f1SDimitry Andric   }
1136fe6060f1SDimitry Andric 
1137fe6060f1SDimitry Andric   MachineBasicBlock &InsertBB = *CurInst->getParent();
1138fe6060f1SDimitry Andric 
1139fe6060f1SDimitry Andric   // We reached the start of the block before finding a defining instruction.
1140fe6060f1SDimitry Andric   // It could be from a constant register, otherwise it must be an argument.
1141fe6060f1SDimitry Andric   if (TRI.isConstantPhysReg(State.first)) {
1142fe6060f1SDimitry Andric     // We can produce a DBG_PHI that identifies the constant physreg. Doesn't
1143fe6060f1SDimitry Andric     // matter where we put it, as it's constant valued.
1144fe6060f1SDimitry Andric     assert(CurInst->isCopy());
1145fe6060f1SDimitry Andric   } else if (State.first == TRI.getFrameRegister(*this)) {
1146fe6060f1SDimitry Andric     // LLVM IR is allowed to read the framepointer by calling a
1147fe6060f1SDimitry Andric     // llvm.frameaddress.* intrinsic. We can support this by emitting a
1148fe6060f1SDimitry Andric     // DBG_PHI $fp. This isn't ideal, because it extends the behaviours /
1149fe6060f1SDimitry Andric     // position that DBG_PHIs appear at, limiting what can be done later.
1150fe6060f1SDimitry Andric     // TODO: see if there's a better way of expressing these variable
1151fe6060f1SDimitry Andric     // locations.
1152fe6060f1SDimitry Andric     ;
1153fe6060f1SDimitry Andric   } else {
1154349cc55cSDimitry Andric     // Assert that this is the entry block, or an EH pad. If it isn't, then
1155349cc55cSDimitry Andric     // there is some code construct we don't recognise that deals with physregs
1156349cc55cSDimitry Andric     // across blocks.
1157fe6060f1SDimitry Andric     assert(!State.first.isVirtual());
1158349cc55cSDimitry Andric     assert(&*InsertBB.getParent()->begin() == &InsertBB || InsertBB.isEHPad());
1159fe6060f1SDimitry Andric   }
1160fe6060f1SDimitry Andric 
1161fe6060f1SDimitry Andric   // Create DBG_PHI for specified physreg.
1162fe6060f1SDimitry Andric   auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1163fe6060f1SDimitry Andric                          TII.get(TargetOpcode::DBG_PHI));
1164349cc55cSDimitry Andric   Builder.addReg(State.first);
1165fe6060f1SDimitry Andric   unsigned NewNum = getNewDebugInstrNum();
1166fe6060f1SDimitry Andric   Builder.addImm(NewNum);
1167fe6060f1SDimitry Andric   return ApplySubregisters({NewNum, 0u});
1168fe6060f1SDimitry Andric }
1169fe6060f1SDimitry Andric 
1170fe6060f1SDimitry Andric void MachineFunction::finalizeDebugInstrRefs() {
1171fe6060f1SDimitry Andric   auto *TII = getSubtarget().getInstrInfo();
1172fe6060f1SDimitry Andric 
11734824e7fdSDimitry Andric   auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1174fe6060f1SDimitry Andric     const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE);
1175fe6060f1SDimitry Andric     MI.setDesc(RefII);
11764824e7fdSDimitry Andric     MI.getOperand(0).setReg(0);
1177fe6060f1SDimitry Andric     MI.getOperand(1).ChangeToRegister(0, false);
1178fe6060f1SDimitry Andric   };
1179fe6060f1SDimitry Andric 
1180349cc55cSDimitry Andric   if (!useDebugInstrRef())
1181fe6060f1SDimitry Andric     return;
1182fe6060f1SDimitry Andric 
1183fe6060f1SDimitry Andric   for (auto &MBB : *this) {
1184fe6060f1SDimitry Andric     for (auto &MI : MBB) {
1185fe6060f1SDimitry Andric       if (!MI.isDebugRef() || !MI.getOperand(0).isReg())
1186fe6060f1SDimitry Andric         continue;
1187fe6060f1SDimitry Andric 
1188fe6060f1SDimitry Andric       Register Reg = MI.getOperand(0).getReg();
1189fe6060f1SDimitry Andric 
1190fe6060f1SDimitry Andric       // Some vregs can be deleted as redundant in the meantime. Mark those
11914824e7fdSDimitry Andric       // as DBG_VALUE $noreg. Additionally, some normal instructions are
11924824e7fdSDimitry Andric       // quickly deleted, leaving dangling references to vregs with no def.
11934824e7fdSDimitry Andric       if (Reg == 0 || !RegInfo->hasOneDef(Reg)) {
11944824e7fdSDimitry Andric         MakeUndefDbgValue(MI);
1195fe6060f1SDimitry Andric         continue;
1196fe6060f1SDimitry Andric       }
1197fe6060f1SDimitry Andric 
1198fe6060f1SDimitry Andric       assert(Reg.isVirtual());
1199fe6060f1SDimitry Andric       MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1200fe6060f1SDimitry Andric 
1201fe6060f1SDimitry Andric       // If we've found a copy-like instruction, follow it back to the
1202fe6060f1SDimitry Andric       // instruction that defines the source value, see salvageCopySSA docs
1203fe6060f1SDimitry Andric       // for why this is important.
1204fe6060f1SDimitry Andric       if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
1205fe6060f1SDimitry Andric         auto Result = salvageCopySSA(DefMI);
1206fe6060f1SDimitry Andric         MI.getOperand(0).ChangeToImmediate(Result.first);
1207fe6060f1SDimitry Andric         MI.getOperand(1).setImm(Result.second);
1208fe6060f1SDimitry Andric       } else {
1209fe6060f1SDimitry Andric         // Otherwise, identify the operand number that the VReg refers to.
1210fe6060f1SDimitry Andric         unsigned OperandIdx = 0;
1211fe6060f1SDimitry Andric         for (const auto &MO : DefMI.operands()) {
1212fe6060f1SDimitry Andric           if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
1213fe6060f1SDimitry Andric             break;
1214fe6060f1SDimitry Andric           ++OperandIdx;
1215fe6060f1SDimitry Andric         }
1216fe6060f1SDimitry Andric         assert(OperandIdx < DefMI.getNumOperands());
1217fe6060f1SDimitry Andric 
1218fe6060f1SDimitry Andric         // Morph this instr ref to point at the given instruction and operand.
1219fe6060f1SDimitry Andric         unsigned ID = DefMI.getDebugInstrNum();
1220fe6060f1SDimitry Andric         MI.getOperand(0).ChangeToImmediate(ID);
1221fe6060f1SDimitry Andric         MI.getOperand(1).setImm(OperandIdx);
1222fe6060f1SDimitry Andric       }
1223fe6060f1SDimitry Andric     }
1224fe6060f1SDimitry Andric   }
1225fe6060f1SDimitry Andric }
1226fe6060f1SDimitry Andric 
1227349cc55cSDimitry Andric bool MachineFunction::useDebugInstrRef() const {
1228349cc55cSDimitry Andric   // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1229349cc55cSDimitry Andric   // have optimized code inlined into this unoptimized code, however with
1230349cc55cSDimitry Andric   // fewer and less aggressive optimizations happening, coverage and accuracy
1231349cc55cSDimitry Andric   // should not suffer.
1232349cc55cSDimitry Andric   if (getTarget().getOptLevel() == CodeGenOpt::None)
1233349cc55cSDimitry Andric     return false;
1234349cc55cSDimitry Andric 
1235349cc55cSDimitry Andric   // Don't use instr-ref if this function is marked optnone.
1236349cc55cSDimitry Andric   if (F.hasFnAttribute(Attribute::OptimizeNone))
1237349cc55cSDimitry Andric     return false;
1238349cc55cSDimitry Andric 
1239349cc55cSDimitry Andric   if (getTarget().Options.ValueTrackingVariableLocations)
1240349cc55cSDimitry Andric     return true;
1241349cc55cSDimitry Andric 
1242349cc55cSDimitry Andric   return false;
1243349cc55cSDimitry Andric }
1244349cc55cSDimitry Andric 
1245349cc55cSDimitry Andric // Use one million as a high / reserved number.
1246349cc55cSDimitry Andric const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1247349cc55cSDimitry Andric 
1248*0b57cec5SDimitry Andric /// \}
1249*0b57cec5SDimitry Andric 
1250*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1251*0b57cec5SDimitry Andric //  MachineJumpTableInfo implementation
1252*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1253*0b57cec5SDimitry Andric 
1254*0b57cec5SDimitry Andric /// Return the size of each entry in the jump table.
1255*0b57cec5SDimitry Andric unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
1256*0b57cec5SDimitry Andric   // The size of a jump table entry is 4 bytes unless the entry is just the
1257*0b57cec5SDimitry Andric   // address of a block, in which case it is the pointer size.
1258*0b57cec5SDimitry Andric   switch (getEntryKind()) {
1259*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_BlockAddress:
1260*0b57cec5SDimitry Andric     return TD.getPointerSize();
1261*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1262*0b57cec5SDimitry Andric     return 8;
1263*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1264*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_LabelDifference32:
1265*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Custom32:
1266*0b57cec5SDimitry Andric     return 4;
1267*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Inline:
1268*0b57cec5SDimitry Andric     return 0;
1269*0b57cec5SDimitry Andric   }
1270*0b57cec5SDimitry Andric   llvm_unreachable("Unknown jump table encoding!");
1271*0b57cec5SDimitry Andric }
1272*0b57cec5SDimitry Andric 
1273*0b57cec5SDimitry Andric /// Return the alignment of each entry in the jump table.
1274*0b57cec5SDimitry Andric unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
1275*0b57cec5SDimitry Andric   // The alignment of a jump table entry is the alignment of int32 unless the
1276*0b57cec5SDimitry Andric   // entry is just the address of a block, in which case it is the pointer
1277*0b57cec5SDimitry Andric   // alignment.
1278*0b57cec5SDimitry Andric   switch (getEntryKind()) {
1279*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_BlockAddress:
12808bcb0991SDimitry Andric     return TD.getPointerABIAlignment(0).value();
1281*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
12828bcb0991SDimitry Andric     return TD.getABIIntegerTypeAlignment(64).value();
1283*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1284*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_LabelDifference32:
1285*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Custom32:
12868bcb0991SDimitry Andric     return TD.getABIIntegerTypeAlignment(32).value();
1287*0b57cec5SDimitry Andric   case MachineJumpTableInfo::EK_Inline:
1288*0b57cec5SDimitry Andric     return 1;
1289*0b57cec5SDimitry Andric   }
1290*0b57cec5SDimitry Andric   llvm_unreachable("Unknown jump table encoding!");
1291*0b57cec5SDimitry Andric }
1292*0b57cec5SDimitry Andric 
1293*0b57cec5SDimitry Andric /// Create a new jump table entry in the jump table info.
1294*0b57cec5SDimitry Andric unsigned MachineJumpTableInfo::createJumpTableIndex(
1295*0b57cec5SDimitry Andric                                const std::vector<MachineBasicBlock*> &DestBBs) {
1296*0b57cec5SDimitry Andric   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1297*0b57cec5SDimitry Andric   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1298*0b57cec5SDimitry Andric   return JumpTables.size()-1;
1299*0b57cec5SDimitry Andric }
1300*0b57cec5SDimitry Andric 
1301*0b57cec5SDimitry Andric /// If Old is the target of any jump tables, update the jump tables to branch
1302*0b57cec5SDimitry Andric /// to New instead.
1303*0b57cec5SDimitry Andric bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1304*0b57cec5SDimitry Andric                                                   MachineBasicBlock *New) {
1305*0b57cec5SDimitry Andric   assert(Old != New && "Not making a change?");
1306*0b57cec5SDimitry Andric   bool MadeChange = false;
1307*0b57cec5SDimitry Andric   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1308*0b57cec5SDimitry Andric     ReplaceMBBInJumpTable(i, Old, New);
1309*0b57cec5SDimitry Andric   return MadeChange;
1310*0b57cec5SDimitry Andric }
1311*0b57cec5SDimitry Andric 
1312e8d8bef9SDimitry Andric /// If MBB is present in any jump tables, remove it.
1313e8d8bef9SDimitry Andric bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1314e8d8bef9SDimitry Andric   bool MadeChange = false;
1315e8d8bef9SDimitry Andric   for (MachineJumpTableEntry &JTE : JumpTables) {
1316e8d8bef9SDimitry Andric     auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1317e8d8bef9SDimitry Andric     MadeChange |= (removeBeginItr != JTE.MBBs.end());
1318e8d8bef9SDimitry Andric     JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1319e8d8bef9SDimitry Andric   }
1320e8d8bef9SDimitry Andric   return MadeChange;
1321e8d8bef9SDimitry Andric }
1322e8d8bef9SDimitry Andric 
1323*0b57cec5SDimitry Andric /// If Old is a target of the jump tables, update the jump table to branch to
1324*0b57cec5SDimitry Andric /// New instead.
1325*0b57cec5SDimitry Andric bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1326*0b57cec5SDimitry Andric                                                  MachineBasicBlock *Old,
1327*0b57cec5SDimitry Andric                                                  MachineBasicBlock *New) {
1328*0b57cec5SDimitry Andric   assert(Old != New && "Not making a change?");
1329*0b57cec5SDimitry Andric   bool MadeChange = false;
1330*0b57cec5SDimitry Andric   MachineJumpTableEntry &JTE = JumpTables[Idx];
13314824e7fdSDimitry Andric   for (MachineBasicBlock *&MBB : JTE.MBBs)
13324824e7fdSDimitry Andric     if (MBB == Old) {
13334824e7fdSDimitry Andric       MBB = New;
1334*0b57cec5SDimitry Andric       MadeChange = true;
1335*0b57cec5SDimitry Andric     }
1336*0b57cec5SDimitry Andric   return MadeChange;
1337*0b57cec5SDimitry Andric }
1338*0b57cec5SDimitry Andric 
1339*0b57cec5SDimitry Andric void MachineJumpTableInfo::print(raw_ostream &OS) const {
1340*0b57cec5SDimitry Andric   if (JumpTables.empty()) return;
1341*0b57cec5SDimitry Andric 
1342*0b57cec5SDimitry Andric   OS << "Jump Tables:\n";
1343*0b57cec5SDimitry Andric 
1344*0b57cec5SDimitry Andric   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1345*0b57cec5SDimitry Andric     OS << printJumpTableEntryReference(i) << ':';
13464824e7fdSDimitry Andric     for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
13474824e7fdSDimitry Andric       OS << ' ' << printMBBReference(*MBB);
1348*0b57cec5SDimitry Andric     if (i != e)
1349*0b57cec5SDimitry Andric       OS << '\n';
1350*0b57cec5SDimitry Andric   }
1351*0b57cec5SDimitry Andric 
1352*0b57cec5SDimitry Andric   OS << '\n';
1353*0b57cec5SDimitry Andric }
1354*0b57cec5SDimitry Andric 
1355*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1356*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1357*0b57cec5SDimitry Andric #endif
1358*0b57cec5SDimitry Andric 
1359*0b57cec5SDimitry Andric Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1360*0b57cec5SDimitry Andric   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1361*0b57cec5SDimitry Andric }
1362*0b57cec5SDimitry Andric 
1363*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1364*0b57cec5SDimitry Andric //  MachineConstantPool implementation
1365*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1366*0b57cec5SDimitry Andric 
1367*0b57cec5SDimitry Andric void MachineConstantPoolValue::anchor() {}
1368*0b57cec5SDimitry Andric 
1369e8d8bef9SDimitry Andric unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1370e8d8bef9SDimitry Andric   return DL.getTypeAllocSize(Ty);
1371e8d8bef9SDimitry Andric }
1372e8d8bef9SDimitry Andric 
1373e8d8bef9SDimitry Andric unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
1374*0b57cec5SDimitry Andric   if (isMachineConstantPoolEntry())
1375e8d8bef9SDimitry Andric     return Val.MachineCPVal->getSizeInBytes(DL);
1376e8d8bef9SDimitry Andric   return DL.getTypeAllocSize(Val.ConstVal->getType());
1377*0b57cec5SDimitry Andric }
1378*0b57cec5SDimitry Andric 
1379*0b57cec5SDimitry Andric bool MachineConstantPoolEntry::needsRelocation() const {
1380*0b57cec5SDimitry Andric   if (isMachineConstantPoolEntry())
1381*0b57cec5SDimitry Andric     return true;
1382fe6060f1SDimitry Andric   return Val.ConstVal->needsDynamicRelocation();
1383*0b57cec5SDimitry Andric }
1384*0b57cec5SDimitry Andric 
1385*0b57cec5SDimitry Andric SectionKind
1386*0b57cec5SDimitry Andric MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1387*0b57cec5SDimitry Andric   if (needsRelocation())
1388*0b57cec5SDimitry Andric     return SectionKind::getReadOnlyWithRel();
1389e8d8bef9SDimitry Andric   switch (getSizeInBytes(*DL)) {
1390*0b57cec5SDimitry Andric   case 4:
1391*0b57cec5SDimitry Andric     return SectionKind::getMergeableConst4();
1392*0b57cec5SDimitry Andric   case 8:
1393*0b57cec5SDimitry Andric     return SectionKind::getMergeableConst8();
1394*0b57cec5SDimitry Andric   case 16:
1395*0b57cec5SDimitry Andric     return SectionKind::getMergeableConst16();
1396*0b57cec5SDimitry Andric   case 32:
1397*0b57cec5SDimitry Andric     return SectionKind::getMergeableConst32();
1398*0b57cec5SDimitry Andric   default:
1399*0b57cec5SDimitry Andric     return SectionKind::getReadOnly();
1400*0b57cec5SDimitry Andric   }
1401*0b57cec5SDimitry Andric }
1402*0b57cec5SDimitry Andric 
1403*0b57cec5SDimitry Andric MachineConstantPool::~MachineConstantPool() {
1404*0b57cec5SDimitry Andric   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1405*0b57cec5SDimitry Andric   // so keep track of which we've deleted to avoid double deletions.
1406*0b57cec5SDimitry Andric   DenseSet<MachineConstantPoolValue*> Deleted;
1407*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1408*0b57cec5SDimitry Andric     if (Constants[i].isMachineConstantPoolEntry()) {
1409*0b57cec5SDimitry Andric       Deleted.insert(Constants[i].Val.MachineCPVal);
1410*0b57cec5SDimitry Andric       delete Constants[i].Val.MachineCPVal;
1411*0b57cec5SDimitry Andric     }
1412fe6060f1SDimitry Andric   for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1413fe6060f1SDimitry Andric     if (Deleted.count(CPV) == 0)
1414fe6060f1SDimitry Andric       delete CPV;
1415*0b57cec5SDimitry Andric   }
1416*0b57cec5SDimitry Andric }
1417*0b57cec5SDimitry Andric 
1418*0b57cec5SDimitry Andric /// Test whether the given two constants can be allocated the same constant pool
1419*0b57cec5SDimitry Andric /// entry.
1420*0b57cec5SDimitry Andric static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1421*0b57cec5SDimitry Andric                                       const DataLayout &DL) {
1422*0b57cec5SDimitry Andric   // Handle the trivial case quickly.
1423*0b57cec5SDimitry Andric   if (A == B) return true;
1424*0b57cec5SDimitry Andric 
1425*0b57cec5SDimitry Andric   // If they have the same type but weren't the same constant, quickly
1426*0b57cec5SDimitry Andric   // reject them.
1427*0b57cec5SDimitry Andric   if (A->getType() == B->getType()) return false;
1428*0b57cec5SDimitry Andric 
1429*0b57cec5SDimitry Andric   // We can't handle structs or arrays.
1430*0b57cec5SDimitry Andric   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1431*0b57cec5SDimitry Andric       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1432*0b57cec5SDimitry Andric     return false;
1433*0b57cec5SDimitry Andric 
1434*0b57cec5SDimitry Andric   // For now, only support constants with the same size.
1435*0b57cec5SDimitry Andric   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1436*0b57cec5SDimitry Andric   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1437*0b57cec5SDimitry Andric     return false;
1438*0b57cec5SDimitry Andric 
1439*0b57cec5SDimitry Andric   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1440*0b57cec5SDimitry Andric 
1441*0b57cec5SDimitry Andric   // Try constant folding a bitcast of both instructions to an integer.  If we
1442*0b57cec5SDimitry Andric   // get two identical ConstantInt's, then we are good to share them.  We use
1443*0b57cec5SDimitry Andric   // the constant folding APIs to do this so that we get the benefit of
1444*0b57cec5SDimitry Andric   // DataLayout.
1445*0b57cec5SDimitry Andric   if (isa<PointerType>(A->getType()))
1446*0b57cec5SDimitry Andric     A = ConstantFoldCastOperand(Instruction::PtrToInt,
1447*0b57cec5SDimitry Andric                                 const_cast<Constant *>(A), IntTy, DL);
1448*0b57cec5SDimitry Andric   else if (A->getType() != IntTy)
1449*0b57cec5SDimitry Andric     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1450*0b57cec5SDimitry Andric                                 IntTy, DL);
1451*0b57cec5SDimitry Andric   if (isa<PointerType>(B->getType()))
1452*0b57cec5SDimitry Andric     B = ConstantFoldCastOperand(Instruction::PtrToInt,
1453*0b57cec5SDimitry Andric                                 const_cast<Constant *>(B), IntTy, DL);
1454*0b57cec5SDimitry Andric   else if (B->getType() != IntTy)
1455*0b57cec5SDimitry Andric     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1456*0b57cec5SDimitry Andric                                 IntTy, DL);
1457*0b57cec5SDimitry Andric 
1458*0b57cec5SDimitry Andric   return A == B;
1459*0b57cec5SDimitry Andric }
1460*0b57cec5SDimitry Andric 
1461*0b57cec5SDimitry Andric /// Create a new entry in the constant pool or return an existing one.
1462*0b57cec5SDimitry Andric /// User must specify the log2 of the minimum required alignment for the object.
1463*0b57cec5SDimitry Andric unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
14645ffd83dbSDimitry Andric                                                    Align Alignment) {
1465*0b57cec5SDimitry Andric   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1466*0b57cec5SDimitry Andric 
1467*0b57cec5SDimitry Andric   // Check to see if we already have this constant.
1468*0b57cec5SDimitry Andric   //
1469*0b57cec5SDimitry Andric   // FIXME, this could be made much more efficient for large constant pools.
1470*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1471*0b57cec5SDimitry Andric     if (!Constants[i].isMachineConstantPoolEntry() &&
1472*0b57cec5SDimitry Andric         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
14735ffd83dbSDimitry Andric       if (Constants[i].getAlign() < Alignment)
1474*0b57cec5SDimitry Andric         Constants[i].Alignment = Alignment;
1475*0b57cec5SDimitry Andric       return i;
1476*0b57cec5SDimitry Andric     }
1477*0b57cec5SDimitry Andric 
1478*0b57cec5SDimitry Andric   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1479*0b57cec5SDimitry Andric   return Constants.size()-1;
1480*0b57cec5SDimitry Andric }
1481*0b57cec5SDimitry Andric 
1482*0b57cec5SDimitry Andric unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
14835ffd83dbSDimitry Andric                                                    Align Alignment) {
1484*0b57cec5SDimitry Andric   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1485*0b57cec5SDimitry Andric 
1486*0b57cec5SDimitry Andric   // Check to see if we already have this constant.
1487*0b57cec5SDimitry Andric   //
1488*0b57cec5SDimitry Andric   // FIXME, this could be made much more efficient for large constant pools.
1489*0b57cec5SDimitry Andric   int Idx = V->getExistingMachineCPValue(this, Alignment);
1490*0b57cec5SDimitry Andric   if (Idx != -1) {
1491*0b57cec5SDimitry Andric     MachineCPVsSharingEntries.insert(V);
1492*0b57cec5SDimitry Andric     return (unsigned)Idx;
1493*0b57cec5SDimitry Andric   }
1494*0b57cec5SDimitry Andric 
1495*0b57cec5SDimitry Andric   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1496*0b57cec5SDimitry Andric   return Constants.size()-1;
1497*0b57cec5SDimitry Andric }
1498*0b57cec5SDimitry Andric 
1499*0b57cec5SDimitry Andric void MachineConstantPool::print(raw_ostream &OS) const {
1500*0b57cec5SDimitry Andric   if (Constants.empty()) return;
1501*0b57cec5SDimitry Andric 
1502*0b57cec5SDimitry Andric   OS << "Constant Pool:\n";
1503*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1504*0b57cec5SDimitry Andric     OS << "  cp#" << i << ": ";
1505*0b57cec5SDimitry Andric     if (Constants[i].isMachineConstantPoolEntry())
1506*0b57cec5SDimitry Andric       Constants[i].Val.MachineCPVal->print(OS);
1507*0b57cec5SDimitry Andric     else
1508*0b57cec5SDimitry Andric       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
15095ffd83dbSDimitry Andric     OS << ", align=" << Constants[i].getAlign().value();
1510*0b57cec5SDimitry Andric     OS << "\n";
1511*0b57cec5SDimitry Andric   }
1512*0b57cec5SDimitry Andric }
1513*0b57cec5SDimitry Andric 
1514*0b57cec5SDimitry Andric #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1515*0b57cec5SDimitry Andric LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1516*0b57cec5SDimitry Andric #endif
1517