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