1//===- MachineFunction.cpp ------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Collect native machine code information for a function. This allows
10// target-specific information about the generated code to be stored with each
11// function.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/MachineFunction.h"
16#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/StringSwitch.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/Analysis/ConstantFolding.h"
26#include "llvm/Analysis/ProfileSummaryInfo.h"
27#include "llvm/CodeGen/MachineBasicBlock.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineJumpTableInfo.h"
32#include "llvm/CodeGen/MachineMemOperand.h"
33#include "llvm/CodeGen/MachineModuleInfo.h"
34#include "llvm/CodeGen/MachineRegisterInfo.h"
35#include "llvm/CodeGen/PseudoSourceValue.h"
36#include "llvm/CodeGen/PseudoSourceValueManager.h"
37#include "llvm/CodeGen/TargetFrameLowering.h"
38#include "llvm/CodeGen/TargetInstrInfo.h"
39#include "llvm/CodeGen/TargetLowering.h"
40#include "llvm/CodeGen/TargetRegisterInfo.h"
41#include "llvm/CodeGen/TargetSubtargetInfo.h"
42#include "llvm/CodeGen/WinEHFuncInfo.h"
43#include "llvm/Config/llvm-config.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
46#include "llvm/IR/Constant.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DerivedTypes.h"
49#include "llvm/IR/EHPersonalities.h"
50#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalValue.h"
52#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Instructions.h"
54#include "llvm/IR/Metadata.h"
55#include "llvm/IR/Module.h"
56#include "llvm/IR/ModuleSlotTracker.h"
57#include "llvm/IR/Value.h"
58#include "llvm/MC/MCContext.h"
59#include "llvm/MC/MCSymbol.h"
60#include "llvm/MC/SectionKind.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/CommandLine.h"
63#include "llvm/Support/Compiler.h"
64#include "llvm/Support/DOTGraphTraits.h"
65#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/FormatVariadic.h"
67#include "llvm/Support/GraphWriter.h"
68#include "llvm/Support/raw_ostream.h"
69#include "llvm/Target/TargetMachine.h"
70#include <algorithm>
71#include <cassert>
72#include <cstddef>
73#include <cstdint>
74#include <iterator>
75#include <string>
76#include <utility>
77#include <vector>
78
79#include "LiveDebugValues/LiveDebugValues.h"
80
81using namespace llvm;
82
83#define DEBUG_TYPE "codegen"
84
85static cl::opt<unsigned> AlignAllFunctions(
86 "align-all-functions",
87 cl::desc("Force the alignment of all functions in log2 format (e.g. 4 "
88 "means align on 16B boundaries)."),
89 cl::init(Val: 0), cl::Hidden);
90
91static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
92 using P = MachineFunctionProperties::Property;
93
94 // clang-format off
95 switch(Prop) {
96 case P::FailedISel: return "FailedISel";
97 case P::IsSSA: return "IsSSA";
98 case P::Legalized: return "Legalized";
99 case P::NoPHIs: return "NoPHIs";
100 case P::NoVRegs: return "NoVRegs";
101 case P::RegBankSelected: return "RegBankSelected";
102 case P::Selected: return "Selected";
103 case P::TracksLiveness: return "TracksLiveness";
104 case P::TiedOpsRewritten: return "TiedOpsRewritten";
105 case P::FailsVerification: return "FailsVerification";
106 case P::FailedRegAlloc: return "FailedRegAlloc";
107 case P::TracksDebugUserValues: return "TracksDebugUserValues";
108 }
109 // clang-format on
110 llvm_unreachable("Invalid machine function property");
111}
112
113void setUnsafeStackSize(const Function &F, MachineFrameInfo &FrameInfo) {
114 if (!F.hasFnAttribute(Kind: Attribute::SafeStack))
115 return;
116
117 auto *Existing =
118 dyn_cast_or_null<MDTuple>(Val: F.getMetadata(KindID: LLVMContext::MD_annotation));
119
120 if (!Existing || Existing->getNumOperands() != 2)
121 return;
122
123 auto *MetadataName = "unsafe-stack-size";
124 if (auto &N = Existing->getOperand(I: 0)) {
125 if (N.equalsStr(Str: MetadataName)) {
126 if (auto &Op = Existing->getOperand(I: 1)) {
127 auto Val = mdconst::extract<ConstantInt>(MD: Op)->getZExtValue();
128 FrameInfo.setUnsafeStackSize(Val);
129 }
130 }
131 }
132}
133
134// Pin the vtable to this file.
135void MachineFunction::Delegate::anchor() {}
136
137void MachineFunctionProperties::print(raw_ostream &OS) const {
138 const char *Separator = "";
139 for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
140 if (!Properties[I])
141 continue;
142 OS << Separator << getPropertyName(Prop: static_cast<Property>(I));
143 Separator = ", ";
144 }
145}
146
147//===----------------------------------------------------------------------===//
148// MachineFunction implementation
149//===----------------------------------------------------------------------===//
150
151// Out-of-line virtual method.
152MachineFunctionInfo::~MachineFunctionInfo() = default;
153
154void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
155 MBB->getParent()->deleteMachineBasicBlock(MBB);
156}
157
158static inline Align getFnStackAlignment(const TargetSubtargetInfo &STI,
159 const Function &F) {
160 if (auto MA = F.getFnStackAlign())
161 return *MA;
162 return STI.getFrameLowering()->getStackAlign();
163}
164
165static FramePointerKind getFramePointerPolicy(const Function &F) {
166 Attribute FPAttr = F.getFnAttribute(Kind: "frame-pointer");
167 if (!FPAttr.isValid())
168 return FramePointerKind::None;
169
170 StringRef FP = FPAttr.getValueAsString();
171 return StringSwitch<FramePointerKind>(FP)
172 .Case(S: "all", Value: FramePointerKind::All)
173 .Case(S: "non-leaf", Value: FramePointerKind::NonLeaf)
174 .Case(S: "non-leaf-no-reserve", Value: FramePointerKind::NonLeafNoReserve)
175 .Case(S: "reserved", Value: FramePointerKind::Reserved)
176 .Case(S: "none", Value: FramePointerKind::None)
177 .Default(Value: FramePointerKind::None);
178}
179
180MachineFunction::MachineFunction(Function &F, const TargetMachine &Target,
181 const TargetSubtargetInfo &STI, MCContext &Ctx,
182 unsigned FunctionNum)
183 : F(F), Target(Target), STI(STI), Ctx(Ctx) {
184 FunctionNumber = FunctionNum;
185 init();
186}
187
188void MachineFunction::handleInsertion(MachineInstr &MI) {
189 if (TheDelegate)
190 TheDelegate->MF_HandleInsertion(MI);
191}
192
193void MachineFunction::handleRemoval(MachineInstr &MI) {
194 if (TheDelegate)
195 TheDelegate->MF_HandleRemoval(MI);
196}
197
198void MachineFunction::handleChangeDesc(MachineInstr &MI,
199 const MCInstrDesc &TID) {
200 if (TheDelegate)
201 TheDelegate->MF_HandleChangeDesc(MI, TID);
202}
203
204void MachineFunction::init() {
205 // Assume the function starts in SSA form with correct liveness.
206 Properties.setIsSSA();
207 Properties.setTracksLiveness();
208 RegInfo = new (Allocator) MachineRegisterInfo(this);
209
210 MFInfo = nullptr;
211
212 // We can realign the stack if the target supports it and the user hasn't
213 // explicitly asked us not to.
214 bool CanRealignSP = STI.getFrameLowering()->isStackRealignable() &&
215 !F.hasFnAttribute(Kind: "no-realign-stack");
216 bool ForceRealignSP = F.hasFnAttribute(Kind: Attribute::StackAlignment) ||
217 F.hasFnAttribute(Kind: "stackrealign");
218 FrameInfo = new (Allocator) MachineFrameInfo(
219 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
220 /*ForcedRealign=*/ForceRealignSP && CanRealignSP);
221 FrameInfo->setFramePointerPolicy(getFramePointerPolicy(F));
222
223 setUnsafeStackSize(F, FrameInfo&: *FrameInfo);
224
225 if (F.hasFnAttribute(Kind: Attribute::StackAlignment))
226 FrameInfo->ensureMaxAlignment(Alignment: *F.getFnStackAlign());
227
228 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
229 Alignment = STI.getTargetLowering()->getMinFunctionAlignment();
230
231 // -fsanitize=function and -fsanitize=kcfi instrument indirect function calls
232 // to load a type hash before the function label. Ensure functions are aligned
233 // by a least 4 to avoid unaligned access, which is especially important for
234 // -mno-unaligned-access.
235 if (F.hasMetadata(KindID: LLVMContext::MD_func_sanitize) ||
236 F.getMetadata(KindID: LLVMContext::MD_kcfi_type))
237 Alignment = std::max(a: Alignment, b: Align(4));
238
239 if (AlignAllFunctions)
240 Alignment = Align(1ULL << AlignAllFunctions);
241
242 JumpTableInfo = nullptr;
243
244 if (isFuncletEHPersonality(Pers: classifyEHPersonality(
245 Pers: F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
246 WinEHInfo = new (Allocator) WinEHFuncInfo();
247 }
248
249 if (!Target.isCompatibleDataLayout(Candidate: getDataLayout())) {
250 report_fatal_error(
251 reason: formatv(Fmt: "Can't create a MachineFunction using a Module with a "
252 "Target-incompatible DataLayout attached\n Target "
253 "DataLayout: {0}\n Module DataLayout: {1}\n",
254 Vals: Target.createDataLayout().getStringRepresentation(),
255 Vals: getDataLayout().getStringRepresentation()));
256 }
257
258 PSVManager = std::make_unique<PseudoSourceValueManager>(args: getTarget());
259}
260
261void MachineFunction::initTargetMachineFunctionInfo(
262 const TargetSubtargetInfo &STI) {
263 assert(!MFInfo && "MachineFunctionInfo already set");
264 MFInfo = Target.createMachineFunctionInfo(Allocator, F, STI: &STI);
265}
266
267MachineFunctionInfo *MachineFunction::cloneInfoFrom(
268 const MachineFunction &OrigMF,
269 const DenseMap<MachineBasicBlock *, MachineBasicBlock *> &Src2DstMBB) {
270 assert(!MFInfo && "new function already has MachineFunctionInfo");
271 if (!OrigMF.MFInfo)
272 return nullptr;
273
274 MachineFunctionInfo *ClonedInfo =
275 OrigMF.MFInfo->clone(Allocator, DestMF&: *this, Src2DstMBB);
276 if (!ClonedInfo)
277 return nullptr;
278
279 RegInfo->copyPendingVirtRegMapEntriesFrom(Other: OrigMF.getRegInfo());
280 return ClonedInfo;
281}
282
283MachineFunction::~MachineFunction() {
284 clear();
285}
286
287void MachineFunction::clear() {
288 Properties.reset();
289
290 // Clear JumpTableInfo first. Otherwise, every MBB we delete would do a
291 // linear search over the jump table entries to find and erase itself.
292 if (JumpTableInfo) {
293 JumpTableInfo->~MachineJumpTableInfo();
294 Allocator.Deallocate(Ptr: JumpTableInfo);
295 JumpTableInfo = nullptr;
296 }
297
298 // Don't call destructors on MachineInstr and MachineOperand. All of their
299 // memory comes from the BumpPtrAllocator which is about to be purged.
300 //
301 // Do call MachineBasicBlock destructors, it contains std::vectors.
302 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(where: I))
303 I->Insts.clearAndLeakNodesUnsafely();
304 MBBNumbering.clear();
305
306 InstructionRecycler.clear(Allocator);
307 OperandRecycler.clear(Allocator);
308 BasicBlockRecycler.clear(Allocator);
309 CodeViewAnnotations.clear();
310 VariableDbgInfos.clear();
311 if (RegInfo) {
312 RegInfo->~MachineRegisterInfo();
313 Allocator.Deallocate(Ptr: RegInfo);
314 }
315 if (MFInfo) {
316 MFInfo->~MachineFunctionInfo();
317 Allocator.Deallocate(Ptr: MFInfo);
318 }
319
320 FrameInfo->~MachineFrameInfo();
321 Allocator.Deallocate(Ptr: FrameInfo);
322
323 ConstantPool->~MachineConstantPool();
324 Allocator.Deallocate(Ptr: ConstantPool);
325
326 if (WinEHInfo) {
327 WinEHInfo->~WinEHFuncInfo();
328 Allocator.Deallocate(Ptr: WinEHInfo);
329 }
330}
331
332const DataLayout &MachineFunction::getDataLayout() const {
333 return F.getDataLayout();
334}
335
336/// Get the JumpTableInfo for this function.
337/// If it does not already exist, allocate one.
338MachineJumpTableInfo *MachineFunction::
339getOrCreateJumpTableInfo(unsigned EntryKind) {
340 if (JumpTableInfo) return JumpTableInfo;
341
342 JumpTableInfo = new (Allocator)
343 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
344 return JumpTableInfo;
345}
346
347DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
348 return F.getDenormalMode(FPType);
349}
350
351/// Should we be emitting segmented stack stuff for the function
352bool MachineFunction::shouldSplitStack() const {
353 return getFunction().hasFnAttribute(Kind: "split-stack");
354}
355
356Align MachineFunction::getPreferredAlignment() const {
357 Align PrefAlignment;
358
359 if (MaybeAlign A = F.getPreferredAlignment())
360 PrefAlignment = *A;
361 else if (!F.hasOptSize())
362 PrefAlignment = STI.getTargetLowering()->getPrefFunctionAlignment();
363 else
364 PrefAlignment = Align(1);
365
366 return std::max(a: PrefAlignment, b: getAlignment());
367}
368
369[[nodiscard]] unsigned
370MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
371 FrameInstructions.push_back(x: Inst);
372 return FrameInstructions.size() - 1;
373}
374
375void MachineFunction::replaceFrameInstRegister(MCRegister FromReg,
376 MCRegister ToReg) {
377 const MCRegisterInfo *MCRI = Ctx.getRegisterInfo();
378 unsigned DwarfFromReg = MCRI->getDwarfRegNum(Reg: FromReg, isEH: false);
379 unsigned DwarfToReg = MCRI->getDwarfRegNum(Reg: ToReg, isEH: false);
380
381 for (MCCFIInstruction &Inst : FrameInstructions)
382 Inst.replaceRegister(FromReg: DwarfFromReg, ToReg: DwarfToReg);
383}
384
385/// This discards all of the MachineBasicBlock numbers and recomputes them.
386/// This guarantees that the MBB numbers are sequential, dense, and match the
387/// ordering of the blocks within the function. If a specific MachineBasicBlock
388/// is specified, only that block and those after it are renumbered.
389void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
390 if (empty()) { MBBNumbering.clear(); return; }
391 MachineFunction::iterator MBBI, E = end();
392 if (MBB == nullptr)
393 MBBI = begin();
394 else
395 MBBI = MBB->getIterator();
396
397 // Figure out the block number this should have.
398 unsigned BlockNo = 0;
399 if (MBBI != begin())
400 BlockNo = std::prev(x: MBBI)->getNumber() + 1;
401
402 for (; MBBI != E; ++MBBI, ++BlockNo) {
403 if (MBBI->getNumber() != (int)BlockNo) {
404 // Remove use of the old number.
405 if (MBBI->getNumber() != -1) {
406 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
407 "MBB number mismatch!");
408 MBBNumbering[MBBI->getNumber()] = nullptr;
409 }
410
411 // If BlockNo is already taken, set that block's number to -1.
412 if (MBBNumbering[BlockNo])
413 MBBNumbering[BlockNo]->setNumber(-1);
414
415 MBBNumbering[BlockNo] = &*MBBI;
416 MBBI->setNumber(BlockNo);
417 }
418 }
419
420 // Okay, all the blocks are renumbered. If we have compactified the block
421 // numbering, shrink MBBNumbering now.
422 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
423 MBBNumbering.resize(new_size: BlockNo);
424}
425
426int64_t MachineFunction::estimateFunctionSizeInBytes() {
427 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
428 const Align FunctionAlignment = getAlignment();
429 MachineFunction::iterator MBBI = begin(), E = end();
430 /// Offset - Distance from the beginning of the function to the end
431 /// of the basic block.
432 int64_t Offset = 0;
433
434 for (; MBBI != E; ++MBBI) {
435 const Align Alignment = MBBI->getAlignment();
436 int64_t BlockSize = 0;
437
438 for (auto &MI : *MBBI) {
439 BlockSize += TII.getInstSizeInBytes(MI);
440 }
441
442 int64_t OffsetBB;
443 if (Alignment <= FunctionAlignment) {
444 OffsetBB = alignTo(Size: Offset, A: Alignment);
445 } else {
446 // The alignment of this MBB is larger than the function's alignment, so
447 // we can't tell whether or not it will insert nops. Assume that it will.
448 OffsetBB = alignTo(Size: Offset, A: Alignment) + Alignment.value() -
449 FunctionAlignment.value();
450 }
451 Offset = OffsetBB + BlockSize;
452 }
453
454 return Offset;
455}
456
457/// This method iterates over the basic blocks and assigns their IsBeginSection
458/// and IsEndSection fields. This must be called after MBB layout is finalized
459/// and the SectionID's are assigned to MBBs.
460void MachineFunction::assignBeginEndSections() {
461 front().setIsBeginSection();
462 auto CurrentSectionID = front().getSectionID();
463 for (auto MBBI = std::next(x: begin()), E = end(); MBBI != E; ++MBBI) {
464 if (MBBI->getSectionID() == CurrentSectionID)
465 continue;
466 MBBI->setIsBeginSection();
467 std::prev(x: MBBI)->setIsEndSection();
468 CurrentSectionID = MBBI->getSectionID();
469 }
470 back().setIsEndSection();
471}
472
473/// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
474MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
475 DebugLoc DL,
476 bool NoImplicit) {
477 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
478 MachineInstr(*this, MCID, std::move(DL), NoImplicit);
479}
480
481/// Create a new MachineInstr which is a copy of the 'Orig' instruction,
482/// identical in all ways except the instruction has no parent, prev, or next.
483MachineInstr *
484MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
485 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
486 MachineInstr(*this, *Orig);
487}
488
489MachineInstr &MachineFunction::cloneMachineInstrBundle(
490 MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
491 const MachineInstr &Orig) {
492 MachineInstr *FirstClone = nullptr;
493 MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
494 while (true) {
495 MachineInstr *Cloned = CloneMachineInstr(Orig: &*I);
496 MBB.insert(I: InsertBefore, MI: Cloned);
497 if (FirstClone == nullptr) {
498 FirstClone = Cloned;
499 } else {
500 Cloned->bundleWithPred();
501 }
502
503 if (!I->isBundledWithSucc())
504 break;
505 ++I;
506 }
507 // Copy over call info to the cloned instruction if needed. If Orig is in
508 // a bundle, copyAdditionalCallInfo takes care of finding the call instruction
509 // in the bundle.
510 if (Orig.shouldUpdateAdditionalCallInfo())
511 copyAdditionalCallInfo(Old: &Orig, New: FirstClone);
512 return *FirstClone;
513}
514
515/// Delete the given MachineInstr.
516///
517/// This function also serves as the MachineInstr destructor - the real
518/// ~MachineInstr() destructor must be empty.
519void MachineFunction::deleteMachineInstr(MachineInstr *MI) {
520 // Verify that a call site info is at valid state. This assertion should
521 // be triggered during the implementation of support for the
522 // call site info of a new architecture. If the assertion is triggered,
523 // back trace will tell where to insert a call to updateCallSiteInfo().
524 assert((!MI->isCandidateForAdditionalCallInfo() ||
525 !CallSitesInfo.contains(MI)) &&
526 "Call site info was not updated!");
527 // Verify that the "called globals" info is in a valid state.
528 assert((!MI->isCandidateForAdditionalCallInfo() ||
529 !CalledGlobalsInfo.contains(MI)) &&
530 "Called globals info was not updated!");
531 // Strip it for parts. The operand array and the MI object itself are
532 // independently recyclable.
533 if (MI->Operands)
534 deallocateOperandArray(Cap: MI->CapOperands, Array: MI->Operands);
535 // Don't call ~MachineInstr() which must be trivial anyway because
536 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
537 // destructors.
538 InstructionRecycler.Deallocate(Allocator, Element: MI);
539}
540
541/// Allocate a new MachineBasicBlock. Use this instead of
542/// `new MachineBasicBlock'.
543MachineBasicBlock *
544MachineFunction::CreateMachineBasicBlock(const BasicBlock *BB,
545 std::optional<UniqueBBID> BBID) {
546 MachineBasicBlock *MBB =
547 new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
548 MachineBasicBlock(*this, BB);
549 // Set BBID for `-basic-block-sections=list` and `-basic-block-address-map` to
550 // allow robust mapping of profiles to basic blocks.
551 if (Target.Options.BBAddrMap ||
552 Target.getBBSectionsType() == BasicBlockSection::List)
553 MBB->setBBID(BBID.has_value() ? *BBID : UniqueBBID{.BaseID: NextBBID++, .CloneID: 0});
554 return MBB;
555}
556
557/// Delete the given MachineBasicBlock.
558void MachineFunction::deleteMachineBasicBlock(MachineBasicBlock *MBB) {
559 assert(MBB->getParent() == this && "MBB parent mismatch!");
560 // Clean up any references to MBB in jump tables before deleting it.
561 if (JumpTableInfo)
562 JumpTableInfo->RemoveMBBFromJumpTables(MBB);
563 MBB->~MachineBasicBlock();
564 BasicBlockRecycler.Deallocate(Allocator, Element: MBB);
565}
566
567MachineMemOperand *MachineFunction::getMachineMemOperand(
568 MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LocationSize Size,
569 Align BaseAlignment, const MMOMetadata &Metadata, SyncScope::ID SSID,
570 AtomicOrdering Ordering, AtomicOrdering FailureOrdering) {
571 assert((!Size.hasValue() ||
572 Size.getValue().getKnownMinValue() != ~UINT64_C(0)) &&
573 "Unexpected an unknown size to be represented using "
574 "LocationSize::beforeOrAfter()");
575 return new (Allocator)
576 MachineMemOperand(PtrInfo, F, Size, BaseAlignment, Metadata, SSID,
577 Ordering, FailureOrdering);
578}
579
580MachineMemOperand *MachineFunction::getMachineMemOperand(
581 MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy,
582 Align BaseAlignment, const MMOMetadata &Metadata, SyncScope::ID SSID,
583 AtomicOrdering Ordering, AtomicOrdering FailureOrdering) {
584 return new (Allocator)
585 MachineMemOperand(PtrInfo, F, MemTy, BaseAlignment, Metadata, SSID,
586 Ordering, FailureOrdering);
587}
588
589MachineMemOperand *
590MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
591 const MachinePointerInfo &PtrInfo,
592 LocationSize Size) {
593 assert((!Size.hasValue() ||
594 Size.getValue().getKnownMinValue() != ~UINT64_C(0)) &&
595 "Unexpected an unknown size to be represented using "
596 "LocationSize::beforeOrAfter()");
597 return new (Allocator) MachineMemOperand(
598 PtrInfo, MMO->getFlags(), Size, MMO->getBaseAlign(),
599 MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MMO->getMemCacheHint()),
600 MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
601 MMO->getFailureOrdering());
602}
603
604MachineMemOperand *MachineFunction::getMachineMemOperand(
605 const MachineMemOperand *MMO, const MachinePointerInfo &PtrInfo, LLT Ty) {
606 return new (Allocator) MachineMemOperand(
607 PtrInfo, MMO->getFlags(), Ty, MMO->getBaseAlign(),
608 MMOMetadata(AAMDNodes(), /*Ranges=*/nullptr, MMO->getMemCacheHint()),
609 MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
610 MMO->getFailureOrdering());
611}
612
613MachineMemOperand *
614MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
615 int64_t Offset, LLT Ty) {
616 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
617
618 // If there is no pointer value, the offset isn't tracked so we need to adjust
619 // the base alignment.
620 Align Alignment = PtrInfo.V.isNull()
621 ? commonAlignment(A: MMO->getBaseAlign(), Offset)
622 : MMO->getBaseAlign();
623
624 // Do not preserve ranges, since we don't necessarily know what the high bits
625 // are anymore.
626 return new (Allocator) MachineMemOperand(
627 PtrInfo.getWithOffset(O: Offset), MMO->getFlags(), Ty, Alignment,
628 MMOMetadata(MMO->getAAInfo(), /*Ranges=*/nullptr, MMO->getMemCacheHint()),
629 MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
630 MMO->getFailureOrdering());
631}
632
633MachineMemOperand *
634MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
635 const AAMDNodes &AAInfo) {
636 MachinePointerInfo MPI = MMO->getValue() ?
637 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
638 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
639
640 return new (Allocator) MachineMemOperand(
641 MPI, MMO->getFlags(), MMO->getSize(), MMO->getBaseAlign(),
642 MMOMetadata(AAInfo, MMO->getRanges(), MMO->getMemCacheHint()),
643 MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
644 MMO->getFailureOrdering());
645}
646
647MachineMemOperand *
648MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
649 MachineMemOperand::Flags Flags) {
650 return new (Allocator) MachineMemOperand(
651 MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlign(),
652 MMOMetadata(MMO->getAAInfo(), MMO->getRanges(), MMO->getMemCacheHint()),
653 MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
654 MMO->getFailureOrdering());
655}
656
657MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
658 ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
659 MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker, MDNode *PCSections,
660 uint32_t CFIType, MDNode *MMRAs, Value *DS) {
661 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
662 PostInstrSymbol, HeapAllocMarker,
663 PCSections, CFIType, MMRAs, DS);
664}
665
666const char *MachineFunction::createExternalSymbolName(StringRef Name) {
667 char *Dest = Allocator.Allocate<char>(Num: Name.size() + 1);
668 llvm::copy(Range&: Name, Out: Dest);
669 Dest[Name.size()] = 0;
670 return Dest;
671}
672
673uint32_t *MachineFunction::allocateRegMask() {
674 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
675 unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
676 uint32_t *Mask = Allocator.Allocate<uint32_t>(Num: Size);
677 memset(s: Mask, c: 0, n: Size * sizeof(Mask[0]));
678 return Mask;
679}
680
681ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
682 int* AllocMask = Allocator.Allocate<int>(Num: Mask.size());
683 copy(Range&: Mask, Out: AllocMask);
684 return {AllocMask, Mask.size()};
685}
686
687#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
688LLVM_DUMP_METHOD void MachineFunction::dump() const {
689 print(dbgs());
690}
691#endif
692
693StringRef MachineFunction::getName() const {
694 return getFunction().getName();
695}
696
697void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
698 OS << "# Machine code for function " << getName() << ": ";
699 getProperties().print(OS);
700 OS << '\n';
701
702 // Print Frame Information
703 FrameInfo->print(MF: *this, OS);
704
705 // Print JumpTable Information
706 if (JumpTableInfo)
707 JumpTableInfo->print(OS);
708
709 // Print Constant Pool
710 ConstantPool->print(OS);
711
712 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
713
714 if (RegInfo && !RegInfo->livein_empty()) {
715 OS << "Function Live Ins: ";
716 for (MachineRegisterInfo::livein_iterator
717 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
718 OS << printReg(Reg: I->first, TRI);
719 if (I->second)
720 OS << " in " << printReg(Reg: I->second, TRI);
721 if (std::next(x: I) != E)
722 OS << ", ";
723 }
724 OS << '\n';
725 }
726
727 ModuleSlotTracker MST(getFunction().getParent());
728 MST.incorporateFunction(F: getFunction());
729 for (const auto &BB : *this) {
730 OS << '\n';
731 // If we print the whole function, print it at its most verbose level.
732 BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
733 }
734
735 OS << "\n# End machine code for function " << getName() << ".\n\n";
736}
737
738/// True if this function needs frame moves for debug or exceptions.
739bool MachineFunction::needsFrameMoves() const {
740 // TODO: Ideally, what we'd like is to have a switch that allows emitting
741 // synchronous (precise at call-sites only) CFA into .eh_frame. However, even
742 // under this switch, we'd like .debug_frame to be precise when using -g. At
743 // this moment, there's no way to specify that some CFI directives go into
744 // .eh_frame only, while others go into .debug_frame only.
745 return getTarget().Options.ForceDwarfFrameSection ||
746 F.needsUnwindTableEntry() ||
747 !F.getParent()->debug_compile_units().empty();
748}
749
750bool MachineFunction::disableFramePointerElim() const {
751 FramePointerKind FP = getFrameInfo().getFramePointerPolicy();
752 switch (FP) {
753 case FramePointerKind::All:
754 return true;
755 case FramePointerKind::NonLeaf:
756 case FramePointerKind::NonLeafNoReserve:
757 return getFrameInfo().hasCalls();
758 case FramePointerKind::None:
759 case FramePointerKind::Reserved:
760 return false;
761 }
762 llvm_unreachable("unknown frame pointer flag");
763}
764
765bool MachineFunction::framePointerIsReserved() const {
766 FramePointerKind FP = getFrameInfo().getFramePointerPolicy();
767 switch (FP) {
768 case FramePointerKind::All:
769 case FramePointerKind::NonLeaf:
770 case FramePointerKind::Reserved:
771 return true;
772 case FramePointerKind::NonLeafNoReserve:
773 return getFrameInfo().hasCalls();
774 case FramePointerKind::None:
775 return false;
776 }
777 llvm_unreachable("unknown frame pointer flag");
778}
779
780MachineFunction::CallSiteInfo::CallSiteInfo(const CallBase &CB) {
781 if (MDNode *Node = CB.getMetadata(KindID: llvm::LLVMContext::MD_call_target))
782 CallTarget = Node;
783
784 // Numeric callee_type ids are only for indirect calls.
785 if (!CB.isIndirectCall())
786 return;
787
788 MDNode *CalleeTypeList = CB.getMetadata(KindID: LLVMContext::MD_callee_type);
789 if (!CalleeTypeList)
790 return;
791
792 for (const MDOperand &Op : CalleeTypeList->operands()) {
793 MDNode *TypeMD = cast<MDNode>(Val: Op);
794 MDString *TypeIdStr = cast<MDString>(Val: TypeMD->getOperand(I: 0));
795 // Compute numeric type id from type id string
796 uint64_t TypeIdVal = MD5Hash(Str: TypeIdStr->getString());
797 IntegerType *Int64Ty = Type::getInt64Ty(C&: CB.getContext());
798 CalleeTypeIds.push_back(
799 Elt: ConstantInt::get(Ty: Int64Ty, V: TypeIdVal, /*IsSigned=*/false));
800 }
801}
802
803template <>
804struct llvm::DOTGraphTraits<const MachineFunction *>
805 : public DefaultDOTGraphTraits {
806 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
807
808 static std::string getGraphName(const MachineFunction *F) {
809 return ("CFG for '" + F->getName() + "' function").str();
810 }
811
812 std::string getNodeLabel(const MachineBasicBlock *Node,
813 const MachineFunction *Graph) {
814 std::string OutStr;
815 {
816 raw_string_ostream OSS(OutStr);
817
818 if (isSimple()) {
819 OSS << printMBBReference(MBB: *Node);
820 if (const BasicBlock *BB = Node->getBasicBlock())
821 OSS << ": " << BB->getName();
822 } else
823 Node->print(OS&: OSS);
824 }
825
826 if (OutStr[0] == '\n')
827 OutStr.erase(position: OutStr.begin());
828
829 // Process string output to make it nicer...
830 for (unsigned i = 0; i != OutStr.length(); ++i)
831 if (OutStr[i] == '\n') { // Left justify
832 OutStr[i] = '\\';
833 OutStr.insert(p: OutStr.begin() + i + 1, c: 'l');
834 }
835 return OutStr;
836 }
837};
838
839void MachineFunction::viewCFG() const
840{
841#ifndef NDEBUG
842 ViewGraph(this, "mf" + getName());
843#else
844 errs() << "MachineFunction::viewCFG is only available in debug builds on "
845 << "systems with Graphviz or gv!\n";
846#endif // NDEBUG
847}
848
849void MachineFunction::viewCFGOnly() const
850{
851#ifndef NDEBUG
852 ViewGraph(this, "mf" + getName(), true);
853#else
854 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
855 << "systems with Graphviz or gv!\n";
856#endif // NDEBUG
857}
858
859/// Add the specified physical register as a live-in value and
860/// create a corresponding virtual register for it.
861Register MachineFunction::addLiveIn(MCRegister PReg,
862 const TargetRegisterClass *RC) {
863 MachineRegisterInfo &MRI = getRegInfo();
864 Register VReg = MRI.getLiveInVirtReg(PReg);
865 if (VReg) {
866 const TargetRegisterClass *VRegRC = MRI.getRegClass(Reg: VReg);
867 (void)VRegRC;
868 // A physical register can be added several times.
869 // Between two calls, the register class of the related virtual register
870 // may have been constrained to match some operation constraints.
871 // In that case, check that the current register class includes the
872 // physical register and is a sub class of the specified RC.
873 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
874 RC->hasSubClassEq(VRegRC))) &&
875 "Register class mismatch!");
876 return VReg;
877 }
878 VReg = MRI.createVirtualRegister(RegClass: RC);
879 MRI.addLiveIn(Reg: PReg, vreg: VReg);
880 return VReg;
881}
882
883/// Return the MCSymbol for the specified non-empty jump table.
884/// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
885/// normal 'L' label is returned.
886MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
887 bool isLinkerPrivate) const {
888 const DataLayout &DL = getDataLayout();
889 assert(JumpTableInfo && "No jump tables");
890 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
891
892 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
893 : DL.getInternalSymbolPrefix();
894 SmallString<60> Name;
895 raw_svector_ostream(Name)
896 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
897 return Ctx.getOrCreateSymbol(Name);
898}
899
900/// Return a function-local symbol to represent the PIC base.
901MCSymbol *MachineFunction::getPICBaseSymbol() const {
902 const DataLayout &DL = getDataLayout();
903 return Ctx.getOrCreateSymbol(Name: Twine(DL.getInternalSymbolPrefix()) +
904 Twine(getFunctionNumber()) + "$pb");
905}
906
907/// \name Exception Handling
908/// \{
909
910LandingPadInfo &
911MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
912 unsigned N = LandingPads.size();
913 for (unsigned i = 0; i < N; ++i) {
914 LandingPadInfo &LP = LandingPads[i];
915 if (LP.LandingPadBlock == LandingPad)
916 return LP;
917 }
918
919 LandingPads.push_back(x: LandingPadInfo(LandingPad));
920 return LandingPads[N];
921}
922
923void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
924 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
925 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
926 LP.BeginLabels.push_back(Elt: BeginLabel);
927 LP.EndLabels.push_back(Elt: EndLabel);
928}
929
930MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
931 MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
932 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
933 LP.LandingPadLabel = LandingPadLabel;
934
935 BasicBlock::const_iterator FirstI =
936 LandingPad->getBasicBlock()->getFirstNonPHIIt();
937 if (const auto *LPI = dyn_cast<LandingPadInst>(Val&: FirstI)) {
938 // If there's no typeid list specified, then "cleanup" is implicit.
939 // Otherwise, id 0 is reserved for the cleanup action.
940 if (LPI->isCleanup() && LPI->getNumClauses() != 0)
941 LP.TypeIds.push_back(x: 0);
942
943 // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
944 // correct, but we need to do it this way because of how the DWARF EH
945 // emitter processes the clauses.
946 for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
947 Value *Val = LPI->getClause(Idx: I - 1);
948 if (LPI->isCatch(Idx: I - 1)) {
949 LP.TypeIds.push_back(
950 x: getTypeIDFor(TI: dyn_cast<GlobalValue>(Val: Val->stripPointerCasts())));
951 } else {
952 // Add filters in a list.
953 auto *CVal = cast<Constant>(Val);
954 SmallVector<unsigned, 4> FilterList;
955 for (const Use &U : CVal->operands())
956 FilterList.push_back(
957 Elt: getTypeIDFor(TI: cast<GlobalValue>(Val: U->stripPointerCasts())));
958
959 LP.TypeIds.push_back(x: getFilterIDFor(TyIds: FilterList));
960 }
961 }
962
963 } else if (const auto *CPI = dyn_cast<CatchPadInst>(Val&: FirstI)) {
964 for (unsigned I = CPI->arg_size(); I != 0; --I) {
965 auto *TypeInfo =
966 dyn_cast<GlobalValue>(Val: CPI->getArgOperand(i: I - 1)->stripPointerCasts());
967 LP.TypeIds.push_back(x: getTypeIDFor(TI: TypeInfo));
968 }
969
970 } else {
971 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
972 }
973
974 return LandingPadLabel;
975}
976
977void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
978 ArrayRef<unsigned> Sites) {
979 LPadToCallSiteMap[Sym].append(in_start: Sites.begin(), in_end: Sites.end());
980}
981
982unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
983 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
984 if (TypeInfos[i] == TI) return i + 1;
985
986 TypeInfos.push_back(x: TI);
987 return TypeInfos.size();
988}
989
990int MachineFunction::getFilterIDFor(ArrayRef<unsigned> TyIds) {
991 // If the new filter coincides with the tail of an existing filter, then
992 // re-use the existing filter. Folding filters more than this requires
993 // re-ordering filters and/or their elements - probably not worth it.
994 for (unsigned i : FilterEnds) {
995 unsigned j = TyIds.size();
996
997 while (i && j)
998 if (FilterIds[--i] != TyIds[--j])
999 goto try_next;
1000
1001 if (!j)
1002 // The new filter coincides with range [i, end) of the existing filter.
1003 return -(1 + i);
1004
1005try_next:;
1006 }
1007
1008 // Add the new filter.
1009 int FilterID = -(1 + FilterIds.size());
1010 FilterIds.reserve(n: FilterIds.size() + TyIds.size() + 1);
1011 llvm::append_range(C&: FilterIds, R&: TyIds);
1012 FilterEnds.push_back(x: FilterIds.size());
1013 FilterIds.push_back(x: 0); // terminator
1014 return FilterID;
1015}
1016
1017MachineFunction::CallSiteInfoMap::iterator
1018MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
1019 assert(MI->isCandidateForAdditionalCallInfo() &&
1020 "Call site info refers only to call (MI) candidates");
1021
1022 if (!Target.Options.EmitCallSiteInfo && !Target.Options.EmitCallGraphSection)
1023 return CallSitesInfo.end();
1024 return CallSitesInfo.find(Val: MI);
1025}
1026
1027/// Return the call machine instruction or find a call within bundle.
1028static const MachineInstr *getCallInstr(const MachineInstr *MI) {
1029 if (!MI->isBundle())
1030 return MI;
1031
1032 for (const auto &BMI : make_range(x: getBundleStart(I: MI->getIterator()),
1033 y: getBundleEnd(I: MI->getIterator())))
1034 if (BMI.isCandidateForAdditionalCallInfo())
1035 return &BMI;
1036
1037 llvm_unreachable("Unexpected bundle without a call site candidate");
1038}
1039
1040void MachineFunction::eraseAdditionalCallInfo(const MachineInstr *MI) {
1041 assert(MI->shouldUpdateAdditionalCallInfo() &&
1042 "Call info refers only to call (MI) candidates or "
1043 "candidates inside bundles");
1044
1045 const MachineInstr *CallMI = getCallInstr(MI);
1046
1047 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(MI: CallMI);
1048 if (CSIt != CallSitesInfo.end())
1049 CallSitesInfo.erase(I: CSIt);
1050
1051 CalledGlobalsInfo.erase(Val: CallMI);
1052}
1053
1054void MachineFunction::copyAdditionalCallInfo(const MachineInstr *Old,
1055 const MachineInstr *New) {
1056 assert(Old->shouldUpdateAdditionalCallInfo() &&
1057 "Call info refers only to call (MI) candidates or "
1058 "candidates inside bundles");
1059
1060 if (!New->isCandidateForAdditionalCallInfo())
1061 return eraseAdditionalCallInfo(MI: Old);
1062
1063 const MachineInstr *OldCallMI = getCallInstr(MI: Old);
1064 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(MI: OldCallMI);
1065 if (CSIt != CallSitesInfo.end()) {
1066 CallSiteInfo CSInfo = CSIt->second;
1067 CallSitesInfo[New] = std::move(CSInfo);
1068 }
1069
1070 CalledGlobalsMap::iterator CGIt = CalledGlobalsInfo.find(Val: OldCallMI);
1071 if (CGIt != CalledGlobalsInfo.end()) {
1072 CalledGlobalInfo CGInfo = CGIt->second;
1073 CalledGlobalsInfo[New] = std::move(CGInfo);
1074 }
1075}
1076
1077void MachineFunction::moveAdditionalCallInfo(const MachineInstr *Old,
1078 const MachineInstr *New) {
1079 assert(Old->shouldUpdateAdditionalCallInfo() &&
1080 "Call info refers only to call (MI) candidates or "
1081 "candidates inside bundles");
1082
1083 if (!New->isCandidateForAdditionalCallInfo())
1084 return eraseAdditionalCallInfo(MI: Old);
1085
1086 const MachineInstr *OldCallMI = getCallInstr(MI: Old);
1087 CallSiteInfoMap::iterator CSIt = getCallSiteInfo(MI: OldCallMI);
1088 if (CSIt != CallSitesInfo.end()) {
1089 CallSiteInfo CSInfo = std::move(CSIt->second);
1090 CallSitesInfo.erase(I: CSIt);
1091 CallSitesInfo[New] = std::move(CSInfo);
1092 }
1093
1094 CalledGlobalsMap::iterator CGIt = CalledGlobalsInfo.find(Val: OldCallMI);
1095 if (CGIt != CalledGlobalsInfo.end()) {
1096 CalledGlobalInfo CGInfo = std::move(CGIt->second);
1097 CalledGlobalsInfo.erase(I: CGIt);
1098 CalledGlobalsInfo[New] = std::move(CGInfo);
1099 }
1100}
1101
1102void MachineFunction::setDebugInstrNumberingCount(unsigned Num) {
1103 DebugInstrNumberingCount = Num;
1104}
1105
1106void MachineFunction::makeDebugValueSubstitution(DebugInstrOperandPair A,
1107 DebugInstrOperandPair B,
1108 unsigned Subreg) {
1109 // Catch any accidental self-loops.
1110 assert(A.first != B.first);
1111 // Don't allow any substitutions _from_ the memory operand number.
1112 assert(A.second != DebugOperandMemNumber);
1113
1114 DebugValueSubstitutions.push_back(Elt: {A, B, Subreg});
1115}
1116
1117void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
1118 MachineInstr &New,
1119 unsigned MaxOperand) {
1120 // If the Old instruction wasn't tracked at all, there is no work to do.
1121 unsigned OldInstrNum = Old.peekDebugInstrNum();
1122 if (!OldInstrNum)
1123 return;
1124
1125 // Iterate over all operands looking for defs to create substitutions for.
1126 // Avoid creating new instr numbers unless we create a new substitution.
1127 // While this has no functional effect, it risks confusing someone reading
1128 // MIR output.
1129 // Examine all the operands, or the first N specified by the caller.
1130 MaxOperand = std::min(a: MaxOperand, b: Old.getNumOperands());
1131 for (unsigned int I = 0; I < MaxOperand; ++I) {
1132 const auto &OldMO = Old.getOperand(i: I);
1133 auto &NewMO = New.getOperand(i: I);
1134 (void)NewMO;
1135
1136 if (!OldMO.isReg() || !OldMO.isDef())
1137 continue;
1138 assert(NewMO.isDef());
1139
1140 unsigned NewInstrNum = New.getDebugInstrNum();
1141 makeDebugValueSubstitution(A: std::make_pair(x&: OldInstrNum, y&: I),
1142 B: std::make_pair(x&: NewInstrNum, y&: I));
1143 }
1144}
1145
1146auto MachineFunction::salvageCopySSA(
1147 MachineInstr &MI, DenseMap<Register, DebugInstrOperandPair> &DbgPHICache)
1148 -> DebugInstrOperandPair {
1149 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1150
1151 // Check whether this copy-like instruction has already been salvaged into
1152 // an operand pair.
1153 Register Dest;
1154 if (auto CopyDstSrc = TII.isCopyLikeInstr(MI)) {
1155 Dest = CopyDstSrc->Destination->getReg();
1156 } else {
1157 assert(MI.isSubregToReg());
1158 Dest = MI.getOperand(i: 0).getReg();
1159 }
1160
1161 auto CacheIt = DbgPHICache.find(Val: Dest);
1162 if (CacheIt != DbgPHICache.end())
1163 return CacheIt->second;
1164
1165 // Calculate the instruction number to use, or install a DBG_PHI.
1166 auto OperandPair = salvageCopySSAImpl(MI);
1167 DbgPHICache.insert(KV: {Dest, OperandPair});
1168 return OperandPair;
1169}
1170
1171auto MachineFunction::salvageCopySSAImpl(MachineInstr &MI)
1172 -> DebugInstrOperandPair {
1173 MachineRegisterInfo &MRI = getRegInfo();
1174 const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1175 const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1176
1177 // Chase the value read by a copy-like instruction back to the instruction
1178 // that ultimately _defines_ that value. This may pass:
1179 // * Through multiple intermediate copies, including subregister moves /
1180 // copies,
1181 // * Copies from physical registers that must then be traced back to the
1182 // defining instruction,
1183 // * Or, physical registers may be live-in to (only) the entry block, which
1184 // requires a DBG_PHI to be created.
1185 // We can pursue this problem in that order: trace back through copies,
1186 // optionally through a physical register, to a defining instruction. We
1187 // should never move from physreg to vreg. As we're still in SSA form, no need
1188 // to worry about partial definitions of registers.
1189
1190 // Helper lambda to interpret a copy-like instruction. Takes instruction,
1191 // returns the register read and any subregister identifying which part is
1192 // read.
1193 auto GetRegAndSubreg =
1194 [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1195 Register NewReg, OldReg;
1196 unsigned SubReg;
1197 if (Cpy.isCopy()) {
1198 OldReg = Cpy.getOperand(i: 0).getReg();
1199 NewReg = Cpy.getOperand(i: 1).getReg();
1200 SubReg = Cpy.getOperand(i: 1).getSubReg();
1201 } else if (Cpy.isSubregToReg()) {
1202 OldReg = Cpy.getOperand(i: 0).getReg();
1203 NewReg = Cpy.getOperand(i: 1).getReg();
1204 SubReg = Cpy.getOperand(i: 2).getImm();
1205 } else {
1206 auto CopyDetails = *TII.isCopyInstr(MI: Cpy);
1207 const MachineOperand &Src = *CopyDetails.Source;
1208 const MachineOperand &Dest = *CopyDetails.Destination;
1209 OldReg = Dest.getReg();
1210 NewReg = Src.getReg();
1211 SubReg = Src.getSubReg();
1212 }
1213
1214 return {NewReg, SubReg};
1215 };
1216
1217 // First seek either the defining instruction, or a copy from a physreg.
1218 // During search, the current state is the current copy instruction, and which
1219 // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1220 // deal with those later.
1221 auto State = GetRegAndSubreg(MI);
1222 auto CurInst = MI.getIterator();
1223 SmallVector<unsigned, 4> SubregsSeen;
1224 while (true) {
1225 // If we've found a copy from a physreg, first portion of search is over.
1226 if (!State.first.isVirtual())
1227 break;
1228
1229 // Record any subregister qualifier.
1230 if (State.second)
1231 SubregsSeen.push_back(Elt: State.second);
1232
1233 MachineInstr *Inst = MRI.getVRegDef(Reg: State.first);
1234 assert(Inst && "Virtual register has no def");
1235 CurInst = Inst->getIterator();
1236
1237 // Any non-copy instruction is the defining instruction we're seeking.
1238 if (!Inst->isCopyLike() && !TII.isCopyLikeInstr(MI: *Inst))
1239 break;
1240 State = GetRegAndSubreg(*Inst);
1241 };
1242
1243 // Helper lambda to apply additional subregister substitutions to a known
1244 // instruction/operand pair. Adds new (fake) substitutions so that we can
1245 // record the subregister. FIXME: this isn't very space efficient if multiple
1246 // values are tracked back through the same copies; cache something later.
1247 auto ApplySubregisters =
1248 [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1249 for (unsigned Subreg : reverse(C&: SubregsSeen)) {
1250 // Fetch a new instruction number, not attached to an actual instruction.
1251 unsigned NewInstrNumber = getNewDebugInstrNum();
1252 // Add a substitution from the "new" number to the known one, with a
1253 // qualifying subreg.
1254 makeDebugValueSubstitution(A: {NewInstrNumber, 0}, B: P, Subreg);
1255 // Return the new number; to find the underlying value, consumers need to
1256 // deal with the qualifying subreg.
1257 P = {NewInstrNumber, 0};
1258 }
1259 return P;
1260 };
1261
1262 // If we managed to find the defining instruction after COPYs, return an
1263 // instruction / operand pair after adding subregister qualifiers.
1264 if (State.first.isVirtual()) {
1265 // Virtual register def -- we can just look up where this happens.
1266 MachineInstr *Inst = MRI.getVRegDef(Reg: State.first);
1267 for (auto &MO : Inst->all_defs()) {
1268 if (MO.getReg() != State.first)
1269 continue;
1270 return ApplySubregisters({Inst->getDebugInstrNum(), MO.getOperandNo()});
1271 }
1272
1273 llvm_unreachable("Vreg def with no corresponding operand?");
1274 }
1275
1276 // Our search ended in a copy from a physreg: walk back up the function
1277 // looking for whatever defines the physreg.
1278 assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1279 State = GetRegAndSubreg(*CurInst);
1280 Register RegToSeek = State.first;
1281
1282 auto RMII = CurInst->getReverseIterator();
1283 auto PrevInstrs = make_range(x: RMII, y: CurInst->getParent()->instr_rend());
1284 for (auto &ToExamine : PrevInstrs) {
1285 for (auto &MO : ToExamine.all_defs()) {
1286 // Test for operand that defines something aliasing RegToSeek.
1287 if (!TRI.regsOverlap(RegA: RegToSeek, RegB: MO.getReg()))
1288 continue;
1289
1290 return ApplySubregisters(
1291 {ToExamine.getDebugInstrNum(), MO.getOperandNo()});
1292 }
1293 }
1294
1295 MachineBasicBlock &InsertBB = *CurInst->getParent();
1296
1297 // We reached the start of the block before finding a defining instruction.
1298 // There are numerous scenarios where this can happen:
1299 // * Constant physical registers,
1300 // * Several intrinsics that allow LLVM-IR to read arbitary registers,
1301 // * Arguments in the entry block,
1302 // * Exception handling landing pads.
1303 // Validating all of them is too difficult, so just insert a DBG_PHI reading
1304 // the variable value at this position, rather than checking it makes sense.
1305
1306 // Create DBG_PHI for specified physreg.
1307 auto Builder = BuildMI(BB&: InsertBB, I: InsertBB.getFirstNonPHI(), MIMD: DebugLoc(),
1308 MCID: TII.get(Opcode: TargetOpcode::DBG_PHI));
1309 Builder.addReg(RegNo: State.first);
1310 unsigned NewNum = getNewDebugInstrNum();
1311 Builder.addImm(Val: NewNum);
1312 return ApplySubregisters({NewNum, 0u});
1313}
1314
1315void MachineFunction::finalizeDebugInstrRefs() {
1316 auto *TII = getSubtarget().getInstrInfo();
1317
1318 auto MakeUndefDbgValue = [&](MachineInstr &MI) {
1319 const MCInstrDesc &RefII = TII->get(Opcode: TargetOpcode::DBG_VALUE_LIST);
1320 MI.setDesc(RefII);
1321 MI.setDebugValueUndef();
1322 };
1323
1324 DenseMap<Register, DebugInstrOperandPair> ArgDbgPHIs;
1325 for (auto &MBB : *this) {
1326 for (auto &MI : MBB) {
1327 if (!MI.isDebugRef())
1328 continue;
1329
1330 bool IsValidRef = true;
1331
1332 for (MachineOperand &MO : MI.debug_operands()) {
1333 if (!MO.isReg())
1334 continue;
1335
1336 Register Reg = MO.getReg();
1337
1338 // Some vregs can be deleted as redundant in the meantime. Mark those
1339 // as DBG_VALUE $noreg. Additionally, some normal instructions are
1340 // quickly deleted, leaving dangling references to vregs with no def.
1341 if (Reg == 0 || !RegInfo->hasOneDef(RegNo: Reg)) {
1342 IsValidRef = false;
1343 break;
1344 }
1345
1346 assert(Reg.isVirtual());
1347 MachineInstr &DefMI = *RegInfo->def_instr_begin(RegNo: Reg);
1348
1349 // If we've found a copy-like instruction, follow it back to the
1350 // instruction that defines the source value, see salvageCopySSA docs
1351 // for why this is important.
1352 if (DefMI.isCopyLike() || TII->isCopyInstr(MI: DefMI)) {
1353 auto Result = salvageCopySSA(MI&: DefMI, DbgPHICache&: ArgDbgPHIs);
1354 MO.ChangeToDbgInstrRef(InstrIdx: Result.first, OpIdx: Result.second);
1355 } else {
1356 // Otherwise, identify the operand number that the VReg refers to.
1357 unsigned OperandIdx = 0;
1358 for (const auto &DefMO : DefMI.operands()) {
1359 if (DefMO.isReg() && DefMO.isDef() && DefMO.getReg() == Reg)
1360 break;
1361 ++OperandIdx;
1362 }
1363 assert(OperandIdx < DefMI.getNumOperands());
1364
1365 // Morph this instr ref to point at the given instruction and operand.
1366 unsigned ID = DefMI.getDebugInstrNum();
1367 MO.ChangeToDbgInstrRef(InstrIdx: ID, OpIdx: OperandIdx);
1368 }
1369 }
1370
1371 if (!IsValidRef)
1372 MakeUndefDbgValue(MI);
1373 }
1374 }
1375}
1376
1377bool MachineFunction::shouldUseDebugInstrRef() const {
1378 // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1379 // have optimized code inlined into this unoptimized code, however with
1380 // fewer and less aggressive optimizations happening, coverage and accuracy
1381 // should not suffer.
1382 if (getTarget().getOptLevel() == CodeGenOptLevel::None)
1383 return false;
1384
1385 // Don't use instr-ref if this function is marked optnone.
1386 if (F.hasFnAttribute(Kind: Attribute::OptimizeNone))
1387 return false;
1388
1389 if (llvm::debuginfoShouldUseDebugInstrRef(T: getTarget().getTargetTriple()))
1390 return true;
1391
1392 return false;
1393}
1394
1395bool MachineFunction::useDebugInstrRef() const {
1396 return UseDebugInstrRef;
1397}
1398
1399void MachineFunction::setUseDebugInstrRef(bool Use) {
1400 UseDebugInstrRef = Use;
1401}
1402
1403// Use one million as a high / reserved number.
1404const unsigned MachineFunction::DebugOperandMemNumber = 1000000;
1405
1406/// \}
1407
1408//===----------------------------------------------------------------------===//
1409// MachineJumpTableInfo implementation
1410//===----------------------------------------------------------------------===//
1411
1412MachineJumpTableEntry::MachineJumpTableEntry(
1413 const std::vector<MachineBasicBlock *> &MBBs)
1414 : MBBs(MBBs), Hotness(MachineFunctionDataHotness::Unknown) {}
1415
1416/// Return the size of each entry in the jump table.
1417unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
1418 // The size of a jump table entry is 4 bytes unless the entry is just the
1419 // address of a block, in which case it is the pointer size.
1420 switch (getEntryKind()) {
1421 case MachineJumpTableInfo::EK_BlockAddress:
1422 return TD.getPointerSize();
1423 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1424 case MachineJumpTableInfo::EK_LabelDifference64:
1425 return 8;
1426 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1427 case MachineJumpTableInfo::EK_LabelDifference32:
1428 case MachineJumpTableInfo::EK_Custom32:
1429 return 4;
1430 case MachineJumpTableInfo::EK_Inline:
1431 return 0;
1432 }
1433 llvm_unreachable("Unknown jump table encoding!");
1434}
1435
1436/// Return the alignment of each entry in the jump table.
1437unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
1438 // The alignment of a jump table entry is the alignment of int32 unless the
1439 // entry is just the address of a block, in which case it is the pointer
1440 // alignment.
1441 switch (getEntryKind()) {
1442 case MachineJumpTableInfo::EK_BlockAddress:
1443 return TD.getPointerABIAlignment(AS: 0).value();
1444 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1445 case MachineJumpTableInfo::EK_LabelDifference64:
1446 return TD.getABIIntegerTypeAlignment(BitWidth: 64).value();
1447 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1448 case MachineJumpTableInfo::EK_LabelDifference32:
1449 case MachineJumpTableInfo::EK_Custom32:
1450 return TD.getABIIntegerTypeAlignment(BitWidth: 32).value();
1451 case MachineJumpTableInfo::EK_Inline:
1452 return 1;
1453 }
1454 llvm_unreachable("Unknown jump table encoding!");
1455}
1456
1457/// Create a new jump table entry in the jump table info.
1458unsigned MachineJumpTableInfo::createJumpTableIndex(
1459 const std::vector<MachineBasicBlock*> &DestBBs) {
1460 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1461 JumpTables.push_back(x: MachineJumpTableEntry(DestBBs));
1462 return JumpTables.size()-1;
1463}
1464
1465bool MachineJumpTableInfo::updateJumpTableEntryHotness(
1466 size_t JTI, MachineFunctionDataHotness Hotness) {
1467 assert(JTI < JumpTables.size() && "Invalid JTI!");
1468 // Record the largest hotness value.
1469 if (Hotness <= JumpTables[JTI].Hotness)
1470 return false;
1471
1472 JumpTables[JTI].Hotness = Hotness;
1473 return true;
1474}
1475
1476/// If Old is the target of any jump tables, update the jump tables to branch
1477/// to New instead.
1478bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1479 MachineBasicBlock *New) {
1480 assert(Old != New && "Not making a change?");
1481 bool MadeChange = false;
1482 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1483 ReplaceMBBInJumpTable(Idx: i, Old, New);
1484 return MadeChange;
1485}
1486
1487/// If MBB is present in any jump tables, remove it.
1488bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1489 bool MadeChange = false;
1490 for (MachineJumpTableEntry &JTE : JumpTables) {
1491 auto removeBeginItr = std::remove(first: JTE.MBBs.begin(), last: JTE.MBBs.end(), value: MBB);
1492 MadeChange |= (removeBeginItr != JTE.MBBs.end());
1493 JTE.MBBs.erase(first: removeBeginItr, last: JTE.MBBs.end());
1494 }
1495 return MadeChange;
1496}
1497
1498/// If Old is a target of the jump tables, update the jump table to branch to
1499/// New instead.
1500bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1501 MachineBasicBlock *Old,
1502 MachineBasicBlock *New) {
1503 assert(Old != New && "Not making a change?");
1504 bool MadeChange = false;
1505 MachineJumpTableEntry &JTE = JumpTables[Idx];
1506 for (MachineBasicBlock *&MBB : JTE.MBBs)
1507 if (MBB == Old) {
1508 MBB = New;
1509 MadeChange = true;
1510 }
1511 return MadeChange;
1512}
1513
1514void MachineJumpTableInfo::print(raw_ostream &OS) const {
1515 if (JumpTables.empty()) return;
1516
1517 OS << "Jump Tables:\n";
1518
1519 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1520 OS << printJumpTableEntryReference(Idx: i) << ':';
1521 for (const MachineBasicBlock *MBB : JumpTables[i].MBBs)
1522 OS << ' ' << printMBBReference(MBB: *MBB);
1523 OS << '\n';
1524 }
1525
1526 OS << '\n';
1527}
1528
1529#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1530LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1531#endif
1532
1533Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1534 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1535}
1536
1537//===----------------------------------------------------------------------===//
1538// MachineConstantPool implementation
1539//===----------------------------------------------------------------------===//
1540
1541void MachineConstantPoolValue::anchor() {}
1542
1543unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1544 return DL.getTypeAllocSize(Ty);
1545}
1546
1547unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
1548 if (isMachineConstantPoolEntry())
1549 return Val.MachineCPVal->getSizeInBytes(DL);
1550 return DL.getTypeAllocSize(Ty: Val.ConstVal->getType());
1551}
1552
1553bool MachineConstantPoolEntry::needsRelocation() const {
1554 if (isMachineConstantPoolEntry())
1555 return true;
1556 return Val.ConstVal->needsDynamicRelocation();
1557}
1558
1559SectionKind
1560MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1561 if (needsRelocation())
1562 return SectionKind::getReadOnlyWithRel();
1563 switch (getSizeInBytes(DL: *DL)) {
1564 case 4:
1565 return SectionKind::getMergeableConst4();
1566 case 8:
1567 return SectionKind::getMergeableConst8();
1568 case 16:
1569 return SectionKind::getMergeableConst16();
1570 case 32:
1571 return SectionKind::getMergeableConst32();
1572 default:
1573 return SectionKind::getReadOnly();
1574 }
1575}
1576
1577MachineConstantPool::~MachineConstantPool() {
1578 // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1579 // so keep track of which we've deleted to avoid double deletions.
1580 DenseSet<MachineConstantPoolValue*> Deleted;
1581 for (const MachineConstantPoolEntry &C : Constants)
1582 if (C.isMachineConstantPoolEntry()) {
1583 Deleted.insert(V: C.Val.MachineCPVal);
1584 delete C.Val.MachineCPVal;
1585 }
1586 for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1587 if (Deleted.count(V: CPV) == 0)
1588 delete CPV;
1589 }
1590}
1591
1592/// Test whether the given two constants can be allocated the same constant pool
1593/// entry referenced by \param A.
1594static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1595 const DataLayout &DL) {
1596 // Handle the trivial case quickly.
1597 if (A == B) return true;
1598
1599 // If they have the same type but weren't the same constant, quickly
1600 // reject them.
1601 if (A->getType() == B->getType()) return false;
1602
1603 // We can't handle structs or arrays.
1604 if (isa<StructType>(Val: A->getType()) || isa<ArrayType>(Val: A->getType()) ||
1605 isa<StructType>(Val: B->getType()) || isa<ArrayType>(Val: B->getType()))
1606 return false;
1607
1608 // For now, only support constants with the same size.
1609 uint64_t StoreSize = DL.getTypeStoreSize(Ty: A->getType());
1610 if (StoreSize != DL.getTypeStoreSize(Ty: B->getType()) || StoreSize > 128)
1611 return false;
1612
1613 bool ContainsUndefOrPoisonA = A->containsUndefOrPoisonElement();
1614
1615 Type *IntTy = IntegerType::get(C&: A->getContext(), NumBits: StoreSize*8);
1616
1617 // Try constant folding a bitcast of both instructions to an integer. If we
1618 // get two identical ConstantInt's, then we are good to share them. We use
1619 // the constant folding APIs to do this so that we get the benefit of
1620 // DataLayout.
1621 if (isa<PointerType>(Val: A->getType()))
1622 A = ConstantFoldCastOperand(Opcode: Instruction::PtrToInt,
1623 C: const_cast<Constant *>(A), DestTy: IntTy, DL);
1624 else if (A->getType() != IntTy)
1625 A = ConstantFoldCastOperand(Opcode: Instruction::BitCast, C: const_cast<Constant *>(A),
1626 DestTy: IntTy, DL);
1627 if (isa<PointerType>(Val: B->getType()))
1628 B = ConstantFoldCastOperand(Opcode: Instruction::PtrToInt,
1629 C: const_cast<Constant *>(B), DestTy: IntTy, DL);
1630 else if (B->getType() != IntTy)
1631 B = ConstantFoldCastOperand(Opcode: Instruction::BitCast, C: const_cast<Constant *>(B),
1632 DestTy: IntTy, DL);
1633
1634 if (A != B)
1635 return false;
1636
1637 // Constants only safely match if A doesn't contain undef/poison.
1638 // As we'll be reusing A, it doesn't matter if B contain undef/poison.
1639 // TODO: Handle cases where A and B have the same undef/poison elements.
1640 // TODO: Merge A and B with mismatching undef/poison elements.
1641 return !ContainsUndefOrPoisonA;
1642}
1643
1644/// Create a new entry in the constant pool or return an existing one.
1645/// User must specify the log2 of the minimum required alignment for the object.
1646unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1647 Align Alignment) {
1648 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1649
1650 // Check to see if we already have this constant.
1651 //
1652 // FIXME, this could be made much more efficient for large constant pools.
1653 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1654 if (!Constants[i].isMachineConstantPoolEntry() &&
1655 CanShareConstantPoolEntry(A: Constants[i].Val.ConstVal, B: C, DL)) {
1656 if (Constants[i].getAlign() < Alignment)
1657 Constants[i].Alignment = Alignment;
1658 return i;
1659 }
1660
1661 Constants.push_back(x: MachineConstantPoolEntry(C, Alignment));
1662 return Constants.size()-1;
1663}
1664
1665unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1666 Align Alignment) {
1667 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1668
1669 // Check to see if we already have this constant.
1670 //
1671 // FIXME, this could be made much more efficient for large constant pools.
1672 int Idx = V->getExistingMachineCPValue(CP: this, Alignment);
1673 if (Idx != -1) {
1674 MachineCPVsSharingEntries.insert(V);
1675 return (unsigned)Idx;
1676 }
1677
1678 Constants.push_back(x: MachineConstantPoolEntry(V, Alignment));
1679 return Constants.size()-1;
1680}
1681
1682void MachineConstantPool::print(raw_ostream &OS) const {
1683 if (Constants.empty()) return;
1684
1685 OS << "Constant Pool:\n";
1686 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1687 OS << " cp#" << i << ": ";
1688 if (Constants[i].isMachineConstantPoolEntry())
1689 Constants[i].Val.MachineCPVal->print(O&: OS);
1690 else
1691 Constants[i].Val.ConstVal->printAsOperand(O&: OS);
1692 OS << ", align=" << Constants[i].getAlign().value();
1693 OS << "\n";
1694 }
1695}
1696
1697//===----------------------------------------------------------------------===//
1698// Template specialization for MachineFunction implementation of
1699// ProfileSummaryInfo::getEntryCount().
1700//===----------------------------------------------------------------------===//
1701template <>
1702std::optional<uint64_t>
1703ProfileSummaryInfo::getEntryCount<llvm::MachineFunction>(
1704 const llvm::MachineFunction *F) const {
1705 return F->getFunction().getEntryCount();
1706}
1707
1708#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1709LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1710#endif
1711