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