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