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