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