xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision 36deb9a670d06fc254df2f357ae595fb8f817d07)
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 (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
750              II != IE; ++II)
751           FilterList.push_back(cast<GlobalValue>((*II)->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   DebugValueSubstitutions.push_back({A, B, Subreg});
978 }
979 
980 void MachineFunction::substituteDebugValuesForInst(const MachineInstr &Old,
981                                                    MachineInstr &New,
982                                                    unsigned MaxOperand) {
983   // If the Old instruction wasn't tracked at all, there is no work to do.
984   unsigned OldInstrNum = Old.peekDebugInstrNum();
985   if (!OldInstrNum)
986     return;
987 
988   // Iterate over all operands looking for defs to create substitutions for.
989   // Avoid creating new instr numbers unless we create a new substitution.
990   // While this has no functional effect, it risks confusing someone reading
991   // MIR output.
992   // Examine all the operands, or the first N specified by the caller.
993   MaxOperand = std::min(MaxOperand, Old.getNumOperands());
994   for (unsigned int I = 0; I < MaxOperand; ++I) {
995     const auto &OldMO = Old.getOperand(I);
996     auto &NewMO = New.getOperand(I);
997     (void)NewMO;
998 
999     if (!OldMO.isReg() || !OldMO.isDef())
1000       continue;
1001     assert(NewMO.isDef());
1002 
1003     unsigned NewInstrNum = New.getDebugInstrNum();
1004     makeDebugValueSubstitution(std::make_pair(OldInstrNum, I),
1005                                std::make_pair(NewInstrNum, I));
1006   }
1007 }
1008 
1009 auto MachineFunction::salvageCopySSA(MachineInstr &MI)
1010     -> DebugInstrOperandPair {
1011   MachineRegisterInfo &MRI = getRegInfo();
1012   const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
1013   const TargetInstrInfo &TII = *getSubtarget().getInstrInfo();
1014 
1015   // Chase the value read by a copy-like instruction back to the instruction
1016   // that ultimately _defines_ that value. This may pass:
1017   //  * Through multiple intermediate copies, including subregister moves /
1018   //    copies,
1019   //  * Copies from physical registers that must then be traced back to the
1020   //    defining instruction,
1021   //  * Or, physical registers may be live-in to (only) the entry block, which
1022   //    requires a DBG_PHI to be created.
1023   // We can pursue this problem in that order: trace back through copies,
1024   // optionally through a physical register, to a defining instruction. We
1025   // should never move from physreg to vreg. As we're still in SSA form, no need
1026   // to worry about partial definitions of registers.
1027 
1028   // Helper lambda to interpret a copy-like instruction. Takes instruction,
1029   // returns the register read and any subregister identifying which part is
1030   // read.
1031   auto GetRegAndSubreg =
1032       [&](const MachineInstr &Cpy) -> std::pair<Register, unsigned> {
1033     Register NewReg, OldReg;
1034     unsigned SubReg;
1035     if (Cpy.isCopy()) {
1036       OldReg = Cpy.getOperand(0).getReg();
1037       NewReg = Cpy.getOperand(1).getReg();
1038       SubReg = Cpy.getOperand(1).getSubReg();
1039     } else if (Cpy.isSubregToReg()) {
1040       OldReg = Cpy.getOperand(0).getReg();
1041       NewReg = Cpy.getOperand(2).getReg();
1042       SubReg = Cpy.getOperand(3).getImm();
1043     } else {
1044       auto CopyDetails = *TII.isCopyInstr(Cpy);
1045       const MachineOperand &Src = *CopyDetails.Source;
1046       const MachineOperand &Dest = *CopyDetails.Destination;
1047       OldReg = Dest.getReg();
1048       NewReg = Src.getReg();
1049       SubReg = Src.getSubReg();
1050     }
1051 
1052     return {NewReg, SubReg};
1053   };
1054 
1055   // First seek either the defining instruction, or a copy from a physreg.
1056   // During search, the current state is the current copy instruction, and which
1057   // register we've read. Accumulate qualifying subregisters into SubregsSeen;
1058   // deal with those later.
1059   auto State = GetRegAndSubreg(MI);
1060   auto CurInst = MI.getIterator();
1061   SmallVector<unsigned, 4> SubregsSeen;
1062   while (true) {
1063     // If we've found a copy from a physreg, first portion of search is over.
1064     if (!State.first.isVirtual())
1065       break;
1066 
1067     // Record any subregister qualifier.
1068     if (State.second)
1069       SubregsSeen.push_back(State.second);
1070 
1071     assert(MRI.hasOneDef(State.first));
1072     MachineInstr &Inst = *MRI.def_begin(State.first)->getParent();
1073     CurInst = Inst.getIterator();
1074 
1075     // Any non-copy instruction is the defining instruction we're seeking.
1076     if (!Inst.isCopyLike() && !TII.isCopyInstr(Inst))
1077       break;
1078     State = GetRegAndSubreg(Inst);
1079   };
1080 
1081   // Helper lambda to apply additional subregister substitutions to a known
1082   // instruction/operand pair. Adds new (fake) substitutions so that we can
1083   // record the subregister. FIXME: this isn't very space efficient if multiple
1084   // values are tracked back through the same copies; cache something later.
1085   auto ApplySubregisters =
1086       [&](DebugInstrOperandPair P) -> DebugInstrOperandPair {
1087     for (unsigned Subreg : reverse(SubregsSeen)) {
1088       // Fetch a new instruction number, not attached to an actual instruction.
1089       unsigned NewInstrNumber = getNewDebugInstrNum();
1090       // Add a substitution from the "new" number to the known one, with a
1091       // qualifying subreg.
1092       makeDebugValueSubstitution({NewInstrNumber, 0}, P, Subreg);
1093       // Return the new number; to find the underlying value, consumers need to
1094       // deal with the qualifying subreg.
1095       P = {NewInstrNumber, 0};
1096     }
1097     return P;
1098   };
1099 
1100   // If we managed to find the defining instruction after COPYs, return an
1101   // instruction / operand pair after adding subregister qualifiers.
1102   if (State.first.isVirtual()) {
1103     // Virtual register def -- we can just look up where this happens.
1104     MachineInstr *Inst = MRI.def_begin(State.first)->getParent();
1105     for (auto &MO : Inst->operands()) {
1106       if (!MO.isReg() || !MO.isDef() || MO.getReg() != State.first)
1107         continue;
1108       return ApplySubregisters(
1109           {Inst->getDebugInstrNum(), Inst->getOperandNo(&MO)});
1110     }
1111 
1112     llvm_unreachable("Vreg def with no corresponding operand?");
1113   }
1114 
1115   // Our search ended in a copy from a physreg: walk back up the function
1116   // looking for whatever defines the physreg.
1117   assert(CurInst->isCopyLike() || TII.isCopyInstr(*CurInst));
1118   State = GetRegAndSubreg(*CurInst);
1119   Register RegToSeek = State.first;
1120 
1121   auto RMII = CurInst->getReverseIterator();
1122   auto PrevInstrs = make_range(RMII, CurInst->getParent()->instr_rend());
1123   for (auto &ToExamine : PrevInstrs) {
1124     for (auto &MO : ToExamine.operands()) {
1125       // Test for operand that defines something aliasing RegToSeek.
1126       if (!MO.isReg() || !MO.isDef() ||
1127           !TRI.regsOverlap(RegToSeek, MO.getReg()))
1128         continue;
1129 
1130       return ApplySubregisters(
1131           {ToExamine.getDebugInstrNum(), ToExamine.getOperandNo(&MO)});
1132     }
1133   }
1134 
1135   MachineBasicBlock &InsertBB = *CurInst->getParent();
1136 
1137   // We reached the start of the block before finding a defining instruction.
1138   // It could be from a constant register, otherwise it must be an argument.
1139   if (TRI.isConstantPhysReg(State.first)) {
1140     // We can produce a DBG_PHI that identifies the constant physreg. Doesn't
1141     // matter where we put it, as it's constant valued.
1142     assert(CurInst->isCopy());
1143   } else if (State.first == TRI.getFrameRegister(*this)) {
1144     // LLVM IR is allowed to read the framepointer by calling a
1145     // llvm.frameaddress.* intrinsic. We can support this by emitting a
1146     // DBG_PHI $fp. This isn't ideal, because it extends the behaviours /
1147     // position that DBG_PHIs appear at, limiting what can be done later.
1148     // TODO: see if there's a better way of expressing these variable
1149     // locations.
1150     ;
1151   } else {
1152     // Assert that this is the entry block, or an EH pad. If it isn't, then
1153     // there is some code construct we don't recognise that deals with physregs
1154     // across blocks.
1155     assert(!State.first.isVirtual());
1156     assert(&*InsertBB.getParent()->begin() == &InsertBB || InsertBB.isEHPad());
1157   }
1158 
1159   // Create DBG_PHI for specified physreg.
1160   auto Builder = BuildMI(InsertBB, InsertBB.getFirstNonPHI(), DebugLoc(),
1161                          TII.get(TargetOpcode::DBG_PHI));
1162   Builder.addReg(State.first);
1163   unsigned NewNum = getNewDebugInstrNum();
1164   Builder.addImm(NewNum);
1165   return ApplySubregisters({NewNum, 0u});
1166 }
1167 
1168 void MachineFunction::finalizeDebugInstrRefs() {
1169   auto *TII = getSubtarget().getInstrInfo();
1170 
1171   auto MakeDbgValue = [&](MachineInstr &MI) {
1172     const MCInstrDesc &RefII = TII->get(TargetOpcode::DBG_VALUE);
1173     MI.setDesc(RefII);
1174     MI.getOperand(1).ChangeToRegister(0, false);
1175   };
1176 
1177   if (!useDebugInstrRef())
1178     return;
1179 
1180   for (auto &MBB : *this) {
1181     for (auto &MI : MBB) {
1182       if (!MI.isDebugRef() || !MI.getOperand(0).isReg())
1183         continue;
1184 
1185       Register Reg = MI.getOperand(0).getReg();
1186 
1187       // Some vregs can be deleted as redundant in the meantime. Mark those
1188       // as DBG_VALUE $noreg.
1189       if (Reg == 0) {
1190         MakeDbgValue(MI);
1191         continue;
1192       }
1193 
1194       assert(Reg.isVirtual());
1195       MachineInstr &DefMI = *RegInfo->def_instr_begin(Reg);
1196       assert(RegInfo->hasOneDef(Reg));
1197 
1198       // If we've found a copy-like instruction, follow it back to the
1199       // instruction that defines the source value, see salvageCopySSA docs
1200       // for why this is important.
1201       if (DefMI.isCopyLike() || TII->isCopyInstr(DefMI)) {
1202         auto Result = salvageCopySSA(DefMI);
1203         MI.getOperand(0).ChangeToImmediate(Result.first);
1204         MI.getOperand(1).setImm(Result.second);
1205       } else {
1206         // Otherwise, identify the operand number that the VReg refers to.
1207         unsigned OperandIdx = 0;
1208         for (const auto &MO : DefMI.operands()) {
1209           if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
1210             break;
1211           ++OperandIdx;
1212         }
1213         assert(OperandIdx < DefMI.getNumOperands());
1214 
1215         // Morph this instr ref to point at the given instruction and operand.
1216         unsigned ID = DefMI.getDebugInstrNum();
1217         MI.getOperand(0).ChangeToImmediate(ID);
1218         MI.getOperand(1).setImm(OperandIdx);
1219       }
1220     }
1221   }
1222 }
1223 
1224 bool MachineFunction::useDebugInstrRef() const {
1225   // Disable instr-ref at -O0: it's very slow (in compile time). We can still
1226   // have optimized code inlined into this unoptimized code, however with
1227   // fewer and less aggressive optimizations happening, coverage and accuracy
1228   // should not suffer.
1229   if (getTarget().getOptLevel() == CodeGenOpt::None)
1230     return false;
1231 
1232   // Don't use instr-ref if this function is marked optnone.
1233   if (F.hasFnAttribute(Attribute::OptimizeNone))
1234     return false;
1235 
1236   if (getTarget().Options.ValueTrackingVariableLocations)
1237     return true;
1238 
1239   return false;
1240 }
1241 
1242 /// \}
1243 
1244 //===----------------------------------------------------------------------===//
1245 //  MachineJumpTableInfo implementation
1246 //===----------------------------------------------------------------------===//
1247 
1248 /// Return the size of each entry in the jump table.
1249 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
1250   // The size of a jump table entry is 4 bytes unless the entry is just the
1251   // address of a block, in which case it is the pointer size.
1252   switch (getEntryKind()) {
1253   case MachineJumpTableInfo::EK_BlockAddress:
1254     return TD.getPointerSize();
1255   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1256     return 8;
1257   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1258   case MachineJumpTableInfo::EK_LabelDifference32:
1259   case MachineJumpTableInfo::EK_Custom32:
1260     return 4;
1261   case MachineJumpTableInfo::EK_Inline:
1262     return 0;
1263   }
1264   llvm_unreachable("Unknown jump table encoding!");
1265 }
1266 
1267 /// Return the alignment of each entry in the jump table.
1268 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
1269   // The alignment of a jump table entry is the alignment of int32 unless the
1270   // entry is just the address of a block, in which case it is the pointer
1271   // alignment.
1272   switch (getEntryKind()) {
1273   case MachineJumpTableInfo::EK_BlockAddress:
1274     return TD.getPointerABIAlignment(0).value();
1275   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1276     return TD.getABIIntegerTypeAlignment(64).value();
1277   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1278   case MachineJumpTableInfo::EK_LabelDifference32:
1279   case MachineJumpTableInfo::EK_Custom32:
1280     return TD.getABIIntegerTypeAlignment(32).value();
1281   case MachineJumpTableInfo::EK_Inline:
1282     return 1;
1283   }
1284   llvm_unreachable("Unknown jump table encoding!");
1285 }
1286 
1287 /// Create a new jump table entry in the jump table info.
1288 unsigned MachineJumpTableInfo::createJumpTableIndex(
1289                                const std::vector<MachineBasicBlock*> &DestBBs) {
1290   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1291   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1292   return JumpTables.size()-1;
1293 }
1294 
1295 /// If Old is the target of any jump tables, update the jump tables to branch
1296 /// to New instead.
1297 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1298                                                   MachineBasicBlock *New) {
1299   assert(Old != New && "Not making a change?");
1300   bool MadeChange = false;
1301   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1302     ReplaceMBBInJumpTable(i, Old, New);
1303   return MadeChange;
1304 }
1305 
1306 /// If MBB is present in any jump tables, remove it.
1307 bool MachineJumpTableInfo::RemoveMBBFromJumpTables(MachineBasicBlock *MBB) {
1308   bool MadeChange = false;
1309   for (MachineJumpTableEntry &JTE : JumpTables) {
1310     auto removeBeginItr = std::remove(JTE.MBBs.begin(), JTE.MBBs.end(), MBB);
1311     MadeChange |= (removeBeginItr != JTE.MBBs.end());
1312     JTE.MBBs.erase(removeBeginItr, JTE.MBBs.end());
1313   }
1314   return MadeChange;
1315 }
1316 
1317 /// If Old is a target of the jump tables, update the jump table to branch to
1318 /// New instead.
1319 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1320                                                  MachineBasicBlock *Old,
1321                                                  MachineBasicBlock *New) {
1322   assert(Old != New && "Not making a change?");
1323   bool MadeChange = false;
1324   MachineJumpTableEntry &JTE = JumpTables[Idx];
1325   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
1326     if (JTE.MBBs[j] == Old) {
1327       JTE.MBBs[j] = New;
1328       MadeChange = true;
1329     }
1330   return MadeChange;
1331 }
1332 
1333 void MachineJumpTableInfo::print(raw_ostream &OS) const {
1334   if (JumpTables.empty()) return;
1335 
1336   OS << "Jump Tables:\n";
1337 
1338   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1339     OS << printJumpTableEntryReference(i) << ':';
1340     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
1341       OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
1342     if (i != e)
1343       OS << '\n';
1344   }
1345 
1346   OS << '\n';
1347 }
1348 
1349 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1350 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1351 #endif
1352 
1353 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1354   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1355 }
1356 
1357 //===----------------------------------------------------------------------===//
1358 //  MachineConstantPool implementation
1359 //===----------------------------------------------------------------------===//
1360 
1361 void MachineConstantPoolValue::anchor() {}
1362 
1363 unsigned MachineConstantPoolValue::getSizeInBytes(const DataLayout &DL) const {
1364   return DL.getTypeAllocSize(Ty);
1365 }
1366 
1367 unsigned MachineConstantPoolEntry::getSizeInBytes(const DataLayout &DL) const {
1368   if (isMachineConstantPoolEntry())
1369     return Val.MachineCPVal->getSizeInBytes(DL);
1370   return DL.getTypeAllocSize(Val.ConstVal->getType());
1371 }
1372 
1373 bool MachineConstantPoolEntry::needsRelocation() const {
1374   if (isMachineConstantPoolEntry())
1375     return true;
1376   return Val.ConstVal->needsDynamicRelocation();
1377 }
1378 
1379 SectionKind
1380 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1381   if (needsRelocation())
1382     return SectionKind::getReadOnlyWithRel();
1383   switch (getSizeInBytes(*DL)) {
1384   case 4:
1385     return SectionKind::getMergeableConst4();
1386   case 8:
1387     return SectionKind::getMergeableConst8();
1388   case 16:
1389     return SectionKind::getMergeableConst16();
1390   case 32:
1391     return SectionKind::getMergeableConst32();
1392   default:
1393     return SectionKind::getReadOnly();
1394   }
1395 }
1396 
1397 MachineConstantPool::~MachineConstantPool() {
1398   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1399   // so keep track of which we've deleted to avoid double deletions.
1400   DenseSet<MachineConstantPoolValue*> Deleted;
1401   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1402     if (Constants[i].isMachineConstantPoolEntry()) {
1403       Deleted.insert(Constants[i].Val.MachineCPVal);
1404       delete Constants[i].Val.MachineCPVal;
1405     }
1406   for (MachineConstantPoolValue *CPV : MachineCPVsSharingEntries) {
1407     if (Deleted.count(CPV) == 0)
1408       delete CPV;
1409   }
1410 }
1411 
1412 /// Test whether the given two constants can be allocated the same constant pool
1413 /// entry.
1414 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1415                                       const DataLayout &DL) {
1416   // Handle the trivial case quickly.
1417   if (A == B) return true;
1418 
1419   // If they have the same type but weren't the same constant, quickly
1420   // reject them.
1421   if (A->getType() == B->getType()) return false;
1422 
1423   // We can't handle structs or arrays.
1424   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1425       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1426     return false;
1427 
1428   // For now, only support constants with the same size.
1429   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1430   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1431     return false;
1432 
1433   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1434 
1435   // Try constant folding a bitcast of both instructions to an integer.  If we
1436   // get two identical ConstantInt's, then we are good to share them.  We use
1437   // the constant folding APIs to do this so that we get the benefit of
1438   // DataLayout.
1439   if (isa<PointerType>(A->getType()))
1440     A = ConstantFoldCastOperand(Instruction::PtrToInt,
1441                                 const_cast<Constant *>(A), IntTy, DL);
1442   else if (A->getType() != IntTy)
1443     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1444                                 IntTy, DL);
1445   if (isa<PointerType>(B->getType()))
1446     B = ConstantFoldCastOperand(Instruction::PtrToInt,
1447                                 const_cast<Constant *>(B), IntTy, DL);
1448   else if (B->getType() != IntTy)
1449     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1450                                 IntTy, DL);
1451 
1452   return A == B;
1453 }
1454 
1455 /// Create a new entry in the constant pool or return an existing one.
1456 /// User must specify the log2 of the minimum required alignment for the object.
1457 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1458                                                    Align Alignment) {
1459   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1460 
1461   // Check to see if we already have this constant.
1462   //
1463   // FIXME, this could be made much more efficient for large constant pools.
1464   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1465     if (!Constants[i].isMachineConstantPoolEntry() &&
1466         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1467       if (Constants[i].getAlign() < Alignment)
1468         Constants[i].Alignment = Alignment;
1469       return i;
1470     }
1471 
1472   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1473   return Constants.size()-1;
1474 }
1475 
1476 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1477                                                    Align Alignment) {
1478   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1479 
1480   // Check to see if we already have this constant.
1481   //
1482   // FIXME, this could be made much more efficient for large constant pools.
1483   int Idx = V->getExistingMachineCPValue(this, Alignment);
1484   if (Idx != -1) {
1485     MachineCPVsSharingEntries.insert(V);
1486     return (unsigned)Idx;
1487   }
1488 
1489   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1490   return Constants.size()-1;
1491 }
1492 
1493 void MachineConstantPool::print(raw_ostream &OS) const {
1494   if (Constants.empty()) return;
1495 
1496   OS << "Constant Pool:\n";
1497   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1498     OS << "  cp#" << i << ": ";
1499     if (Constants[i].isMachineConstantPoolEntry())
1500       Constants[i].Val.MachineCPVal->print(OS);
1501     else
1502       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1503     OS << ", align=" << Constants[i].getAlign().value();
1504     OS << "\n";
1505   }
1506 }
1507 
1508 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1509 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1510 #endif
1511