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