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