MachineFunction.cpp revision b84822fb7b64977c16e97b870891da1d6c9736fe
1c1a19689b83a9569b30ba43c168fdca328cb9f2eJakob Bornecrantz//===-- MachineFunction.cpp -----------------------------------------------===//
2c1a19689b83a9569b30ba43c168fdca328cb9f2eJakob Bornecrantz//
3c1a19689b83a9569b30ba43c168fdca328cb9f2eJakob Bornecrantz//                     The LLVM Compiler Infrastructure
4c1a19689b83a9569b30ba43c168fdca328cb9f2eJakob Bornecrantz//
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/DerivedTypes.h"
17#include "llvm/Function.h"
18#include "llvm/Instructions.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/Config/config.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstr.h"
26#include "llvm/CodeGen/MachineJumpTableInfo.h"
27#include "llvm/CodeGen/MachineRegisterInfo.h"
28#include "llvm/CodeGen/Passes.h"
29#include "llvm/Analysis/DebugInfo.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/Target/TargetLowering.h"
33#include "llvm/Target/TargetMachine.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Support/GraphWriter.h"
36#include "llvm/Support/raw_ostream.h"
37using namespace llvm;
38
39namespace {
40  struct Printer : public MachineFunctionPass {
41    static char ID;
42
43    raw_ostream &OS;
44    const std::string Banner;
45
46    Printer(raw_ostream &os, const std::string &banner)
47      : MachineFunctionPass(&ID), OS(os), Banner(banner) {}
48
49    const char *getPassName() const { return "MachineFunction Printer"; }
50
51    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52      AU.setPreservesAll();
53      MachineFunctionPass::getAnalysisUsage(AU);
54    }
55
56    bool runOnMachineFunction(MachineFunction &MF) {
57      OS << "# " << Banner << ":\n";
58      MF.print(OS);
59      return false;
60    }
61  };
62  char Printer::ID = 0;
63}
64
65/// Returns a newly-created MachineFunction Printer pass. The default banner is
66/// empty.
67///
68FunctionPass *llvm::createMachineFunctionPrinterPass(raw_ostream &OS,
69                                                     const std::string &Banner){
70  return new Printer(OS, Banner);
71}
72
73//===----------------------------------------------------------------------===//
74// MachineFunction implementation
75//===----------------------------------------------------------------------===//
76
77// Out of line virtual method.
78MachineFunctionInfo::~MachineFunctionInfo() {}
79
80void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
81  MBB->getParent()->DeleteMachineBasicBlock(MBB);
82}
83
84MachineFunction::MachineFunction(Function *F, const TargetMachine &TM,
85                                 unsigned FunctionNum)
86  : Fn(F), Target(TM) {
87  if (TM.getRegisterInfo())
88    RegInfo = new (Allocator.Allocate<MachineRegisterInfo>())
89                  MachineRegisterInfo(*TM.getRegisterInfo());
90  else
91    RegInfo = 0;
92  MFInfo = 0;
93  FrameInfo = new (Allocator.Allocate<MachineFrameInfo>())
94                  MachineFrameInfo(*TM.getFrameInfo());
95  ConstantPool = new (Allocator.Allocate<MachineConstantPool>())
96                     MachineConstantPool(TM.getTargetData());
97  Alignment = TM.getTargetLowering()->getFunctionAlignment(F);
98  FunctionNumber = FunctionNum;
99  JumpTableInfo = 0;
100}
101
102MachineFunction::~MachineFunction() {
103  BasicBlocks.clear();
104  InstructionRecycler.clear(Allocator);
105  BasicBlockRecycler.clear(Allocator);
106  if (RegInfo) {
107    RegInfo->~MachineRegisterInfo();
108    Allocator.Deallocate(RegInfo);
109  }
110  if (MFInfo) {
111    MFInfo->~MachineFunctionInfo();
112    Allocator.Deallocate(MFInfo);
113  }
114  FrameInfo->~MachineFrameInfo();         Allocator.Deallocate(FrameInfo);
115  ConstantPool->~MachineConstantPool();   Allocator.Deallocate(ConstantPool);
116
117  if (JumpTableInfo) {
118    JumpTableInfo->~MachineJumpTableInfo();
119    Allocator.Deallocate(JumpTableInfo);
120  }
121}
122
123/// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
124/// does already exist, allocate one.
125MachineJumpTableInfo *MachineFunction::
126getOrCreateJumpTableInfo(unsigned EntryKind) {
127  if (JumpTableInfo) return JumpTableInfo;
128
129  JumpTableInfo = new (Allocator.Allocate<MachineJumpTableInfo>())
130    MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
131  return JumpTableInfo;
132}
133
134/// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
135/// recomputes them.  This guarantees that the MBB numbers are sequential,
136/// dense, and match the ordering of the blocks within the function.  If a
137/// specific MachineBasicBlock is specified, only that block and those after
138/// it are renumbered.
139void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
140  if (empty()) { MBBNumbering.clear(); return; }
141  MachineFunction::iterator MBBI, E = end();
142  if (MBB == 0)
143    MBBI = begin();
144  else
145    MBBI = MBB;
146
147  // Figure out the block number this should have.
148  unsigned BlockNo = 0;
149  if (MBBI != begin())
150    BlockNo = prior(MBBI)->getNumber()+1;
151
152  for (; MBBI != E; ++MBBI, ++BlockNo) {
153    if (MBBI->getNumber() != (int)BlockNo) {
154      // Remove use of the old number.
155      if (MBBI->getNumber() != -1) {
156        assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
157               "MBB number mismatch!");
158        MBBNumbering[MBBI->getNumber()] = 0;
159      }
160
161      // If BlockNo is already taken, set that block's number to -1.
162      if (MBBNumbering[BlockNo])
163        MBBNumbering[BlockNo]->setNumber(-1);
164
165      MBBNumbering[BlockNo] = MBBI;
166      MBBI->setNumber(BlockNo);
167    }
168  }
169
170  // Okay, all the blocks are renumbered.  If we have compactified the block
171  // numbering, shrink MBBNumbering now.
172  assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
173  MBBNumbering.resize(BlockNo);
174}
175
176/// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
177/// of `new MachineInstr'.
178///
179MachineInstr *
180MachineFunction::CreateMachineInstr(const TargetInstrDesc &TID,
181                                    DebugLoc DL, bool NoImp) {
182  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
183    MachineInstr(TID, DL, NoImp);
184}
185
186/// CloneMachineInstr - Create a new MachineInstr which is a copy of the
187/// 'Orig' instruction, identical in all ways except the the instruction
188/// has no parent, prev, or next.
189///
190MachineInstr *
191MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
192  return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
193             MachineInstr(*this, *Orig);
194}
195
196/// DeleteMachineInstr - Delete the given MachineInstr.
197///
198void
199MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
200  MI->~MachineInstr();
201  InstructionRecycler.Deallocate(Allocator, MI);
202}
203
204/// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
205/// instead of `new MachineBasicBlock'.
206///
207MachineBasicBlock *
208MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
209  return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
210             MachineBasicBlock(*this, bb);
211}
212
213/// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
214///
215void
216MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
217  assert(MBB->getParent() == this && "MBB parent mismatch!");
218  MBB->~MachineBasicBlock();
219  BasicBlockRecycler.Deallocate(Allocator, MBB);
220}
221
222MachineMemOperand *
223MachineFunction::getMachineMemOperand(const Value *v, unsigned f,
224                                      int64_t o, uint64_t s,
225                                      unsigned base_alignment) {
226  return new (Allocator.Allocate<MachineMemOperand>())
227             MachineMemOperand(v, f, o, s, base_alignment);
228}
229
230MachineMemOperand *
231MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
232                                      int64_t Offset, uint64_t Size) {
233  return new (Allocator.Allocate<MachineMemOperand>())
234             MachineMemOperand(MMO->getValue(), MMO->getFlags(),
235                               int64_t(uint64_t(MMO->getOffset()) +
236                                       uint64_t(Offset)),
237                               Size, MMO->getBaseAlignment());
238}
239
240MachineInstr::mmo_iterator
241MachineFunction::allocateMemRefsArray(unsigned long Num) {
242  return Allocator.Allocate<MachineMemOperand *>(Num);
243}
244
245std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
246MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
247                                    MachineInstr::mmo_iterator End) {
248  // Count the number of load mem refs.
249  unsigned Num = 0;
250  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
251    if ((*I)->isLoad())
252      ++Num;
253
254  // Allocate a new array and populate it with the load information.
255  MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
256  unsigned Index = 0;
257  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
258    if ((*I)->isLoad()) {
259      if (!(*I)->isStore())
260        // Reuse the MMO.
261        Result[Index] = *I;
262      else {
263        // Clone the MMO and unset the store flag.
264        MachineMemOperand *JustLoad =
265          getMachineMemOperand((*I)->getValue(),
266                               (*I)->getFlags() & ~MachineMemOperand::MOStore,
267                               (*I)->getOffset(), (*I)->getSize(),
268                               (*I)->getBaseAlignment());
269        Result[Index] = JustLoad;
270      }
271      ++Index;
272    }
273  }
274  return std::make_pair(Result, Result + Num);
275}
276
277std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
278MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
279                                     MachineInstr::mmo_iterator End) {
280  // Count the number of load mem refs.
281  unsigned Num = 0;
282  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
283    if ((*I)->isStore())
284      ++Num;
285
286  // Allocate a new array and populate it with the store information.
287  MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
288  unsigned Index = 0;
289  for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
290    if ((*I)->isStore()) {
291      if (!(*I)->isLoad())
292        // Reuse the MMO.
293        Result[Index] = *I;
294      else {
295        // Clone the MMO and unset the load flag.
296        MachineMemOperand *JustStore =
297          getMachineMemOperand((*I)->getValue(),
298                               (*I)->getFlags() & ~MachineMemOperand::MOLoad,
299                               (*I)->getOffset(), (*I)->getSize(),
300                               (*I)->getBaseAlignment());
301        Result[Index] = JustStore;
302      }
303      ++Index;
304    }
305  }
306  return std::make_pair(Result, Result + Num);
307}
308
309void MachineFunction::dump() const {
310  print(dbgs());
311}
312
313void MachineFunction::print(raw_ostream &OS) const {
314  OS << "# Machine code for function " << Fn->getName() << ":\n";
315
316  // Print Frame Information
317  FrameInfo->print(*this, OS);
318
319  // Print JumpTable Information
320  if (JumpTableInfo)
321    JumpTableInfo->print(OS);
322
323  // Print Constant Pool
324  ConstantPool->print(OS);
325
326  const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
327
328  if (RegInfo && !RegInfo->livein_empty()) {
329    OS << "Function Live Ins: ";
330    for (MachineRegisterInfo::livein_iterator
331         I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
332      if (TRI)
333        OS << "%" << TRI->getName(I->first);
334      else
335        OS << " %physreg" << I->first;
336
337      if (I->second)
338        OS << " in reg%" << I->second;
339
340      if (llvm::next(I) != E)
341        OS << ", ";
342    }
343    OS << '\n';
344  }
345  if (RegInfo && !RegInfo->liveout_empty()) {
346    OS << "Function Live Outs: ";
347    for (MachineRegisterInfo::liveout_iterator
348         I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I){
349      if (TRI)
350        OS << '%' << TRI->getName(*I);
351      else
352        OS << "%physreg" << *I;
353
354      if (llvm::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);
363  }
364
365  OS << "\n# End machine code for function " << Fn->getName() << ".\n\n";
366}
367
368namespace 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->getFunction()->getNameStr() + "' function";
376    }
377
378    std::string getNodeLabel(const MachineBasicBlock *Node,
379                             const MachineFunction *Graph) {
380      if (isSimple () && Node->getBasicBlock() &&
381          !Node->getBasicBlock()->getName().empty())
382        return Node->getBasicBlock()->getNameStr() + ":";
383
384      std::string OutStr;
385      {
386        raw_string_ostream OSS(OutStr);
387
388        if (isSimple())
389          OSS << Node->getNumber() << ':';
390        else
391          Node->print(OSS);
392      }
393
394      if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
395
396      // Process string output to make it nicer...
397      for (unsigned i = 0; i != OutStr.length(); ++i)
398        if (OutStr[i] == '\n') {                            // Left justify
399          OutStr[i] = '\\';
400          OutStr.insert(OutStr.begin()+i+1, 'l');
401        }
402      return OutStr;
403    }
404  };
405}
406
407void MachineFunction::viewCFG() const
408{
409#ifndef NDEBUG
410  ViewGraph(this, "mf" + getFunction()->getNameStr());
411#else
412  errs() << "SelectionDAG::viewGraph is only available in debug builds on "
413         << "systems with Graphviz or gv!\n";
414#endif // NDEBUG
415}
416
417void MachineFunction::viewCFGOnly() const
418{
419#ifndef NDEBUG
420  ViewGraph(this, "mf" + getFunction()->getNameStr(), true);
421#else
422  errs() << "SelectionDAG::viewGraph is only available in debug builds on "
423         << "systems with Graphviz or gv!\n";
424#endif // NDEBUG
425}
426
427/// addLiveIn - Add the specified physical register as a live-in value and
428/// create a corresponding virtual register for it.
429unsigned MachineFunction::addLiveIn(unsigned PReg,
430                                    const TargetRegisterClass *RC) {
431  assert(RC->contains(PReg) && "Not the correct regclass!");
432  unsigned VReg = getRegInfo().createVirtualRegister(RC);
433  getRegInfo().addLiveIn(PReg, VReg);
434  return VReg;
435}
436
437/// getDILocation - Get the DILocation for a given DebugLoc object.
438DILocation MachineFunction::getDILocation(DebugLoc DL) const {
439  unsigned Idx = DL.getIndex();
440  assert(Idx < DebugLocInfo.DebugLocations.size() &&
441         "Invalid index into debug locations!");
442  return DILocation(DebugLocInfo.DebugLocations[Idx]);
443}
444
445//===----------------------------------------------------------------------===//
446//  MachineFrameInfo implementation
447//===----------------------------------------------------------------------===//
448
449/// CreateFixedObject - Create a new object at a fixed location on the stack.
450/// All fixed objects should be created before other objects are created for
451/// efficiency. By default, fixed objects are immutable. This returns an
452/// index with a negative value.
453///
454int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
455                                        bool Immutable, bool isSS) {
456  assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
457  Objects.insert(Objects.begin(), StackObject(Size, 1, SPOffset, Immutable,
458                                              isSS));
459  return -++NumFixedObjects;
460}
461
462
463BitVector
464MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
465  assert(MBB && "MBB must be valid");
466  const MachineFunction *MF = MBB->getParent();
467  assert(MF && "MBB must be part of a MachineFunction");
468  const TargetMachine &TM = MF->getTarget();
469  const TargetRegisterInfo *TRI = TM.getRegisterInfo();
470  BitVector BV(TRI->getNumRegs());
471
472  // Before CSI is calculated, no registers are considered pristine. They can be
473  // freely used and PEI will make sure they are saved.
474  if (!isCalleeSavedInfoValid())
475    return BV;
476
477  for (const unsigned *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
478    BV.set(*CSR);
479
480  // The entry MBB always has all CSRs pristine.
481  if (MBB == &MF->front())
482    return BV;
483
484  // On other MBBs the saved CSRs are not pristine.
485  const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
486  for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
487         E = CSI.end(); I != E; ++I)
488    BV.reset(I->getReg());
489
490  return BV;
491}
492
493
494void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
495  if (Objects.empty()) return;
496
497  const TargetFrameInfo *FI = MF.getTarget().getFrameInfo();
498  int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
499
500  OS << "Frame Objects:\n";
501
502  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
503    const StackObject &SO = Objects[i];
504    OS << "  fi#" << (int)(i-NumFixedObjects) << ": ";
505    if (SO.Size == ~0ULL) {
506      OS << "dead\n";
507      continue;
508    }
509    if (SO.Size == 0)
510      OS << "variable sized";
511    else
512      OS << "size=" << SO.Size;
513    OS << ", align=" << SO.Alignment;
514
515    if (i < NumFixedObjects)
516      OS << ", fixed";
517    if (i < NumFixedObjects || SO.SPOffset != -1) {
518      int64_t Off = SO.SPOffset - ValOffset;
519      OS << ", at location [SP";
520      if (Off > 0)
521        OS << "+" << Off;
522      else if (Off < 0)
523        OS << Off;
524      OS << "]";
525    }
526    OS << "\n";
527  }
528}
529
530void MachineFrameInfo::dump(const MachineFunction &MF) const {
531  print(MF, dbgs());
532}
533
534//===----------------------------------------------------------------------===//
535//  MachineJumpTableInfo implementation
536//===----------------------------------------------------------------------===//
537
538/// getEntrySize - Return the size of each entry in the jump table.
539unsigned MachineJumpTableInfo::getEntrySize(const TargetData &TD) const {
540  // The size of a jump table entry is 4 bytes unless the entry is just the
541  // address of a block, in which case it is the pointer size.
542  switch (getEntryKind()) {
543  case MachineJumpTableInfo::EK_BlockAddress:
544    return TD.getPointerSize();
545  case MachineJumpTableInfo::EK_GPRel32BlockAddress:
546  case MachineJumpTableInfo::EK_LabelDifference32:
547  case MachineJumpTableInfo::EK_Custom32:
548    return 4;
549  }
550  assert(0 && "Unknown jump table encoding!");
551  return ~0;
552}
553
554/// getEntryAlignment - Return the alignment of each entry in the jump table.
555unsigned MachineJumpTableInfo::getEntryAlignment(const TargetData &TD) const {
556  // The alignment of a jump table entry is the alignment of int32 unless the
557  // entry is just the address of a block, in which case it is the pointer
558  // alignment.
559  switch (getEntryKind()) {
560  case MachineJumpTableInfo::EK_BlockAddress:
561    return TD.getPointerABIAlignment();
562  case MachineJumpTableInfo::EK_GPRel32BlockAddress:
563  case MachineJumpTableInfo::EK_LabelDifference32:
564  case MachineJumpTableInfo::EK_Custom32:
565    return TD.getABIIntegerTypeAlignment(32);
566  }
567  assert(0 && "Unknown jump table encoding!");
568  return ~0;
569}
570
571/// getJumpTableIndex - Create a new jump table entry in the jump table info
572/// or return an existing one.
573///
574unsigned MachineJumpTableInfo::getJumpTableIndex(
575                               const std::vector<MachineBasicBlock*> &DestBBs) {
576  assert(!DestBBs.empty() && "Cannot create an empty jump table!");
577  JumpTables.push_back(MachineJumpTableEntry(DestBBs));
578  return JumpTables.size()-1;
579}
580
581/// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
582/// the jump tables to branch to New instead.
583bool
584MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
585                                             MachineBasicBlock *New) {
586  assert(Old != New && "Not making a change?");
587  bool MadeChange = false;
588  for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
589    ReplaceMBBInJumpTable(i, Old, New);
590  return MadeChange;
591}
592
593/// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
594/// the jump table to branch to New instead.
595bool
596MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
597                                            MachineBasicBlock *Old,
598                                            MachineBasicBlock *New) {
599  assert(Old != New && "Not making a change?");
600  bool MadeChange = false;
601  MachineJumpTableEntry &JTE = JumpTables[Idx];
602  for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
603    if (JTE.MBBs[j] == Old) {
604      JTE.MBBs[j] = New;
605      MadeChange = true;
606    }
607  return MadeChange;
608}
609
610void MachineJumpTableInfo::print(raw_ostream &OS) const {
611  if (JumpTables.empty()) return;
612
613  OS << "Jump Tables:\n";
614
615  for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
616    OS << "  jt#" << i << ": ";
617    for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
618      OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
619  }
620
621  OS << '\n';
622}
623
624void MachineJumpTableInfo::dump() const { print(dbgs()); }
625
626
627//===----------------------------------------------------------------------===//
628//  MachineConstantPool implementation
629//===----------------------------------------------------------------------===//
630
631const Type *MachineConstantPoolEntry::getType() const {
632  if (isMachineConstantPoolEntry())
633    return Val.MachineCPVal->getType();
634  return Val.ConstVal->getType();
635}
636
637
638unsigned MachineConstantPoolEntry::getRelocationInfo() const {
639  if (isMachineConstantPoolEntry())
640    return Val.MachineCPVal->getRelocationInfo();
641  return Val.ConstVal->getRelocationInfo();
642}
643
644MachineConstantPool::~MachineConstantPool() {
645  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
646    if (Constants[i].isMachineConstantPoolEntry())
647      delete Constants[i].Val.MachineCPVal;
648}
649
650/// CanShareConstantPoolEntry - Test whether the given two constants
651/// can be allocated the same constant pool entry.
652static bool CanShareConstantPoolEntry(Constant *A, Constant *B,
653                                      const TargetData *TD) {
654  // Handle the trivial case quickly.
655  if (A == B) return true;
656
657  // If they have the same type but weren't the same constant, quickly
658  // reject them.
659  if (A->getType() == B->getType()) return false;
660
661  // For now, only support constants with the same size.
662  if (TD->getTypeStoreSize(A->getType()) != TD->getTypeStoreSize(B->getType()))
663    return false;
664
665  // If a floating-point value and an integer value have the same encoding,
666  // they can share a constant-pool entry.
667  if (ConstantFP *AFP = dyn_cast<ConstantFP>(A))
668    if (ConstantInt *BI = dyn_cast<ConstantInt>(B))
669      return AFP->getValueAPF().bitcastToAPInt() == BI->getValue();
670  if (ConstantFP *BFP = dyn_cast<ConstantFP>(B))
671    if (ConstantInt *AI = dyn_cast<ConstantInt>(A))
672      return BFP->getValueAPF().bitcastToAPInt() == AI->getValue();
673
674  // Two vectors can share an entry if each pair of corresponding
675  // elements could.
676  if (ConstantVector *AV = dyn_cast<ConstantVector>(A))
677    if (ConstantVector *BV = dyn_cast<ConstantVector>(B)) {
678      if (AV->getType()->getNumElements() != BV->getType()->getNumElements())
679        return false;
680      for (unsigned i = 0, e = AV->getType()->getNumElements(); i != e; ++i)
681        if (!CanShareConstantPoolEntry(AV->getOperand(i),
682                                       BV->getOperand(i), TD))
683          return false;
684      return true;
685    }
686
687  // TODO: Handle other cases.
688
689  return false;
690}
691
692/// getConstantPoolIndex - Create a new entry in the constant pool or return
693/// an existing one.  User must specify the log2 of the minimum required
694/// alignment for the object.
695///
696unsigned MachineConstantPool::getConstantPoolIndex(Constant *C,
697                                                   unsigned Alignment) {
698  assert(Alignment && "Alignment must be specified!");
699  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
700
701  // Check to see if we already have this constant.
702  //
703  // FIXME, this could be made much more efficient for large constant pools.
704  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
705    if (!Constants[i].isMachineConstantPoolEntry() &&
706        CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, TD)) {
707      if ((unsigned)Constants[i].getAlignment() < Alignment)
708        Constants[i].Alignment = Alignment;
709      return i;
710    }
711
712  Constants.push_back(MachineConstantPoolEntry(C, Alignment));
713  return Constants.size()-1;
714}
715
716unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
717                                                   unsigned Alignment) {
718  assert(Alignment && "Alignment must be specified!");
719  if (Alignment > PoolAlignment) PoolAlignment = Alignment;
720
721  // Check to see if we already have this constant.
722  //
723  // FIXME, this could be made much more efficient for large constant pools.
724  int Idx = V->getExistingMachineCPValue(this, Alignment);
725  if (Idx != -1)
726    return (unsigned)Idx;
727
728  Constants.push_back(MachineConstantPoolEntry(V, Alignment));
729  return Constants.size()-1;
730}
731
732void MachineConstantPool::print(raw_ostream &OS) const {
733  if (Constants.empty()) return;
734
735  OS << "Constant Pool:\n";
736  for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
737    OS << "  cp#" << i << ": ";
738    if (Constants[i].isMachineConstantPoolEntry())
739      Constants[i].Val.MachineCPVal->print(OS);
740    else
741      OS << *(Value*)Constants[i].Val.ConstVal;
742    OS << ", align=" << Constants[i].getAlignment();
743    OS << "\n";
744  }
745}
746
747void MachineConstantPool::dump() const { print(dbgs()); }
748