1 //===-- MachineFunction.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Collect native machine code information for a function. This allows
11 // target-specific information about the generated code to be stored with each
14 //===----------------------------------------------------------------------===//
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/DataLayout.h"
29 #include "llvm/DebugInfo.h"
30 #include "llvm/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"
41 //===----------------------------------------------------------------------===//
42 // MachineFunction implementation
43 //===----------------------------------------------------------------------===//
45 // Out of line virtual method.
46 MachineFunctionInfo::~MachineFunctionInfo() {}
48 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
49 MBB->getParent()->DeleteMachineBasicBlock(MBB);
52 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
53 unsigned FunctionNum, MachineModuleInfo &mmi,
55 : Fn(F), Target(TM), Ctx(mmi.getContext()), MMI(mmi), GMI(gmi) {
56 if (TM.getRegisterInfo())
57 RegInfo = new (Allocator) MachineRegisterInfo(*TM.getRegisterInfo());
61 FrameInfo = new (Allocator) MachineFrameInfo(*TM.getFrameLowering(),
62 TM.Options.RealignStack);
63 if (Fn->getFnAttributes().hasAttribute(Attributes::StackAlignment))
64 FrameInfo->ensureMaxAlignment(Fn->getAttributes().
65 getFnAttributes().getStackAlignment());
66 ConstantPool = new (Allocator) MachineConstantPool(TM.getDataLayout());
67 Alignment = TM.getTargetLowering()->getMinFunctionAlignment();
68 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
69 if (!Fn->getFnAttributes().hasAttribute(Attributes::OptimizeForSize))
70 Alignment = std::max(Alignment,
71 TM.getTargetLowering()->getPrefFunctionAlignment());
72 FunctionNumber = FunctionNum;
76 MachineFunction::~MachineFunction() {
78 InstructionRecycler.clear(Allocator);
79 BasicBlockRecycler.clear(Allocator);
81 RegInfo->~MachineRegisterInfo();
82 Allocator.Deallocate(RegInfo);
85 MFInfo->~MachineFunctionInfo();
86 Allocator.Deallocate(MFInfo);
89 FrameInfo->~MachineFrameInfo();
90 Allocator.Deallocate(FrameInfo);
92 ConstantPool->~MachineConstantPool();
93 Allocator.Deallocate(ConstantPool);
96 JumpTableInfo->~MachineJumpTableInfo();
97 Allocator.Deallocate(JumpTableInfo);
101 /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
102 /// does already exist, allocate one.
103 MachineJumpTableInfo *MachineFunction::
104 getOrCreateJumpTableInfo(unsigned EntryKind) {
105 if (JumpTableInfo) return JumpTableInfo;
107 JumpTableInfo = new (Allocator)
108 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
109 return JumpTableInfo;
112 /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
113 /// recomputes them. This guarantees that the MBB numbers are sequential,
114 /// dense, and match the ordering of the blocks within the function. If a
115 /// specific MachineBasicBlock is specified, only that block and those after
116 /// it are renumbered.
117 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
118 if (empty()) { MBBNumbering.clear(); return; }
119 MachineFunction::iterator MBBI, E = end();
125 // Figure out the block number this should have.
126 unsigned BlockNo = 0;
128 BlockNo = prior(MBBI)->getNumber()+1;
130 for (; MBBI != E; ++MBBI, ++BlockNo) {
131 if (MBBI->getNumber() != (int)BlockNo) {
132 // Remove use of the old number.
133 if (MBBI->getNumber() != -1) {
134 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
135 "MBB number mismatch!");
136 MBBNumbering[MBBI->getNumber()] = 0;
139 // If BlockNo is already taken, set that block's number to -1.
140 if (MBBNumbering[BlockNo])
141 MBBNumbering[BlockNo]->setNumber(-1);
143 MBBNumbering[BlockNo] = MBBI;
144 MBBI->setNumber(BlockNo);
148 // Okay, all the blocks are renumbered. If we have compactified the block
149 // numbering, shrink MBBNumbering now.
150 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
151 MBBNumbering.resize(BlockNo);
154 /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
155 /// of `new MachineInstr'.
158 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
159 DebugLoc DL, bool NoImp) {
160 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
161 MachineInstr(MCID, DL, NoImp);
164 /// CloneMachineInstr - Create a new MachineInstr which is a copy of the
165 /// 'Orig' instruction, identical in all ways except the instruction
166 /// has no parent, prev, or next.
169 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
170 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
171 MachineInstr(*this, *Orig);
174 /// DeleteMachineInstr - Delete the given MachineInstr.
177 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
179 InstructionRecycler.Deallocate(Allocator, MI);
182 /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
183 /// instead of `new MachineBasicBlock'.
186 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
187 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
188 MachineBasicBlock(*this, bb);
191 /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
194 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
195 assert(MBB->getParent() == this && "MBB parent mismatch!");
196 MBB->~MachineBasicBlock();
197 BasicBlockRecycler.Deallocate(Allocator, MBB);
201 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
202 uint64_t s, unsigned base_alignment,
203 const MDNode *TBAAInfo,
204 const MDNode *Ranges) {
205 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
210 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
211 int64_t Offset, uint64_t Size) {
212 return new (Allocator)
213 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
214 MMO->getOffset()+Offset),
215 MMO->getFlags(), Size,
216 MMO->getBaseAlignment(), 0);
219 MachineInstr::mmo_iterator
220 MachineFunction::allocateMemRefsArray(unsigned long Num) {
221 return Allocator.Allocate<MachineMemOperand *>(Num);
224 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
225 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
226 MachineInstr::mmo_iterator End) {
227 // Count the number of load mem refs.
229 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
233 // Allocate a new array and populate it with the load information.
234 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
236 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
237 if ((*I)->isLoad()) {
238 if (!(*I)->isStore())
242 // Clone the MMO and unset the store flag.
243 MachineMemOperand *JustLoad =
244 getMachineMemOperand((*I)->getPointerInfo(),
245 (*I)->getFlags() & ~MachineMemOperand::MOStore,
246 (*I)->getSize(), (*I)->getBaseAlignment(),
247 (*I)->getTBAAInfo());
248 Result[Index] = JustLoad;
253 return std::make_pair(Result, Result + Num);
256 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
257 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
258 MachineInstr::mmo_iterator End) {
259 // Count the number of load mem refs.
261 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
265 // Allocate a new array and populate it with the store information.
266 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
268 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
269 if ((*I)->isStore()) {
274 // Clone the MMO and unset the load flag.
275 MachineMemOperand *JustStore =
276 getMachineMemOperand((*I)->getPointerInfo(),
277 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
278 (*I)->getSize(), (*I)->getBaseAlignment(),
279 (*I)->getTBAAInfo());
280 Result[Index] = JustStore;
285 return std::make_pair(Result, Result + Num);
288 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
289 void MachineFunction::dump() const {
294 StringRef MachineFunction::getName() const {
295 assert(getFunction() && "No function!");
296 return getFunction()->getName();
299 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
300 OS << "# Machine code for function " << getName() << ": ";
302 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
303 if (!RegInfo->tracksLiveness())
304 OS << ", not tracking liveness";
308 // Print Frame Information
309 FrameInfo->print(*this, OS);
311 // Print JumpTable Information
313 JumpTableInfo->print(OS);
315 // Print Constant Pool
316 ConstantPool->print(OS);
318 const TargetRegisterInfo *TRI = getTarget().getRegisterInfo();
320 if (RegInfo && !RegInfo->livein_empty()) {
321 OS << "Function Live Ins: ";
322 for (MachineRegisterInfo::livein_iterator
323 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
324 OS << PrintReg(I->first, TRI);
326 OS << " in " << PrintReg(I->second, TRI);
327 if (llvm::next(I) != E)
332 if (RegInfo && !RegInfo->liveout_empty()) {
333 OS << "Function Live Outs:";
334 for (MachineRegisterInfo::liveout_iterator
335 I = RegInfo->liveout_begin(), E = RegInfo->liveout_end(); I != E; ++I)
336 OS << ' ' << PrintReg(*I, TRI);
340 for (const_iterator BB = begin(), E = end(); BB != E; ++BB) {
342 BB->print(OS, Indexes);
345 OS << "\n# End machine code for function " << getName() << ".\n\n";
350 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
352 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
354 static std::string getGraphName(const MachineFunction *F) {
355 return "CFG for '" + F->getName().str() + "' function";
358 std::string getNodeLabel(const MachineBasicBlock *Node,
359 const MachineFunction *Graph) {
362 raw_string_ostream OSS(OutStr);
365 OSS << "BB#" << Node->getNumber();
366 if (const BasicBlock *BB = Node->getBasicBlock())
367 OSS << ": " << BB->getName();
372 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
374 // Process string output to make it nicer...
375 for (unsigned i = 0; i != OutStr.length(); ++i)
376 if (OutStr[i] == '\n') { // Left justify
378 OutStr.insert(OutStr.begin()+i+1, 'l');
385 void MachineFunction::viewCFG() const
388 ViewGraph(this, "mf" + getName());
390 errs() << "MachineFunction::viewCFG is only available in debug builds on "
391 << "systems with Graphviz or gv!\n";
395 void MachineFunction::viewCFGOnly() const
398 ViewGraph(this, "mf" + getName(), true);
400 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
401 << "systems with Graphviz or gv!\n";
405 /// addLiveIn - Add the specified physical register as a live-in value and
406 /// create a corresponding virtual register for it.
407 unsigned MachineFunction::addLiveIn(unsigned PReg,
408 const TargetRegisterClass *RC) {
409 MachineRegisterInfo &MRI = getRegInfo();
410 unsigned VReg = MRI.getLiveInVirtReg(PReg);
412 assert(MRI.getRegClass(VReg) == RC && "Register class mismatch!");
415 VReg = MRI.createVirtualRegister(RC);
416 MRI.addLiveIn(PReg, VReg);
420 /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
421 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
422 /// normal 'L' label is returned.
423 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
424 bool isLinkerPrivate) const {
425 assert(JumpTableInfo && "No jump tables");
426 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
427 const MCAsmInfo &MAI = *getTarget().getMCAsmInfo();
429 const char *Prefix = isLinkerPrivate ? MAI.getLinkerPrivateGlobalPrefix() :
430 MAI.getPrivateGlobalPrefix();
431 SmallString<60> Name;
432 raw_svector_ostream(Name)
433 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
434 return Ctx.GetOrCreateSymbol(Name.str());
437 /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
439 MCSymbol *MachineFunction::getPICBaseSymbol() const {
440 const MCAsmInfo &MAI = *Target.getMCAsmInfo();
441 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
442 Twine(getFunctionNumber())+"$pb");
445 //===----------------------------------------------------------------------===//
446 // MachineFrameInfo implementation
447 //===----------------------------------------------------------------------===//
449 /// ensureMaxAlignment - Make sure the function is at least Align bytes
451 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
452 if (!TFI.isStackRealignable() || !RealignOption)
453 assert(Align <= TFI.getStackAlignment() &&
454 "For targets without stack realignment, Align is out of limit!");
455 if (MaxAlignment < Align) MaxAlignment = Align;
458 /// clampStackAlignment - Clamp the alignment if requested and emit a warning.
459 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
460 unsigned StackAlign) {
461 if (!ShouldClamp || Align <= StackAlign)
463 DEBUG(dbgs() << "Warning: requested alignment " << Align
464 << " exceeds the stack alignment " << StackAlign
465 << " when stack realignment is off" << '\n');
469 /// CreateStackObject - Create a new statically sized stack object, returning
470 /// a nonnegative identifier to represent it.
472 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
473 bool isSS, bool MayNeedSP, const AllocaInst *Alloca) {
474 assert(Size != 0 && "Cannot allocate zero size stack objects!");
475 Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
476 Alignment, TFI.getStackAlignment());
477 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, MayNeedSP,
479 int Index = (int)Objects.size() - NumFixedObjects - 1;
480 assert(Index >= 0 && "Bad frame index!");
481 ensureMaxAlignment(Alignment);
485 /// CreateSpillStackObject - Create a new statically sized stack object that
486 /// represents a spill slot, returning a nonnegative identifier to represent
489 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
490 unsigned Alignment) {
491 Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
492 Alignment, TFI.getStackAlignment());
493 CreateStackObject(Size, Alignment, true, false);
494 int Index = (int)Objects.size() - NumFixedObjects - 1;
495 ensureMaxAlignment(Alignment);
499 /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
500 /// variable sized object has been created. This must be created whenever a
501 /// variable sized object is created, whether or not the index returned is
504 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment) {
505 HasVarSizedObjects = true;
506 Alignment = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
507 Alignment, TFI.getStackAlignment());
508 Objects.push_back(StackObject(0, Alignment, 0, false, false, true, 0));
509 ensureMaxAlignment(Alignment);
510 return (int)Objects.size()-NumFixedObjects-1;
513 /// CreateFixedObject - Create a new object at a fixed location on the stack.
514 /// All fixed objects should be created before other objects are created for
515 /// efficiency. By default, fixed objects are immutable. This returns an
516 /// index with a negative value.
518 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
520 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
521 // The alignment of the frame index can be determined from its offset from
522 // the incoming frame position. If the frame object is at offset 32 and
523 // the stack is guaranteed to be 16-byte aligned, then we know that the
524 // object is 16-byte aligned.
525 unsigned StackAlign = TFI.getStackAlignment();
526 unsigned Align = MinAlign(SPOffset, StackAlign);
527 Align = clampStackAlignment(!TFI.isStackRealignable() || !RealignOption,
528 Align, TFI.getStackAlignment());
529 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
533 return -++NumFixedObjects;
538 MachineFrameInfo::getPristineRegs(const MachineBasicBlock *MBB) const {
539 assert(MBB && "MBB must be valid");
540 const MachineFunction *MF = MBB->getParent();
541 assert(MF && "MBB must be part of a MachineFunction");
542 const TargetMachine &TM = MF->getTarget();
543 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
544 BitVector BV(TRI->getNumRegs());
546 // Before CSI is calculated, no registers are considered pristine. They can be
547 // freely used and PEI will make sure they are saved.
548 if (!isCalleeSavedInfoValid())
551 for (const uint16_t *CSR = TRI->getCalleeSavedRegs(MF); CSR && *CSR; ++CSR)
554 // The entry MBB always has all CSRs pristine.
555 if (MBB == &MF->front())
558 // On other MBBs the saved CSRs are not pristine.
559 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
560 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
561 E = CSI.end(); I != E; ++I)
562 BV.reset(I->getReg());
568 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
569 if (Objects.empty()) return;
571 const TargetFrameLowering *FI = MF.getTarget().getFrameLowering();
572 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
574 OS << "Frame Objects:\n";
576 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
577 const StackObject &SO = Objects[i];
578 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
579 if (SO.Size == ~0ULL) {
584 OS << "variable sized";
586 OS << "size=" << SO.Size;
587 OS << ", align=" << SO.Alignment;
589 if (i < NumFixedObjects)
591 if (i < NumFixedObjects || SO.SPOffset != -1) {
592 int64_t Off = SO.SPOffset - ValOffset;
593 OS << ", at location [SP";
604 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
605 void MachineFrameInfo::dump(const MachineFunction &MF) const {
610 //===----------------------------------------------------------------------===//
611 // MachineJumpTableInfo implementation
612 //===----------------------------------------------------------------------===//
614 /// getEntrySize - Return the size of each entry in the jump table.
615 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
616 // The size of a jump table entry is 4 bytes unless the entry is just the
617 // address of a block, in which case it is the pointer size.
618 switch (getEntryKind()) {
619 case MachineJumpTableInfo::EK_BlockAddress:
620 return TD.getPointerSize();
621 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
623 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
624 case MachineJumpTableInfo::EK_LabelDifference32:
625 case MachineJumpTableInfo::EK_Custom32:
627 case MachineJumpTableInfo::EK_Inline:
630 llvm_unreachable("Unknown jump table encoding!");
633 /// getEntryAlignment - Return the alignment of each entry in the jump table.
634 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
635 // The alignment of a jump table entry is the alignment of int32 unless the
636 // entry is just the address of a block, in which case it is the pointer
638 switch (getEntryKind()) {
639 case MachineJumpTableInfo::EK_BlockAddress:
640 return TD.getPointerABIAlignment();
641 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
642 return TD.getABIIntegerTypeAlignment(64);
643 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
644 case MachineJumpTableInfo::EK_LabelDifference32:
645 case MachineJumpTableInfo::EK_Custom32:
646 return TD.getABIIntegerTypeAlignment(32);
647 case MachineJumpTableInfo::EK_Inline:
650 llvm_unreachable("Unknown jump table encoding!");
653 /// createJumpTableIndex - Create a new jump table entry in the jump table info.
655 unsigned MachineJumpTableInfo::createJumpTableIndex(
656 const std::vector<MachineBasicBlock*> &DestBBs) {
657 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
658 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
659 return JumpTables.size()-1;
662 /// ReplaceMBBInJumpTables - If Old is the target of any jump tables, update
663 /// the jump tables to branch to New instead.
664 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
665 MachineBasicBlock *New) {
666 assert(Old != New && "Not making a change?");
667 bool MadeChange = false;
668 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
669 ReplaceMBBInJumpTable(i, Old, New);
673 /// ReplaceMBBInJumpTable - If Old is a target of the jump tables, update
674 /// the jump table to branch to New instead.
675 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
676 MachineBasicBlock *Old,
677 MachineBasicBlock *New) {
678 assert(Old != New && "Not making a change?");
679 bool MadeChange = false;
680 MachineJumpTableEntry &JTE = JumpTables[Idx];
681 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
682 if (JTE.MBBs[j] == Old) {
689 void MachineJumpTableInfo::print(raw_ostream &OS) const {
690 if (JumpTables.empty()) return;
692 OS << "Jump Tables:\n";
694 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
695 OS << " jt#" << i << ": ";
696 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
697 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
703 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
704 void MachineJumpTableInfo::dump() const { print(dbgs()); }
708 //===----------------------------------------------------------------------===//
709 // MachineConstantPool implementation
710 //===----------------------------------------------------------------------===//
712 void MachineConstantPoolValue::anchor() { }
714 Type *MachineConstantPoolEntry::getType() const {
715 if (isMachineConstantPoolEntry())
716 return Val.MachineCPVal->getType();
717 return Val.ConstVal->getType();
721 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
722 if (isMachineConstantPoolEntry())
723 return Val.MachineCPVal->getRelocationInfo();
724 return Val.ConstVal->getRelocationInfo();
727 MachineConstantPool::~MachineConstantPool() {
728 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
729 if (Constants[i].isMachineConstantPoolEntry())
730 delete Constants[i].Val.MachineCPVal;
731 for (DenseSet<MachineConstantPoolValue*>::iterator I =
732 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
737 /// CanShareConstantPoolEntry - Test whether the given two constants
738 /// can be allocated the same constant pool entry.
739 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
740 const DataLayout *TD) {
741 // Handle the trivial case quickly.
742 if (A == B) return true;
744 // If they have the same type but weren't the same constant, quickly
746 if (A->getType() == B->getType()) return false;
748 // We can't handle structs or arrays.
749 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
750 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
753 // For now, only support constants with the same size.
754 uint64_t StoreSize = TD->getTypeStoreSize(A->getType());
755 if (StoreSize != TD->getTypeStoreSize(B->getType()) ||
759 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
761 // Try constant folding a bitcast of both instructions to an integer. If we
762 // get two identical ConstantInt's, then we are good to share them. We use
763 // the constant folding APIs to do this so that we get the benefit of
765 if (isa<PointerType>(A->getType()))
766 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
767 const_cast<Constant*>(A), TD);
768 else if (A->getType() != IntTy)
769 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
770 const_cast<Constant*>(A), TD);
771 if (isa<PointerType>(B->getType()))
772 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
773 const_cast<Constant*>(B), TD);
774 else if (B->getType() != IntTy)
775 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
776 const_cast<Constant*>(B), TD);
781 /// getConstantPoolIndex - Create a new entry in the constant pool or return
782 /// an existing one. User must specify the log2 of the minimum required
783 /// alignment for the object.
785 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
786 unsigned Alignment) {
787 assert(Alignment && "Alignment must be specified!");
788 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
790 // Check to see if we already have this constant.
792 // FIXME, this could be made much more efficient for large constant pools.
793 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
794 if (!Constants[i].isMachineConstantPoolEntry() &&
795 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, TD)) {
796 if ((unsigned)Constants[i].getAlignment() < Alignment)
797 Constants[i].Alignment = Alignment;
801 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
802 return Constants.size()-1;
805 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
806 unsigned Alignment) {
807 assert(Alignment && "Alignment must be specified!");
808 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
810 // Check to see if we already have this constant.
812 // FIXME, this could be made much more efficient for large constant pools.
813 int Idx = V->getExistingMachineCPValue(this, Alignment);
815 MachineCPVsSharingEntries.insert(V);
816 return (unsigned)Idx;
819 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
820 return Constants.size()-1;
823 void MachineConstantPool::print(raw_ostream &OS) const {
824 if (Constants.empty()) return;
826 OS << "Constant Pool:\n";
827 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
828 OS << " cp#" << i << ": ";
829 if (Constants[i].isMachineConstantPoolEntry())
830 Constants[i].Val.MachineCPVal->print(OS);
832 OS << *(const Value*)Constants[i].Val.ConstVal;
833 OS << ", align=" << Constants[i].getAlignment();
838 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
839 void MachineConstantPool::dump() const { print(dbgs()); }