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