xref: /llvm-project/llvm/lib/CodeGen/MachineFunction.cpp (revision e5909431b5f3479dd713c7fe4919a028499dd709)
1 //===- MachineFunction.cpp ------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect native machine code information for a function.  This allows
11 // target-specific information about the generated code to be stored with each
12 // function.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/EHPersonalities.h"
27 #include "llvm/CodeGen/MachineBasicBlock.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineMemOperand.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/TargetFrameLowering.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/DerivedTypes.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalValue.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/Metadata.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSlotTracker.h"
55 #include "llvm/IR/Value.h"
56 #include "llvm/MC/MCContext.h"
57 #include "llvm/MC/MCSymbol.h"
58 #include "llvm/MC/SectionKind.h"
59 #include "llvm/Support/Casting.h"
60 #include "llvm/Support/CommandLine.h"
61 #include "llvm/Support/Compiler.h"
62 #include "llvm/Support/DOTGraphTraits.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/GraphWriter.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Target/TargetMachine.h"
68 #include <algorithm>
69 #include <cassert>
70 #include <cstddef>
71 #include <cstdint>
72 #include <iterator>
73 #include <string>
74 #include <utility>
75 #include <vector>
76 
77 using namespace llvm;
78 
79 #define DEBUG_TYPE "codegen"
80 
81 static cl::opt<unsigned>
82 AlignAllFunctions("align-all-functions",
83                   cl::desc("Force the alignment of all functions."),
84                   cl::init(0), cl::Hidden);
85 
86 static const char *getPropertyName(MachineFunctionProperties::Property Prop) {
87   using P = MachineFunctionProperties::Property;
88 
89   switch(Prop) {
90   case P::FailedISel: return "FailedISel";
91   case P::IsSSA: return "IsSSA";
92   case P::Legalized: return "Legalized";
93   case P::NoPHIs: return "NoPHIs";
94   case P::NoVRegs: return "NoVRegs";
95   case P::RegBankSelected: return "RegBankSelected";
96   case P::Selected: return "Selected";
97   case P::TracksLiveness: return "TracksLiveness";
98   }
99   llvm_unreachable("Invalid machine function property");
100 }
101 
102 // Pin the vtable to this file.
103 void MachineFunction::Delegate::anchor() {}
104 
105 void MachineFunctionProperties::print(raw_ostream &OS) const {
106   const char *Separator = "";
107   for (BitVector::size_type I = 0; I < Properties.size(); ++I) {
108     if (!Properties[I])
109       continue;
110     OS << Separator << getPropertyName(static_cast<Property>(I));
111     Separator = ", ";
112   }
113 }
114 
115 //===----------------------------------------------------------------------===//
116 // MachineFunction implementation
117 //===----------------------------------------------------------------------===//
118 
119 // Out-of-line virtual method.
120 MachineFunctionInfo::~MachineFunctionInfo() = default;
121 
122 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
123   MBB->getParent()->DeleteMachineBasicBlock(MBB);
124 }
125 
126 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI,
127                                            const Function &F) {
128   if (F.hasFnAttribute(Attribute::StackAlignment))
129     return F.getFnStackAlignment();
130   return STI->getFrameLowering()->getStackAlignment();
131 }
132 
133 MachineFunction::MachineFunction(const Function &F, const TargetMachine &Target,
134                                  const TargetSubtargetInfo &STI,
135                                  unsigned FunctionNum, MachineModuleInfo &mmi)
136     : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) {
137   FunctionNumber = FunctionNum;
138   init();
139 }
140 
141 void MachineFunction::handleInsertion(const MachineInstr &MI) {
142   if (TheDelegate)
143     TheDelegate->MF_HandleInsertion(MI);
144 }
145 
146 void MachineFunction::handleRemoval(const MachineInstr &MI) {
147   if (TheDelegate)
148     TheDelegate->MF_HandleRemoval(MI);
149 }
150 
151 void MachineFunction::init() {
152   // Assume the function starts in SSA form with correct liveness.
153   Properties.set(MachineFunctionProperties::Property::IsSSA);
154   Properties.set(MachineFunctionProperties::Property::TracksLiveness);
155   if (STI->getRegisterInfo())
156     RegInfo = new (Allocator) MachineRegisterInfo(this);
157   else
158     RegInfo = nullptr;
159 
160   MFInfo = nullptr;
161   // We can realign the stack if the target supports it and the user hasn't
162   // explicitly asked us not to.
163   bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() &&
164                       !F.hasFnAttribute("no-realign-stack");
165   FrameInfo = new (Allocator) MachineFrameInfo(
166       getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP,
167       /*ForceRealign=*/CanRealignSP &&
168           F.hasFnAttribute(Attribute::StackAlignment));
169 
170   if (F.hasFnAttribute(Attribute::StackAlignment))
171     FrameInfo->ensureMaxAlignment(F.getFnStackAlignment());
172 
173   ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
174   Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
175 
176   // FIXME: Shouldn't use pref alignment if explicit alignment is set on F.
177   // FIXME: Use Function::optForSize().
178   if (!F.hasFnAttribute(Attribute::OptimizeForSize))
179     Alignment = std::max(Alignment,
180                          STI->getTargetLowering()->getPrefFunctionAlignment());
181 
182   if (AlignAllFunctions)
183     Alignment = AlignAllFunctions;
184 
185   JumpTableInfo = nullptr;
186 
187   if (isFuncletEHPersonality(classifyEHPersonality(
188           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
189     WinEHInfo = new (Allocator) WinEHFuncInfo();
190   }
191 
192   if (isScopedEHPersonality(classifyEHPersonality(
193           F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) {
194     WasmEHInfo = new (Allocator) WasmEHFuncInfo();
195   }
196 
197   assert(Target.isCompatibleDataLayout(getDataLayout()) &&
198          "Can't create a MachineFunction using a Module with a "
199          "Target-incompatible DataLayout attached\n");
200 
201   PSVManager =
202     llvm::make_unique<PseudoSourceValueManager>(*(getSubtarget().
203                                                   getInstrInfo()));
204 }
205 
206 MachineFunction::~MachineFunction() {
207   clear();
208 }
209 
210 void MachineFunction::clear() {
211   Properties.reset();
212   // Don't call destructors on MachineInstr and MachineOperand. All of their
213   // memory comes from the BumpPtrAllocator which is about to be purged.
214   //
215   // Do call MachineBasicBlock destructors, it contains std::vectors.
216   for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
217     I->Insts.clearAndLeakNodesUnsafely();
218   MBBNumbering.clear();
219 
220   InstructionRecycler.clear(Allocator);
221   OperandRecycler.clear(Allocator);
222   BasicBlockRecycler.clear(Allocator);
223   CodeViewAnnotations.clear();
224   VariableDbgInfos.clear();
225   if (RegInfo) {
226     RegInfo->~MachineRegisterInfo();
227     Allocator.Deallocate(RegInfo);
228   }
229   if (MFInfo) {
230     MFInfo->~MachineFunctionInfo();
231     Allocator.Deallocate(MFInfo);
232   }
233 
234   FrameInfo->~MachineFrameInfo();
235   Allocator.Deallocate(FrameInfo);
236 
237   ConstantPool->~MachineConstantPool();
238   Allocator.Deallocate(ConstantPool);
239 
240   if (JumpTableInfo) {
241     JumpTableInfo->~MachineJumpTableInfo();
242     Allocator.Deallocate(JumpTableInfo);
243   }
244 
245   if (WinEHInfo) {
246     WinEHInfo->~WinEHFuncInfo();
247     Allocator.Deallocate(WinEHInfo);
248   }
249 }
250 
251 const DataLayout &MachineFunction::getDataLayout() const {
252   return F.getParent()->getDataLayout();
253 }
254 
255 /// Get the JumpTableInfo for this function.
256 /// If it does not already exist, allocate one.
257 MachineJumpTableInfo *MachineFunction::
258 getOrCreateJumpTableInfo(unsigned EntryKind) {
259   if (JumpTableInfo) return JumpTableInfo;
260 
261   JumpTableInfo = new (Allocator)
262     MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
263   return JumpTableInfo;
264 }
265 
266 /// Should we be emitting segmented stack stuff for the function
267 bool MachineFunction::shouldSplitStack() const {
268   return getFunction().hasFnAttribute("split-stack");
269 }
270 
271 /// This discards all of the MachineBasicBlock numbers and recomputes them.
272 /// This guarantees that the MBB numbers are sequential, dense, and match the
273 /// ordering of the blocks within the function.  If a specific MachineBasicBlock
274 /// is specified, only that block and those after it are renumbered.
275 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
276   if (empty()) { MBBNumbering.clear(); return; }
277   MachineFunction::iterator MBBI, E = end();
278   if (MBB == nullptr)
279     MBBI = begin();
280   else
281     MBBI = MBB->getIterator();
282 
283   // Figure out the block number this should have.
284   unsigned BlockNo = 0;
285   if (MBBI != begin())
286     BlockNo = std::prev(MBBI)->getNumber() + 1;
287 
288   for (; MBBI != E; ++MBBI, ++BlockNo) {
289     if (MBBI->getNumber() != (int)BlockNo) {
290       // Remove use of the old number.
291       if (MBBI->getNumber() != -1) {
292         assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
293                "MBB number mismatch!");
294         MBBNumbering[MBBI->getNumber()] = nullptr;
295       }
296 
297       // If BlockNo is already taken, set that block's number to -1.
298       if (MBBNumbering[BlockNo])
299         MBBNumbering[BlockNo]->setNumber(-1);
300 
301       MBBNumbering[BlockNo] = &*MBBI;
302       MBBI->setNumber(BlockNo);
303     }
304   }
305 
306   // Okay, all the blocks are renumbered.  If we have compactified the block
307   // numbering, shrink MBBNumbering now.
308   assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
309   MBBNumbering.resize(BlockNo);
310 }
311 
312 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
313 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
314                                                   const DebugLoc &DL,
315                                                   bool NoImp) {
316   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
317     MachineInstr(*this, MCID, DL, NoImp);
318 }
319 
320 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
321 /// identical in all ways except the instruction has no parent, prev, or next.
322 MachineInstr *
323 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
324   return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
325              MachineInstr(*this, *Orig);
326 }
327 
328 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB,
329     MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) {
330   MachineInstr *FirstClone = nullptr;
331   MachineBasicBlock::const_instr_iterator I = Orig.getIterator();
332   while (true) {
333     MachineInstr *Cloned = CloneMachineInstr(&*I);
334     MBB.insert(InsertBefore, Cloned);
335     if (FirstClone == nullptr) {
336       FirstClone = Cloned;
337     } else {
338       Cloned->bundleWithPred();
339     }
340 
341     if (!I->isBundledWithSucc())
342       break;
343     ++I;
344   }
345   return *FirstClone;
346 }
347 
348 /// Delete the given MachineInstr.
349 ///
350 /// This function also serves as the MachineInstr destructor - the real
351 /// ~MachineInstr() destructor must be empty.
352 void
353 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
354   // Strip it for parts. The operand array and the MI object itself are
355   // independently recyclable.
356   if (MI->Operands)
357     deallocateOperandArray(MI->CapOperands, MI->Operands);
358   // Don't call ~MachineInstr() which must be trivial anyway because
359   // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
360   // destructors.
361   InstructionRecycler.Deallocate(Allocator, MI);
362 }
363 
364 /// Allocate a new MachineBasicBlock. Use this instead of
365 /// `new MachineBasicBlock'.
366 MachineBasicBlock *
367 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
368   return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
369              MachineBasicBlock(*this, bb);
370 }
371 
372 /// Delete the given MachineBasicBlock.
373 void
374 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
375   assert(MBB->getParent() == this && "MBB parent mismatch!");
376   MBB->~MachineBasicBlock();
377   BasicBlockRecycler.Deallocate(Allocator, MBB);
378 }
379 
380 MachineMemOperand *MachineFunction::getMachineMemOperand(
381     MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s,
382     unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges,
383     SyncScope::ID SSID, AtomicOrdering Ordering,
384     AtomicOrdering FailureOrdering) {
385   return new (Allocator)
386       MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges,
387                         SSID, Ordering, FailureOrdering);
388 }
389 
390 MachineMemOperand *
391 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
392                                       int64_t Offset, uint64_t Size) {
393   if (MMO->getValue())
394     return new (Allocator)
395                MachineMemOperand(MachinePointerInfo(MMO->getValue(),
396                                                     MMO->getOffset()+Offset),
397                                  MMO->getFlags(), Size, MMO->getBaseAlignment(),
398                                  AAMDNodes(), nullptr, MMO->getSyncScopeID(),
399                                  MMO->getOrdering(), MMO->getFailureOrdering());
400   return new (Allocator)
401              MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
402                                                   MMO->getOffset()+Offset),
403                                MMO->getFlags(), Size, MMO->getBaseAlignment(),
404                                AAMDNodes(), nullptr, MMO->getSyncScopeID(),
405                                MMO->getOrdering(), MMO->getFailureOrdering());
406 }
407 
408 MachineMemOperand *
409 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
410                                       const AAMDNodes &AAInfo) {
411   MachinePointerInfo MPI = MMO->getValue() ?
412              MachinePointerInfo(MMO->getValue(), MMO->getOffset()) :
413              MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset());
414 
415   return new (Allocator)
416              MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(),
417                                MMO->getBaseAlignment(), AAInfo,
418                                MMO->getRanges(), MMO->getSyncScopeID(),
419                                MMO->getOrdering(), MMO->getFailureOrdering());
420 }
421 
422 MachineInstr::ExtraInfo *
423 MachineFunction::createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs,
424                                    MCSymbol *PreInstrSymbol,
425                                    MCSymbol *PostInstrSymbol) {
426   return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol,
427                                          PostInstrSymbol);
428 }
429 
430 const char *MachineFunction::createExternalSymbolName(StringRef Name) {
431   char *Dest = Allocator.Allocate<char>(Name.size() + 1);
432   std::copy(Name.begin(), Name.end(), Dest);
433   Dest[Name.size()] = 0;
434   return Dest;
435 }
436 
437 uint32_t *MachineFunction::allocateRegMask() {
438   unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs();
439   unsigned Size = MachineOperand::getRegMaskSize(NumRegs);
440   uint32_t *Mask = Allocator.Allocate<uint32_t>(Size);
441   memset(Mask, 0, Size * sizeof(Mask[0]));
442   return Mask;
443 }
444 
445 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
446 LLVM_DUMP_METHOD void MachineFunction::dump() const {
447   print(dbgs());
448 }
449 #endif
450 
451 StringRef MachineFunction::getName() const {
452   return getFunction().getName();
453 }
454 
455 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const {
456   OS << "# Machine code for function " << getName() << ": ";
457   getProperties().print(OS);
458   OS << '\n';
459 
460   // Print Frame Information
461   FrameInfo->print(*this, OS);
462 
463   // Print JumpTable Information
464   if (JumpTableInfo)
465     JumpTableInfo->print(OS);
466 
467   // Print Constant Pool
468   ConstantPool->print(OS);
469 
470   const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
471 
472   if (RegInfo && !RegInfo->livein_empty()) {
473     OS << "Function Live Ins: ";
474     for (MachineRegisterInfo::livein_iterator
475          I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
476       OS << printReg(I->first, TRI);
477       if (I->second)
478         OS << " in " << printReg(I->second, TRI);
479       if (std::next(I) != E)
480         OS << ", ";
481     }
482     OS << '\n';
483   }
484 
485   ModuleSlotTracker MST(getFunction().getParent());
486   MST.incorporateFunction(getFunction());
487   for (const auto &BB : *this) {
488     OS << '\n';
489     // If we print the whole function, print it at its most verbose level.
490     BB.print(OS, MST, Indexes, /*IsStandalone=*/true);
491   }
492 
493   OS << "\n# End machine code for function " << getName() << ".\n\n";
494 }
495 
496 namespace llvm {
497 
498   template<>
499   struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
500     DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
501 
502     static std::string getGraphName(const MachineFunction *F) {
503       return ("CFG for '" + F->getName() + "' function").str();
504     }
505 
506     std::string getNodeLabel(const MachineBasicBlock *Node,
507                              const MachineFunction *Graph) {
508       std::string OutStr;
509       {
510         raw_string_ostream OSS(OutStr);
511 
512         if (isSimple()) {
513           OSS << printMBBReference(*Node);
514           if (const BasicBlock *BB = Node->getBasicBlock())
515             OSS << ": " << BB->getName();
516         } else
517           Node->print(OSS);
518       }
519 
520       if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
521 
522       // Process string output to make it nicer...
523       for (unsigned i = 0; i != OutStr.length(); ++i)
524         if (OutStr[i] == '\n') {                            // Left justify
525           OutStr[i] = '\\';
526           OutStr.insert(OutStr.begin()+i+1, 'l');
527         }
528       return OutStr;
529     }
530   };
531 
532 } // end namespace llvm
533 
534 void MachineFunction::viewCFG() const
535 {
536 #ifndef NDEBUG
537   ViewGraph(this, "mf" + getName());
538 #else
539   errs() << "MachineFunction::viewCFG is only available in debug builds on "
540          << "systems with Graphviz or gv!\n";
541 #endif // NDEBUG
542 }
543 
544 void MachineFunction::viewCFGOnly() const
545 {
546 #ifndef NDEBUG
547   ViewGraph(this, "mf" + getName(), true);
548 #else
549   errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
550          << "systems with Graphviz or gv!\n";
551 #endif // NDEBUG
552 }
553 
554 /// Add the specified physical register as a live-in value and
555 /// create a corresponding virtual register for it.
556 unsigned MachineFunction::addLiveIn(unsigned PReg,
557                                     const TargetRegisterClass *RC) {
558   MachineRegisterInfo &MRI = getRegInfo();
559   unsigned VReg = MRI.getLiveInVirtReg(PReg);
560   if (VReg) {
561     const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
562     (void)VRegRC;
563     // A physical register can be added several times.
564     // Between two calls, the register class of the related virtual register
565     // may have been constrained to match some operation constraints.
566     // In that case, check that the current register class includes the
567     // physical register and is a sub class of the specified RC.
568     assert((VRegRC == RC || (VRegRC->contains(PReg) &&
569                              RC->hasSubClassEq(VRegRC))) &&
570             "Register class mismatch!");
571     return VReg;
572   }
573   VReg = MRI.createVirtualRegister(RC);
574   MRI.addLiveIn(PReg, VReg);
575   return VReg;
576 }
577 
578 /// Return the MCSymbol for the specified non-empty jump table.
579 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
580 /// normal 'L' label is returned.
581 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
582                                         bool isLinkerPrivate) const {
583   const DataLayout &DL = getDataLayout();
584   assert(JumpTableInfo && "No jump tables");
585   assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
586 
587   StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
588                                      : DL.getPrivateGlobalPrefix();
589   SmallString<60> Name;
590   raw_svector_ostream(Name)
591     << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
592   return Ctx.getOrCreateSymbol(Name);
593 }
594 
595 /// Return a function-local symbol to represent the PIC base.
596 MCSymbol *MachineFunction::getPICBaseSymbol() const {
597   const DataLayout &DL = getDataLayout();
598   return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
599                                Twine(getFunctionNumber()) + "$pb");
600 }
601 
602 /// \name Exception Handling
603 /// \{
604 
605 LandingPadInfo &
606 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
607   unsigned N = LandingPads.size();
608   for (unsigned i = 0; i < N; ++i) {
609     LandingPadInfo &LP = LandingPads[i];
610     if (LP.LandingPadBlock == LandingPad)
611       return LP;
612   }
613 
614   LandingPads.push_back(LandingPadInfo(LandingPad));
615   return LandingPads[N];
616 }
617 
618 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad,
619                                 MCSymbol *BeginLabel, MCSymbol *EndLabel) {
620   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
621   LP.BeginLabels.push_back(BeginLabel);
622   LP.EndLabels.push_back(EndLabel);
623 }
624 
625 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) {
626   MCSymbol *LandingPadLabel = Ctx.createTempSymbol();
627   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
628   LP.LandingPadLabel = LandingPadLabel;
629   return LandingPadLabel;
630 }
631 
632 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad,
633                                        ArrayRef<const GlobalValue *> TyInfo) {
634   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
635   for (unsigned N = TyInfo.size(); N; --N)
636     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
637 }
638 
639 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad,
640                                         ArrayRef<const GlobalValue *> TyInfo) {
641   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
642   std::vector<unsigned> IdsInFilter(TyInfo.size());
643   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
644     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
645   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
646 }
647 
648 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol*, uintptr_t> *LPMap) {
649   for (unsigned i = 0; i != LandingPads.size(); ) {
650     LandingPadInfo &LandingPad = LandingPads[i];
651     if (LandingPad.LandingPadLabel &&
652         !LandingPad.LandingPadLabel->isDefined() &&
653         (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0))
654       LandingPad.LandingPadLabel = nullptr;
655 
656     // Special case: we *should* emit LPs with null LP MBB. This indicates
657     // "nounwind" case.
658     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
659       LandingPads.erase(LandingPads.begin() + i);
660       continue;
661     }
662 
663     for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) {
664       MCSymbol *BeginLabel = LandingPad.BeginLabels[j];
665       MCSymbol *EndLabel = LandingPad.EndLabels[j];
666       if ((BeginLabel->isDefined() ||
667            (LPMap && (*LPMap)[BeginLabel] != 0)) &&
668           (EndLabel->isDefined() ||
669            (LPMap && (*LPMap)[EndLabel] != 0))) continue;
670 
671       LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
672       LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
673       --j;
674       --e;
675     }
676 
677     // Remove landing pads with no try-ranges.
678     if (LandingPads[i].BeginLabels.empty()) {
679       LandingPads.erase(LandingPads.begin() + i);
680       continue;
681     }
682 
683     // If there is no landing pad, ensure that the list of typeids is empty.
684     // If the only typeid is a cleanup, this is the same as having no typeids.
685     if (!LandingPad.LandingPadBlock ||
686         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
687       LandingPad.TypeIds.clear();
688     ++i;
689   }
690 }
691 
692 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) {
693   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
694   LP.TypeIds.push_back(0);
695 }
696 
697 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad,
698                                          const Function *Filter,
699                                          const BlockAddress *RecoverBA) {
700   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
701   SEHHandler Handler;
702   Handler.FilterOrFinally = Filter;
703   Handler.RecoverBA = RecoverBA;
704   LP.SEHHandlers.push_back(Handler);
705 }
706 
707 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad,
708                                            const Function *Cleanup) {
709   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
710   SEHHandler Handler;
711   Handler.FilterOrFinally = Cleanup;
712   Handler.RecoverBA = nullptr;
713   LP.SEHHandlers.push_back(Handler);
714 }
715 
716 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym,
717                                             ArrayRef<unsigned> Sites) {
718   LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end());
719 }
720 
721 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) {
722   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
723     if (TypeInfos[i] == TI) return i + 1;
724 
725   TypeInfos.push_back(TI);
726   return TypeInfos.size();
727 }
728 
729 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) {
730   // If the new filter coincides with the tail of an existing filter, then
731   // re-use the existing filter.  Folding filters more than this requires
732   // re-ordering filters and/or their elements - probably not worth it.
733   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
734        E = FilterEnds.end(); I != E; ++I) {
735     unsigned i = *I, j = TyIds.size();
736 
737     while (i && j)
738       if (FilterIds[--i] != TyIds[--j])
739         goto try_next;
740 
741     if (!j)
742       // The new filter coincides with range [i, end) of the existing filter.
743       return -(1 + i);
744 
745 try_next:;
746   }
747 
748   // Add the new filter.
749   int FilterID = -(1 + FilterIds.size());
750   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
751   FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end());
752   FilterEnds.push_back(FilterIds.size());
753   FilterIds.push_back(0); // terminator
754   return FilterID;
755 }
756 
757 void llvm::addLandingPadInfo(const LandingPadInst &I, MachineBasicBlock &MBB) {
758   MachineFunction &MF = *MBB.getParent();
759   if (const auto *PF = dyn_cast<Function>(
760           I.getParent()->getParent()->getPersonalityFn()->stripPointerCasts()))
761     MF.getMMI().addPersonality(PF);
762 
763   if (I.isCleanup())
764     MF.addCleanup(&MBB);
765 
766   // FIXME: New EH - Add the clauses in reverse order. This isn't 100% correct,
767   //        but we need to do it this way because of how the DWARF EH emitter
768   //        processes the clauses.
769   for (unsigned i = I.getNumClauses(); i != 0; --i) {
770     Value *Val = I.getClause(i - 1);
771     if (I.isCatch(i - 1)) {
772       MF.addCatchTypeInfo(&MBB,
773                           dyn_cast<GlobalValue>(Val->stripPointerCasts()));
774     } else {
775       // Add filters in a list.
776       Constant *CVal = cast<Constant>(Val);
777       SmallVector<const GlobalValue *, 4> FilterList;
778       for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end();
779            II != IE; ++II)
780         FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts()));
781 
782       MF.addFilterTypeInfo(&MBB, FilterList);
783     }
784   }
785 }
786 
787 /// \}
788 
789 //===----------------------------------------------------------------------===//
790 //  MachineJumpTableInfo implementation
791 //===----------------------------------------------------------------------===//
792 
793 /// Return the size of each entry in the jump table.
794 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
795   // The size of a jump table entry is 4 bytes unless the entry is just the
796   // address of a block, in which case it is the pointer size.
797   switch (getEntryKind()) {
798   case MachineJumpTableInfo::EK_BlockAddress:
799     return TD.getPointerSize();
800   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
801     return 8;
802   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
803   case MachineJumpTableInfo::EK_LabelDifference32:
804   case MachineJumpTableInfo::EK_Custom32:
805     return 4;
806   case MachineJumpTableInfo::EK_Inline:
807     return 0;
808   }
809   llvm_unreachable("Unknown jump table encoding!");
810 }
811 
812 /// Return the alignment of each entry in the jump table.
813 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
814   // The alignment of a jump table entry is the alignment of int32 unless the
815   // entry is just the address of a block, in which case it is the pointer
816   // alignment.
817   switch (getEntryKind()) {
818   case MachineJumpTableInfo::EK_BlockAddress:
819     return TD.getPointerABIAlignment(0);
820   case MachineJumpTableInfo::EK_GPRel64BlockAddress:
821     return TD.getABIIntegerTypeAlignment(64);
822   case MachineJumpTableInfo::EK_GPRel32BlockAddress:
823   case MachineJumpTableInfo::EK_LabelDifference32:
824   case MachineJumpTableInfo::EK_Custom32:
825     return TD.getABIIntegerTypeAlignment(32);
826   case MachineJumpTableInfo::EK_Inline:
827     return 1;
828   }
829   llvm_unreachable("Unknown jump table encoding!");
830 }
831 
832 /// Create a new jump table entry in the jump table info.
833 unsigned MachineJumpTableInfo::createJumpTableIndex(
834                                const std::vector<MachineBasicBlock*> &DestBBs) {
835   assert(!DestBBs.empty() && "Cannot create an empty jump table!");
836   JumpTables.push_back(MachineJumpTableEntry(DestBBs));
837   return JumpTables.size()-1;
838 }
839 
840 /// If Old is the target of any jump tables, update the jump tables to branch
841 /// to New instead.
842 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
843                                                   MachineBasicBlock *New) {
844   assert(Old != New && "Not making a change?");
845   bool MadeChange = false;
846   for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
847     ReplaceMBBInJumpTable(i, Old, New);
848   return MadeChange;
849 }
850 
851 /// If Old is a target of the jump tables, update the jump table to branch to
852 /// New instead.
853 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
854                                                  MachineBasicBlock *Old,
855                                                  MachineBasicBlock *New) {
856   assert(Old != New && "Not making a change?");
857   bool MadeChange = false;
858   MachineJumpTableEntry &JTE = JumpTables[Idx];
859   for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
860     if (JTE.MBBs[j] == Old) {
861       JTE.MBBs[j] = New;
862       MadeChange = true;
863     }
864   return MadeChange;
865 }
866 
867 void MachineJumpTableInfo::print(raw_ostream &OS) const {
868   if (JumpTables.empty()) return;
869 
870   OS << "Jump Tables:\n";
871 
872   for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
873     OS << printJumpTableEntryReference(i) << ": ";
874     for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
875       OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]);
876   }
877 
878   OS << '\n';
879 }
880 
881 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
882 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); }
883 #endif
884 
885 Printable llvm::printJumpTableEntryReference(unsigned Idx) {
886   return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; });
887 }
888 
889 //===----------------------------------------------------------------------===//
890 //  MachineConstantPool implementation
891 //===----------------------------------------------------------------------===//
892 
893 void MachineConstantPoolValue::anchor() {}
894 
895 Type *MachineConstantPoolEntry::getType() const {
896   if (isMachineConstantPoolEntry())
897     return Val.MachineCPVal->getType();
898   return Val.ConstVal->getType();
899 }
900 
901 bool MachineConstantPoolEntry::needsRelocation() const {
902   if (isMachineConstantPoolEntry())
903     return true;
904   return Val.ConstVal->needsRelocation();
905 }
906 
907 SectionKind
908 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
909   if (needsRelocation())
910     return SectionKind::getReadOnlyWithRel();
911   switch (DL->getTypeAllocSize(getType())) {
912   case 4:
913     return SectionKind::getMergeableConst4();
914   case 8:
915     return SectionKind::getMergeableConst8();
916   case 16:
917     return SectionKind::getMergeableConst16();
918   case 32:
919     return SectionKind::getMergeableConst32();
920   default:
921     return SectionKind::getReadOnly();
922   }
923 }
924 
925 MachineConstantPool::~MachineConstantPool() {
926   // A constant may be a member of both Constants and MachineCPVsSharingEntries,
927   // so keep track of which we've deleted to avoid double deletions.
928   DenseSet<MachineConstantPoolValue*> Deleted;
929   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
930     if (Constants[i].isMachineConstantPoolEntry()) {
931       Deleted.insert(Constants[i].Val.MachineCPVal);
932       delete Constants[i].Val.MachineCPVal;
933     }
934   for (DenseSet<MachineConstantPoolValue*>::iterator I =
935        MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
936        I != E; ++I) {
937     if (Deleted.count(*I) == 0)
938       delete *I;
939   }
940 }
941 
942 /// Test whether the given two constants can be allocated the same constant pool
943 /// entry.
944 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
945                                       const DataLayout &DL) {
946   // Handle the trivial case quickly.
947   if (A == B) return true;
948 
949   // If they have the same type but weren't the same constant, quickly
950   // reject them.
951   if (A->getType() == B->getType()) return false;
952 
953   // We can't handle structs or arrays.
954   if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
955       isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
956     return false;
957 
958   // For now, only support constants with the same size.
959   uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
960   if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
961     return false;
962 
963   Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
964 
965   // Try constant folding a bitcast of both instructions to an integer.  If we
966   // get two identical ConstantInt's, then we are good to share them.  We use
967   // the constant folding APIs to do this so that we get the benefit of
968   // DataLayout.
969   if (isa<PointerType>(A->getType()))
970     A = ConstantFoldCastOperand(Instruction::PtrToInt,
971                                 const_cast<Constant *>(A), IntTy, DL);
972   else if (A->getType() != IntTy)
973     A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A),
974                                 IntTy, DL);
975   if (isa<PointerType>(B->getType()))
976     B = ConstantFoldCastOperand(Instruction::PtrToInt,
977                                 const_cast<Constant *>(B), IntTy, DL);
978   else if (B->getType() != IntTy)
979     B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B),
980                                 IntTy, DL);
981 
982   return A == B;
983 }
984 
985 /// Create a new entry in the constant pool or return an existing one.
986 /// User must specify the log2 of the minimum required alignment for the object.
987 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
988                                                    unsigned Alignment) {
989   assert(Alignment && "Alignment must be specified!");
990   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
991 
992   // Check to see if we already have this constant.
993   //
994   // FIXME, this could be made much more efficient for large constant pools.
995   for (unsigned i = 0, e = Constants.size(); i != e; ++i)
996     if (!Constants[i].isMachineConstantPoolEntry() &&
997         CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
998       if ((unsigned)Constants[i].getAlignment() < Alignment)
999         Constants[i].Alignment = Alignment;
1000       return i;
1001     }
1002 
1003   Constants.push_back(MachineConstantPoolEntry(C, Alignment));
1004   return Constants.size()-1;
1005 }
1006 
1007 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
1008                                                    unsigned Alignment) {
1009   assert(Alignment && "Alignment must be specified!");
1010   if (Alignment > PoolAlignment) PoolAlignment = Alignment;
1011 
1012   // Check to see if we already have this constant.
1013   //
1014   // FIXME, this could be made much more efficient for large constant pools.
1015   int Idx = V->getExistingMachineCPValue(this, Alignment);
1016   if (Idx != -1) {
1017     MachineCPVsSharingEntries.insert(V);
1018     return (unsigned)Idx;
1019   }
1020 
1021   Constants.push_back(MachineConstantPoolEntry(V, Alignment));
1022   return Constants.size()-1;
1023 }
1024 
1025 void MachineConstantPool::print(raw_ostream &OS) const {
1026   if (Constants.empty()) return;
1027 
1028   OS << "Constant Pool:\n";
1029   for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
1030     OS << "  cp#" << i << ": ";
1031     if (Constants[i].isMachineConstantPoolEntry())
1032       Constants[i].Val.MachineCPVal->print(OS);
1033     else
1034       Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
1035     OS << ", align=" << Constants[i].getAlignment();
1036     OS << "\n";
1037   }
1038 }
1039 
1040 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1041 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); }
1042 #endif
1043