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