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