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