xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision df082ac45aa034b8b5194123035554a93ed6d38e)
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   }
102   llvm_unreachable("Invalid machine function property");
103 }
104 
105 // Pin the vtable to this file.
106 void MachineFunction::Delegate::anchor() {}
107 
108 void MachineFunctionProperties::print(raw_ostream &OS) const {
109   const char *Separator = "";
110   for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
111     if (!Properties[I])
112       continue;
113     OS << Separator << getPropertyName(static_cast<Property>(I));
114     Separator = ", ";
115   }
116 }
117 
118 //===----------------------------------------------------------------------===//
119 // MachineFunction implementation
120 //===----------------------------------------------------------------------===//
121 
122 // Out-of-line virtual method.
123 MachineFunctionInfo::~MachineFunctionInfo() = default;
124 
125 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
126   MBB->getParent()->DeleteMachineBasicBlock(MBB);
127 }
128 
129 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
130                                            const Function &F) {
131   if (F.hasFnAttribute(Attribute::StackAlignment))
132     return F.getFnStackAlignment();
133   return STI->getFrameLowering()->getStackAlignment();
134 }
135 
136 MachineFunction::MachineFunction(const Function &F,
137                                  const LLVMTargetMachine &Target,
138                                  const TargetSubtargetInfo &STI,
139                                  unsigned FunctionNum, MachineModuleInfo &mmi)
140     : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
141   FunctionNumber = FunctionNum;
142   init();
143 }
144 
145 void MachineFunction::handleInsertion(MachineInstr &MI) {
146   if (TheDelegate)
147     TheDelegate->MF_HandleInsertion(MI);
148 }
149 
150 void MachineFunction::handleRemoval(MachineInstr &MI) {
151   if (TheDelegate)
152     TheDelegate->MF_HandleRemoval(MI);
153 }
154 
155 void MachineFunction::init() {
156   // Assume the function starts in SSA form with correct liveness.
157   Properties.set(MachineFunctionProperties::Property::IsSSA);
158   Properties.set(MachineFunctionProperties::Property::TracksLiveness);
159   if (STI->getRegisterInfo())
160     RegInfo = new (Allocator) MachineRegisterInfo(this);
161   else
162     RegInfo = nullptr;
163 
164   MFInfo = nullptr;
165   // We can realign the stack if the target supports it and the user hasn't
166   // explicitly asked us not to.
167   bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
168                       !F.hasFnAttribute("no-realign-stack");
169   FrameInfo = new (Allocator) MachineFrameInfo(
170       getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
171       /*ForcedRealign=*/CanRealignSP &&
172           F.hasFnAttribute(Attribute::StackAlignment));
173 
174   if (F.hasFnAttribute(Attribute::StackAlignment))
175     FrameInfo->ensureMaxAlignment(F.getFnStackAlignment());
176 
177   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
178   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
179 
180   // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
181   // FIXME: Use Function::hasOptSize().
182   if (!F.hasFnAttribute(Attribute::OptimizeForSize))
183     Alignment = std::max(Alignment,
184                          STI->getTargetLowering()->getPrefFunctionAlignment());
185 
186   if (AlignAllFunctions)
187     Alignment = Align(1ULL << AlignAllFunctions);
188 
189   JumpTableInfo = nullptr;
190 
191   if (isFuncletEHPersonality(classifyEHPersonality(
192           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
193     WinEHInfo = new (Allocator) WinEHFuncInfo();
194   }
195 
196   if (isScopedEHPersonality(classifyEHPersonality(
197           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
198     WasmEHInfo = new (Allocator) WasmEHFuncInfo();
199   }
200 
201   assert(Target.isCompatibleDataLayout(getDataLayout()) &&
202          "Can't create a MachineFunction using a Module with a "
203          "Target-incompatible DataLayout attached\n");
204 
205   PSVManager =
206     std::make_unique<PseudoSourceValueManager>(*(getSubtarget().
207                                                   getInstrInfo()));
208 }
209 
210 MachineFunction::~MachineFunction() {
211   clear();
212 }
213 
214 void MachineFunction::clear() {
215   Properties.reset();
216   // Don't call destructors on MachineInstr and MachineOperand. All of their
217   // memory comes from the BumpPtrAllocator which is about to be purged.
218   //
219   // Do call MachineBasicBlock destructors, it contains std::vectors.
220   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
221     I->Insts.clearAndLeakNodesUnsafely();
222   MBBNumbering.clear();
223 
224   InstructionRecycler.clear(Allocator);
225   OperandRecycler.clear(Allocator);
226   BasicBlockRecycler.clear(Allocator);
227   CodeViewAnnotations.clear();
228   VariableDbgInfos.clear();
229   if (RegInfo) {
230     RegInfo->~MachineRegisterInfo();
231     Allocator.Deallocate(RegInfo);
232   }
233   if (MFInfo) {
234     MFInfo->~MachineFunctionInfo();
235     Allocator.Deallocate(MFInfo);
236   }
237 
238   FrameInfo->~MachineFrameInfo();
239   Allocator.Deallocate(FrameInfo);
240 
241   ConstantPool->~MachineConstantPool();
242   Allocator.Deallocate(ConstantPool);
243 
244   if (JumpTableInfo) {
245     JumpTableInfo->~MachineJumpTableInfo();
246     Allocator.Deallocate(JumpTableInfo);
247   }
248 
249   if (WinEHInfo) {
250     WinEHInfo->~WinEHFuncInfo();
251     Allocator.Deallocate(WinEHInfo);
252   }
253 
254   if (WasmEHInfo) {
255     WasmEHInfo->~WasmEHFuncInfo();
256     Allocator.Deallocate(WasmEHInfo);
257   }
258 }
259 
260 const DataLayout &MachineFunction::getDataLayout() const {
261   return F.getParent()->getDataLayout();
262 }
263 
264 /// Get the JumpTableInfo for this function.
265 /// If it does not already exist, allocate one.
266 MachineJumpTableInfo *MachineFunction::
267 getOrCreateJumpTableInfo(unsigned EntryKind) {
268   if (JumpTableInfo) return JumpTableInfo;
269 
270   JumpTableInfo = new (Allocator)
271     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
272   return JumpTableInfo;
273 }
274 
275 DenormalMode MachineFunction::getDenormalMode(const fltSemantics &FPType) const {
276   if (&FPType == &APFloat::IEEEsingle()) {
277     Attribute Attr = F.getFnAttribute("denormal-fp-math-f32");
278     StringRef Val = Attr.getValueAsString();
279     if (!Val.empty())
280       return parseDenormalFPAttribute(Val);
281 
282     // If the f32 variant of the attribute isn't specified, try to use the
283     // generic one.
284   }
285 
286   // TODO: Should probably avoid the connection to the IR and store directly
287   // in the MachineFunction.
288   Attribute Attr = F.getFnAttribute("denormal-fp-math");
289   return parseDenormalFPAttribute(Attr.getValueAsString());
290 }
291 
292 /// Should we be emitting segmented stack stuff for the function
293 bool MachineFunction::shouldSplitStack() const {
294   return getFunction().hasFnAttribute("split-stack");
295 }
296 
297 LLVM_NODISCARD unsigned
298 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) {
299   FrameInstructions.push_back(Inst);
300   return FrameInstructions.size() - 1;
301 }
302 
303 /// This discards all of the MachineBasicBlock numbers and recomputes them.
304 /// This guarantees that the MBB numbers are sequential, dense, and match the
305 /// ordering of the blocks within the function.  If a specific MachineBasicBlock
306 /// is specified, only that block and those after it are renumbered.
307 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
308   if (empty()) { MBBNumbering.clear(); return; }
309   MachineFunction::iterator MBBI, E = end();
310   if (MBB == nullptr)
311     MBBI = begin();
312   else
313     MBBI = MBB->getIterator();
314 
315   // Figure out the block number this should have.
316   unsigned BlockNo = 0;
317   if (MBBI != begin())
318     BlockNo = std::prev(MBBI)->getNumber() + 1;
319 
320   for (; MBBI != E; ++MBBI, ++BlockNo) {
321     if (MBBI->getNumber() != (int)BlockNo) {
322       // Remove use of the old number.
323       if (MBBI->getNumber() != -1) {
324         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
325                "MBB number mismatch!");
326         MBBNumbering[MBBI->getNumber()] = nullptr;
327       }
328 
329       // If BlockNo is already taken, set that block's number to -1.
330       if (MBBNumbering[BlockNo])
331         MBBNumbering[BlockNo]->setNumber(-1);
332 
333       MBBNumbering[BlockNo] = &*MBBI;
334       MBBI->setNumber(BlockNo);
335     }
336   }
337 
338   // Okay, all the blocks are renumbered.  If we have compactified the block
339   // numbering, shrink MBBNumbering now.
340   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
341   MBBNumbering.resize(BlockNo);
342 }
343 
344 /// This sets the section ranges of cold or exception section with basic block
345 /// sections.
346 void MachineFunction::setSectionRange() {
347   // Compute the Section Range of cold and exception basic blocks.  Find the
348   // first and last block of each range.
349   auto SectionRange =
350       ([&](llvm::MachineBasicBlockSection S) -> std::pair<int, int> {
351         auto MBBP =
352             std::find_if(begin(), end(), [&](MachineBasicBlock &MBB) -> bool {
353               return MBB.getSectionType() == S;
354             });
355         if (MBBP == end())
356           return std::make_pair(-1, -1);
357 
358         auto MBBQ =
359             std::find_if(rbegin(), rend(), [&](MachineBasicBlock &MBB) -> bool {
360               return MBB.getSectionType() == S;
361             });
362         assert(MBBQ != rend() && "Section end not found!");
363         return std::make_pair(MBBP->getNumber(), MBBQ->getNumber());
364       });
365 
366   ExceptionSectionRange = SectionRange(MBBS_Exception);
367   ColdSectionRange = SectionRange(llvm::MBBS_Cold);
368 }
369 
370 /// This is used with -fbasicblock-sections or -fbasicblock-labels option.
371 /// A unary encoding of basic block labels is done to keep ".strtab" sizes
372 /// small.
373 void MachineFunction::createBBLabels() {
374   const TargetInstrInfo *TII = getSubtarget().getInstrInfo();
375   this->BBSectionsSymbolPrefix.resize(getNumBlockIDs(), 'a');
376   for (auto MBBI = begin(), E = end(); MBBI != E; ++MBBI) {
377     assert(
378         (MBBI->getNumber() >= 0 && MBBI->getNumber() < (int)getNumBlockIDs()) &&
379         "BasicBlock number was out of range!");
380     // 'a' - Normal block.
381     // 'r' - Return block.
382     // 'l' - Landing Pad.
383     // 'L' - Return and landing pad.
384     bool isEHPad = MBBI->isEHPad();
385     bool isRetBlock = MBBI->isReturnBlock() && !TII->isTailCall(MBBI->back());
386     char type = 'a';
387     if (isEHPad && isRetBlock)
388       type = 'L';
389     else if (isEHPad)
390       type = 'l';
391     else if (isRetBlock)
392       type = 'r';
393     BBSectionsSymbolPrefix[MBBI->getNumber()] = type;
394   }
395 }
396 
397 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
398 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
399                                                   const DebugLoc &DL,
400                                                   bool NoImp) {
401   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
402     MachineInstr(*this, MCID, DL, NoImp);
403 }
404 
405 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
406 /// identical in all ways except the instruction has no parent, prev, or next.
407 MachineInstr *
408 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
409   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
410              MachineInstr(*this, *Orig);
411 }
412 
413 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
414     MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
415   MachineInstr *FirstClone = nullptr;
416   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
417   while (true) {
418     MachineInstr *Cloned = CloneMachineInstr(&*I);
419     MBB.insert(InsertBefore, Cloned);
420     if (FirstClone == nullptr) {
421       FirstClone = Cloned;
422     } else {
423       Cloned->bundleWithPred();
424     }
425 
426     if (!I->isBundledWithSucc())
427       break;
428     ++I;
429   }
430   return *FirstClone;
431 }
432 
433 /// Delete the given MachineInstr.
434 ///
435 /// This function also serves as the MachineInstr destructor - the real
436 /// ~MachineInstr() destructor must be empty.
437 void
438 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
439   // Verify that a call site info is at valid state. This assertion should
440   // be triggered during the implementation of support for the
441   // call site info of a new architecture. If the assertion is triggered,
442   // back trace will tell where to insert a call to updateCallSiteInfo().
443   assert((!MI->isCandidateForCallSiteEntry() ||
444           CallSitesInfo.find(MI) == CallSitesInfo.end()) &&
445          "Call site info was not updated!");
446   // Strip it for parts. The operand array and the MI object itself are
447   // independently recyclable.
448   if (MI->Operands)
449     deallocateOperandArray(MI->CapOperands, MI->Operands);
450   // Don't call ~MachineInstr() which must be trivial anyway because
451   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
452   // destructors.
453   InstructionRecycler.Deallocate(Allocator, MI);
454 }
455 
456 /// Allocate a new MachineBasicBlock. Use this instead of
457 /// `new MachineBasicBlock'.
458 MachineBasicBlock *
459 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
460   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
461              MachineBasicBlock(*this, bb);
462 }
463 
464 /// Delete the given MachineBasicBlock.
465 void
466 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
467   assert(MBB->getParent() == this && "MBB parent mismatch!");
468   MBB->~MachineBasicBlock();
469   BasicBlockRecycler.Deallocate(Allocator, MBB);
470 }
471 
472 MachineMemOperand *MachineFunction::getMachineMemOperand(
473     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
474     unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
475     SyncScope::ID SSID, AtomicOrdering Ordering,
476     AtomicOrdering FailureOrdering) {
477   return new (Allocator)
478       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
479                         SSID, Ordering, FailureOrdering);
480 }
481 
482 MachineMemOperand *
483 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
484                                       int64_t Offset, uint64_t Size) {
485   const MachinePointerInfo &PtrInfo = MMO->getPointerInfo();
486 
487   // If there is no pointer value, the offset isn't tracked so we need to adjust
488   // the base alignment.
489   unsigned Align = PtrInfo.V.isNull()
490                        ? MinAlign(MMO->getBaseAlignment(), Offset)
491                        : MMO->getBaseAlignment();
492 
493   return new (Allocator)
494       MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size,
495                         Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(),
496                         MMO->getOrdering(), MMO->getFailureOrdering());
497 }
498 
499 MachineMemOperand *
500 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
501                                       const AAMDNodes &AAInfo) {
502   MachinePointerInfo MPI = MMO->getValue() ?
503              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
504              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
505 
506   return new (Allocator)
507              MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
508                                MMO->getBaseAlignment(), AAInfo,
509                                MMO->getRanges(), MMO->getSyncScopeID(),
510                                MMO->getOrdering(), MMO->getFailureOrdering());
511 }
512 
513 MachineMemOperand *
514 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
515                                       MachineMemOperand::Flags Flags) {
516   return new (Allocator) MachineMemOperand(
517       MMO->getPointerInfo(), Flags, MMO->getSize(), MMO->getBaseAlignment(),
518       MMO->getAAInfo(), MMO->getRanges(), MMO->getSyncScopeID(),
519       MMO->getOrdering(), MMO->getFailureOrdering());
520 }
521 
522 MachineInstr::ExtraInfo *MachineFunction::createMIExtraInfo(
523     ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol,
524     MCSymbol *PostInstrSymbol, MDNode *HeapAllocMarker) {
525   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
526                                          PostInstrSymbol, HeapAllocMarker);
527 }
528 
529 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
530   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
531   llvm::copy(Name, Dest);
532   Dest[Name.size()] = 0;
533   return Dest;
534 }
535 
536 uint32_t *MachineFunction::allocateRegMask() {
537   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
538   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
539   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
540   memset(Mask, 0, Size * sizeof(Mask[0]));
541   return Mask;
542 }
543 
544 ArrayRef<int> MachineFunction::allocateShuffleMask(ArrayRef<int> Mask) {
545   int* AllocMask = Allocator.Allocate<int>(Mask.size());
546   copy(Mask, AllocMask);
547   return {AllocMask, Mask.size()};
548 }
549 
550 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
551 LLVM_DUMP_METHOD void MachineFunction::dump() const {
552   print(dbgs());
553 }
554 #endif
555 
556 StringRef MachineFunction::getName() const {
557   return getFunction().getName();
558 }
559 
560 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
561   OS << "# Machine code for function " << getName() << ": ";
562   getProperties().print(OS);
563   OS << '\n';
564 
565   // Print Frame Information
566   FrameInfo->print(*this, OS);
567 
568   // Print JumpTable Information
569   if (JumpTableInfo)
570     JumpTableInfo->print(OS);
571 
572   // Print Constant Pool
573   ConstantPool->print(OS);
574 
575   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
576 
577   if (RegInfo && !RegInfo->livein_empty()) {
578     OS << "Function Live Ins: ";
579     for (MachineRegisterInfo::livein_iterator
580          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
581       OS << printReg(I->first, TRI);
582       if (I->second)
583         OS << " in " << printReg(I->second, TRI);
584       if (std::next(I) != E)
585         OS << ", ";
586     }
587     OS << '\n';
588   }
589 
590   ModuleSlotTracker MST(getFunction().getParent());
591   MST.incorporateFunction(getFunction());
592   for (const auto &BB : *this) {
593     OS << '\n';
594     // If we print the whole function, print it at its most verbose level.
595     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
596   }
597 
598   OS << "\n# End machine code for function " << getName() << ".\n\n";
599 }
600 
601 /// True if this function needs frame moves for debug or exceptions.
602 bool MachineFunction::needsFrameMoves() const {
603   return getMMI().hasDebugInfo() ||
604          getTarget().Options.ForceDwarfFrameSection ||
605          F.needsUnwindTableEntry();
606 }
607 
608 namespace llvm {
609 
610   template<>
611   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
612     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
613 
614     static std::string getGraphName(const MachineFunction *F) {
615       return ("CFG for '" + F->getName() + "' function").str();
616     }
617 
618     std::string getNodeLabel(const MachineBasicBlock *Node,
619                              const MachineFunction *Graph) {
620       std::string OutStr;
621       {
622         raw_string_ostream OSS(OutStr);
623 
624         if (isSimple()) {
625           OSS << printMBBReference(*Node);
626           if (const BasicBlock *BB = Node->getBasicBlock())
627             OSS << ": " << BB->getName();
628         } else
629           Node->print(OSS);
630       }
631 
632       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
633 
634       // Process string output to make it nicer...
635       for (unsigned i = 0; i != OutStr.length(); ++i)
636         if (OutStr[i] == '\n') {                            // Left justify
637           OutStr[i] = '\\';
638           OutStr.insert(OutStr.begin()+i+1, 'l');
639         }
640       return OutStr;
641     }
642   };
643 
644 } // end namespace llvm
645 
646 void MachineFunction::viewCFG() const
647 {
648 #ifndef NDEBUG
649   ViewGraph(this, "mf" + getName());
650 #else
651   errs() << "MachineFunction::viewCFG is only available in debug builds on "
652          << "systems with Graphviz or gv!\n";
653 #endif // NDEBUG
654 }
655 
656 void MachineFunction::viewCFGOnly() const
657 {
658 #ifndef NDEBUG
659   ViewGraph(this, "mf" + getName(), true);
660 #else
661   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
662          << "systems with Graphviz or gv!\n";
663 #endif // NDEBUG
664 }
665 
666 /// Add the specified physical register as a live-in value and
667 /// create a corresponding virtual register for it.
668 unsigned MachineFunction::addLiveIn(unsigned PReg,
669                                     const TargetRegisterClass *RC) {
670   MachineRegisterInfo &MRI = getRegInfo();
671   unsigned VReg = MRI.getLiveInVirtReg(PReg);
672   if (VReg) {
673     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
674     (void)VRegRC;
675     // A physical register can be added several times.
676     // Between two calls, the register class of the related virtual register
677     // may have been constrained to match some operation constraints.
678     // In that case, check that the current register class includes the
679     // physical register and is a sub class of the specified RC.
680     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
681                              RC->hasSubClassEq(VRegRC))) &&
682             "Register class mismatch!");
683     return VReg;
684   }
685   VReg = MRI.createVirtualRegister(RC);
686   MRI.addLiveIn(PReg, VReg);
687   return VReg;
688 }
689 
690 /// Return the MCSymbol for the specified non-empty jump table.
691 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
692 /// normal 'L' label is returned.
693 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
694                                         bool isLinkerPrivate) const {
695   const DataLayout &DL = getDataLayout();
696   assert(JumpTableInfo && "No jump tables");
697   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
698 
699   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
700                                      : DL.getPrivateGlobalPrefix();
701   SmallString<60> Name;
702   raw_svector_ostream(Name)
703     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
704   return Ctx.getOrCreateSymbol(Name);
705 }
706 
707 /// Return a function-local symbol to represent the PIC base.
708 MCSymbol *MachineFunction::getPICBaseSymbol() const {
709   const DataLayout &DL = getDataLayout();
710   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
711                                Twine(getFunctionNumber()) + "$pb");
712 }
713 
714 /// \name Exception Handling
715 /// \{
716 
717 LandingPadInfo &
718 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
719   unsigned N = LandingPads.size();
720   for (unsigned i = 0; i < N; ++i) {
721     LandingPadInfo &LP = LandingPads[i];
722     if (LP.LandingPadBlock == LandingPad)
723       return LP;
724   }
725 
726   LandingPads.push_back(LandingPadInfo(LandingPad));
727   return LandingPads[N];
728 }
729 
730 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
731                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
732   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
733   LP.BeginLabels.push_back(BeginLabel);
734   LP.EndLabels.push_back(EndLabel);
735 }
736 
737 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
738   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
739   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
740   LP.LandingPadLabel = LandingPadLabel;
741 
742   const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI();
743   if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) {
744     if (const auto *PF =
745             dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts()))
746       getMMI().addPersonality(PF);
747 
748     if (LPI->isCleanup())
749       addCleanup(LandingPad);
750 
751     // FIXME: New EH - Add the clauses in reverse order. This isn't 100%
752     //        correct, but we need to do it this way because of how the DWARF EH
753     //        emitter processes the clauses.
754     for (unsigned I = LPI->getNumClauses(); I != 0; --I) {
755       Value *Val = LPI->getClause(I - 1);
756       if (LPI->isCatch(I - 1)) {
757         addCatchTypeInfo(LandingPad,
758                          dyn_cast<GlobalValue>(Val->stripPointerCasts()));
759       } else {
760         // Add filters in a list.
761         auto *CVal = cast<Constant>(Val);
762         SmallVector<const GlobalValue *, 4> FilterList;
763         for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
764              II != IE; ++II)
765           FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
766 
767         addFilterTypeInfo(LandingPad, FilterList);
768       }
769     }
770 
771   } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) {
772     for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) {
773       Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts();
774       addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo));
775     }
776 
777   } else {
778     assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!");
779   }
780 
781   return LandingPadLabel;
782 }
783 
784 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
785                                        ArrayRef<const GlobalValue *> TyInfo) {
786   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
787   for (unsigned N = TyInfo.size(); N; --N)
788     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
789 }
790 
791 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
792                                         ArrayRef<const GlobalValue *> TyInfo) {
793   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
794   std::vector<unsigned> IdsInFilter(TyInfo.size());
795   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
796     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
797   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
798 }
799 
800 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap,
801                                       bool TidyIfNoBeginLabels) {
802   for (unsigned i = 0; i != LandingPads.size(); ) {
803     LandingPadInfo &LandingPad = LandingPads[i];
804     if (LandingPad.LandingPadLabel &&
805         !LandingPad.LandingPadLabel->isDefined() &&
806         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
807       LandingPad.LandingPadLabel = nullptr;
808 
809     // Special case: we *should* emit LPs with null LP MBB. This indicates
810     // "nounwind" case.
811     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
812       LandingPads.erase(LandingPads.begin() + i);
813       continue;
814     }
815 
816     if (TidyIfNoBeginLabels) {
817       for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
818         MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
819         MCSymbol *EndLabel = LandingPad.EndLabels[j];
820         if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) &&
821             (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0)))
822           continue;
823 
824         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
825         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
826         --j;
827         --e;
828       }
829 
830       // Remove landing pads with no try-ranges.
831       if (LandingPads[i].BeginLabels.empty()) {
832         LandingPads.erase(LandingPads.begin() + i);
833         continue;
834       }
835     }
836 
837     // If there is no landing pad, ensure that the list of typeids is empty.
838     // If the only typeid is a cleanup, this is the same as having no typeids.
839     if (!LandingPad.LandingPadBlock ||
840         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
841       LandingPad.TypeIds.clear();
842     ++i;
843   }
844 }
845 
846 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
847   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
848   LP.TypeIds.push_back(0);
849 }
850 
851 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
852                                          const Function *Filter,
853                                          const BlockAddress *RecoverBA) {
854   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
855   SEHHandler Handler;
856   Handler.FilterOrFinally = Filter;
857   Handler.RecoverBA = RecoverBA;
858   LP.SEHHandlers.push_back(Handler);
859 }
860 
861 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
862                                            const Function *Cleanup) {
863   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
864   SEHHandler Handler;
865   Handler.FilterOrFinally = Cleanup;
866   Handler.RecoverBA = nullptr;
867   LP.SEHHandlers.push_back(Handler);
868 }
869 
870 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
871                                             ArrayRef<unsigned> Sites) {
872   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
873 }
874 
875 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
876   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
877     if (TypeInfos[i] == TI) return i + 1;
878 
879   TypeInfos.push_back(TI);
880   return TypeInfos.size();
881 }
882 
883 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
884   // If the new filter coincides with the tail of an existing filter, then
885   // re-use the existing filter.  Folding filters more than this requires
886   // re-ordering filters and/or their elements - probably not worth it.
887   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
888        E = FilterEnds.end(); I != E; ++I) {
889     unsigned i = *I, j = TyIds.size();
890 
891     while (i && j)
892       if (FilterIds[--i] != TyIds[--j])
893         goto try_next;
894 
895     if (!j)
896       // The new filter coincides with range [i, end) of the existing filter.
897       return -(1 + i);
898 
899 try_next:;
900   }
901 
902   // Add the new filter.
903   int FilterID = -(1 + FilterIds.size());
904   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
905   FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
906   FilterEnds.push_back(FilterIds.size());
907   FilterIds.push_back(0); // terminator
908   return FilterID;
909 }
910 
911 MachineFunction::CallSiteInfoMap::iterator
912 MachineFunction::getCallSiteInfo(const MachineInstr *MI) {
913   assert(MI->isCandidateForCallSiteEntry() &&
914          "Call site info refers only to call (MI) candidates");
915 
916   if (!Target.Options.EmitCallSiteInfo)
917     return CallSitesInfo.end();
918   return CallSitesInfo.find(MI);
919 }
920 
921 /// Return the call machine instruction or find a call within bundle.
922 static const MachineInstr *getCallInstr(const MachineInstr *MI) {
923   if (!MI->isBundle())
924     return MI;
925 
926   for (auto &BMI : make_range(getBundleStart(MI->getIterator()),
927                               getBundleEnd(MI->getIterator())))
928     if (BMI.isCandidateForCallSiteEntry())
929       return &BMI;
930 
931   llvm_unreachable("Unexpected bundle without a call site candidate");
932 }
933 
934 void MachineFunction::eraseCallSiteInfo(const MachineInstr *MI) {
935   assert(MI->shouldUpdateCallSiteInfo() &&
936          "Call site info refers only to call (MI) candidates or "
937          "candidates inside bundles");
938 
939   const MachineInstr *CallMI = getCallInstr(MI);
940   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(CallMI);
941   if (CSIt == CallSitesInfo.end())
942     return;
943   CallSitesInfo.erase(CSIt);
944 }
945 
946 void MachineFunction::copyCallSiteInfo(const MachineInstr *Old,
947                                        const MachineInstr *New) {
948   assert(Old->shouldUpdateCallSiteInfo() &&
949          "Call site info refers only to call (MI) candidates or "
950          "candidates inside bundles");
951 
952   if (!New->isCandidateForCallSiteEntry())
953     return eraseCallSiteInfo(Old);
954 
955   const MachineInstr *OldCallMI = getCallInstr(Old);
956   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
957   if (CSIt == CallSitesInfo.end())
958     return;
959 
960   CallSiteInfo CSInfo = CSIt->second;
961   CallSitesInfo[New] = CSInfo;
962 }
963 
964 void MachineFunction::moveCallSiteInfo(const MachineInstr *Old,
965                                        const MachineInstr *New) {
966   assert(Old->shouldUpdateCallSiteInfo() &&
967          "Call site info refers only to call (MI) candidates or "
968          "candidates inside bundles");
969 
970   if (!New->isCandidateForCallSiteEntry())
971     return eraseCallSiteInfo(Old);
972 
973   const MachineInstr *OldCallMI = getCallInstr(Old);
974   CallSiteInfoMap::iterator CSIt = getCallSiteInfo(OldCallMI);
975   if (CSIt == CallSitesInfo.end())
976     return;
977 
978   CallSiteInfo CSInfo = std::move(CSIt->second);
979   CallSitesInfo.erase(CSIt);
980   CallSitesInfo[New] = CSInfo;
981 }
982 
983 /// \}
984 
985 //===----------------------------------------------------------------------===//
986 //  MachineJumpTableInfo implementation
987 //===----------------------------------------------------------------------===//
988 
989 /// Return the size of each entry in the jump table.
990 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
991   // The size of a jump table entry is 4 bytes unless the entry is just the
992   // address of a block, in which case it is the pointer size.
993   switch (getEntryKind()) {
994   case MachineJumpTableInfo::EK_BlockAddress:
995     return TD.getPointerSize();
996   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
997     return 8;
998   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
999   case MachineJumpTableInfo::EK_LabelDifference32:
1000   case MachineJumpTableInfo::EK_Custom32:
1001     return 4;
1002   case MachineJumpTableInfo::EK_Inline:
1003     return 0;
1004   }
1005   llvm_unreachable("Unknown jump table encoding!");
1006 }
1007 
1008 /// Return the alignment of each entry in the jump table.
1009 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
1010   // The alignment of a jump table entry is the alignment of int32 unless the
1011   // entry is just the address of a block, in which case it is the pointer
1012   // alignment.
1013   switch (getEntryKind()) {
1014   case MachineJumpTableInfo::EK_BlockAddress:
1015     return TD.getPointerABIAlignment(0).value();
1016   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
1017     return TD.getABIIntegerTypeAlignment(64).value();
1018   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
1019   case MachineJumpTableInfo::EK_LabelDifference32:
1020   case MachineJumpTableInfo::EK_Custom32:
1021     return TD.getABIIntegerTypeAlignment(32).value();
1022   case MachineJumpTableInfo::EK_Inline:
1023     return 1;
1024   }
1025   llvm_unreachable("Unknown jump table encoding!");
1026 }
1027 
1028 /// Create a new jump table entry in the jump table info.
1029 unsigned MachineJumpTableInfo::createJumpTableIndex(
1030                                const std::vector<MachineBasicBlock*> &DestBBs) {
1031   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
1032   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
1033   return JumpTables.size()-1;
1034 }
1035 
1036 /// If Old is the target of any jump tables, update the jump tables to branch
1037 /// to New instead.
1038 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
1039                                                   MachineBasicBlock *New) {
1040   assert(Old != New && "Not making a change?");
1041   bool MadeChange = false;
1042   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
1043     ReplaceMBBInJumpTable(i, Old, New);
1044   return MadeChange;
1045 }
1046 
1047 /// If Old is a target of the jump tables, update the jump table to branch to
1048 /// New instead.
1049 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
1050                                                  MachineBasicBlock *Old,
1051                                                  MachineBasicBlock *New) {
1052   assert(Old != New && "Not making a change?");
1053   bool MadeChange = false;
1054   MachineJumpTableEntry &JTE = JumpTables[Idx];
1055   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
1056     if (JTE.MBBs[j] == Old) {
1057       JTE.MBBs[j] = New;
1058       MadeChange = true;
1059     }
1060   return MadeChange;
1061 }
1062 
1063 void MachineJumpTableInfo::print(raw_ostream &OS) const {
1064   if (JumpTables.empty()) return;
1065 
1066   OS << "Jump Tables:\n";
1067 
1068   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
1069     OS << printJumpTableEntryReference(i) << ':';
1070     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
1071       OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
1072     if (i != e)
1073       OS << '\n';
1074   }
1075 
1076   OS << '\n';
1077 }
1078 
1079 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1080 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
1081 #endif
1082 
1083 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
1084   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
1085 }
1086 
1087 //===----------------------------------------------------------------------===//
1088 //  MachineConstantPool implementation
1089 //===----------------------------------------------------------------------===//
1090 
1091 void MachineConstantPoolValue::anchor() {}
1092 
1093 Type *MachineConstantPoolEntry::getType() const {
1094   if (isMachineConstantPoolEntry())
1095     return Val.MachineCPVal->getType();
1096   return Val.ConstVal->getType();
1097 }
1098 
1099 bool MachineConstantPoolEntry::needsRelocation() const {
1100   if (isMachineConstantPoolEntry())
1101     return true;
1102   return Val.ConstVal->needsRelocation();
1103 }
1104 
1105 SectionKind
1106 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
1107   if (needsRelocation())
1108     return SectionKind::getReadOnlyWithRel();
1109   switch (DL->getTypeAllocSize(getType())) {
1110   case 4:
1111     return SectionKind::getMergeableConst4();
1112   case 8:
1113     return SectionKind::getMergeableConst8();
1114   case 16:
1115     return SectionKind::getMergeableConst16();
1116   case 32:
1117     return SectionKind::getMergeableConst32();
1118   default:
1119     return SectionKind::getReadOnly();
1120   }
1121 }
1122 
1123 MachineConstantPool::~MachineConstantPool() {
1124   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
1125   // so keep track of which we've deleted to avoid double deletions.
1126   DenseSet<MachineConstantPoolValue*> Deleted;
1127   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1128     if (Constants[i].isMachineConstantPoolEntry()) {
1129       Deleted.insert(Constants[i].Val.MachineCPVal);
1130       delete Constants[i].Val.MachineCPVal;
1131     }
1132   for (DenseSet<MachineConstantPoolValue*>::iterator I =
1133        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
1134        I != E; ++I) {
1135     if (Deleted.count(*I) == 0)
1136       delete *I;
1137   }
1138 }
1139 
1140 /// Test whether the given two constants can be allocated the same constant pool
1141 /// entry.
1142 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
1143                                       const DataLayout &DL) {
1144   // Handle the trivial case quickly.
1145   if (A == B) return true;
1146 
1147   // If they have the same type but weren't the same constant, quickly
1148   // reject them.
1149   if (A->getType() == B->getType()) return false;
1150 
1151   // We can't handle structs or arrays.
1152   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
1153       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
1154     return false;
1155 
1156   // For now, only support constants with the same size.
1157   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
1158   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
1159     return false;
1160 
1161   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
1162 
1163   // Try constant folding a bitcast of both instructions to an integer.  If we
1164   // get two identical ConstantInt's, then we are good to share them.  We use
1165   // the constant folding APIs to do this so that we get the benefit of
1166   // DataLayout.
1167   if (isa<PointerType>(A->getType()))
1168     A = ConstantFoldCastOperand(Instruction::PtrToInt,
1169                                 const_cast<Constant *>(A), IntTy, DL);
1170   else if (A->getType() != IntTy)
1171     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
1172                                 IntTy, DL);
1173   if (isa<PointerType>(B->getType()))
1174     B = ConstantFoldCastOperand(Instruction::PtrToInt,
1175                                 const_cast<Constant *>(B), IntTy, DL);
1176   else if (B->getType() != IntTy)
1177     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
1178                                 IntTy, DL);
1179 
1180   return A == B;
1181 }
1182 
1183 /// Create a new entry in the constant pool or return an existing one.
1184 /// User must specify the log2 of the minimum required alignment for the object.
1185 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
1186                                                    unsigned Alignment) {
1187   assert(Alignment && "Alignment must be specified!");
1188   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1189 
1190   // Check to see if we already have this constant.
1191   //
1192   // FIXME, this could be made much more efficient for large constant pools.
1193   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
1194     if (!Constants[i].isMachineConstantPoolEntry() &&
1195         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
1196       if ((unsigned)Constants[i].getAlignment() < Alignment)
1197         Constants[i].Alignment = Alignment;
1198       return i;
1199     }
1200 
1201   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1202   return Constants.size()-1;
1203 }
1204 
1205 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1206                                                    unsigned Alignment) {
1207   assert(Alignment && "Alignment must be specified!");
1208   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1209 
1210   // Check to see if we already have this constant.
1211   //
1212   // FIXME, this could be made much more efficient for large constant pools.
1213   int Idx = V->getExistingMachineCPValue(this, Alignment);
1214   if (Idx != -1) {
1215     MachineCPVsSharingEntries.insert(V);
1216     return (unsigned)Idx;
1217   }
1218 
1219   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1220   return Constants.size()-1;
1221 }
1222 
1223 void MachineConstantPool::print(raw_ostream &OS) const {
1224   if (Constants.empty()) return;
1225 
1226   OS << "Constant Pool:\n";
1227   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1228     OS << "  cp#" << i << ": ";
1229     if (Constants[i].isMachineConstantPoolEntry())
1230       Constants[i].Val.MachineCPVal->print(OS);
1231     else
1232       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1233     OS << ", align=" << Constants[i].getAlignment();
1234     OS << "\n";
1235   }
1236 }
1237 
1238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1239 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1240 #endif
1241