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