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

source code of llvm/lib/CodeGen/MachineFunction.cpp