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