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