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/MachineFunctionInitializer.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/GraphWriter.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetFrameLowering.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
45 #define DEBUG_TYPE "codegen"
47 void MachineFunctionInitializer::anchor() {}
49 //===----------------------------------------------------------------------===//
50 // MachineFunction implementation
51 //===----------------------------------------------------------------------===//
53 // Out-of-line virtual method.
54 MachineFunctionInfo::~MachineFunctionInfo() {}
56 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) {
57 MBB->getParent()->DeleteMachineBasicBlock(MBB);
60 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM,
61 unsigned FunctionNum, MachineModuleInfo &mmi)
62 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()),
64 if (STI->getRegisterInfo())
65 RegInfo = new (Allocator) MachineRegisterInfo(this);
70 FrameInfo = new (Allocator)
71 MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(),
72 STI->getFrameLowering()->isStackRealignable(),
73 !F->hasFnAttribute("no-realign-stack"));
75 if (Fn->hasFnAttribute(Attribute::StackAlignment))
76 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment());
78 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout());
79 Alignment = STI->getTargetLowering()->getMinFunctionAlignment();
81 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn.
82 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize))
83 Alignment = std::max(Alignment,
84 STI->getTargetLowering()->getPrefFunctionAlignment());
86 FunctionNumber = FunctionNum;
87 JumpTableInfo = nullptr;
90 MachineFunction::~MachineFunction() {
91 // Don't call destructors on MachineInstr and MachineOperand. All of their
92 // memory comes from the BumpPtrAllocator which is about to be purged.
94 // Do call MachineBasicBlock destructors, it contains std::vectors.
95 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I))
96 I->Insts.clearAndLeakNodesUnsafely();
98 InstructionRecycler.clear(Allocator);
99 OperandRecycler.clear(Allocator);
100 BasicBlockRecycler.clear(Allocator);
102 RegInfo->~MachineRegisterInfo();
103 Allocator.Deallocate(RegInfo);
106 MFInfo->~MachineFunctionInfo();
107 Allocator.Deallocate(MFInfo);
110 FrameInfo->~MachineFrameInfo();
111 Allocator.Deallocate(FrameInfo);
113 ConstantPool->~MachineConstantPool();
114 Allocator.Deallocate(ConstantPool);
117 JumpTableInfo->~MachineJumpTableInfo();
118 Allocator.Deallocate(JumpTableInfo);
122 const DataLayout &MachineFunction::getDataLayout() const {
123 return Fn->getParent()->getDataLayout();
126 /// Get the JumpTableInfo for this function.
127 /// If it does not already exist, allocate one.
128 MachineJumpTableInfo *MachineFunction::
129 getOrCreateJumpTableInfo(unsigned EntryKind) {
130 if (JumpTableInfo) return JumpTableInfo;
132 JumpTableInfo = new (Allocator)
133 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind);
134 return JumpTableInfo;
137 /// Should we be emitting segmented stack stuff for the function
138 bool MachineFunction::shouldSplitStack() {
139 return getFunction()->hasFnAttribute("split-stack");
142 /// This discards all of the MachineBasicBlock numbers and recomputes them.
143 /// This guarantees that the MBB numbers are sequential, dense, and match the
144 /// ordering of the blocks within the function. If a specific MachineBasicBlock
145 /// is specified, only that block and those after it are renumbered.
146 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) {
147 if (empty()) { MBBNumbering.clear(); return; }
148 MachineFunction::iterator MBBI, E = end();
154 // Figure out the block number this should have.
155 unsigned BlockNo = 0;
157 BlockNo = std::prev(MBBI)->getNumber() + 1;
159 for (; MBBI != E; ++MBBI, ++BlockNo) {
160 if (MBBI->getNumber() != (int)BlockNo) {
161 // Remove use of the old number.
162 if (MBBI->getNumber() != -1) {
163 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI &&
164 "MBB number mismatch!");
165 MBBNumbering[MBBI->getNumber()] = nullptr;
168 // If BlockNo is already taken, set that block's number to -1.
169 if (MBBNumbering[BlockNo])
170 MBBNumbering[BlockNo]->setNumber(-1);
172 MBBNumbering[BlockNo] = MBBI;
173 MBBI->setNumber(BlockNo);
177 // Okay, all the blocks are renumbered. If we have compactified the block
178 // numbering, shrink MBBNumbering now.
179 assert(BlockNo <= MBBNumbering.size() && "Mismatch!");
180 MBBNumbering.resize(BlockNo);
183 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'.
185 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID,
186 DebugLoc DL, bool NoImp) {
187 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
188 MachineInstr(*this, MCID, DL, NoImp);
191 /// Create a new MachineInstr which is a copy of the 'Orig' instruction,
192 /// identical in all ways except the instruction has no parent, prev, or next.
194 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) {
195 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator))
196 MachineInstr(*this, *Orig);
199 /// Delete the given MachineInstr.
201 /// This function also serves as the MachineInstr destructor - the real
202 /// ~MachineInstr() destructor must be empty.
204 MachineFunction::DeleteMachineInstr(MachineInstr *MI) {
205 // Strip it for parts. The operand array and the MI object itself are
206 // independently recyclable.
208 deallocateOperandArray(MI->CapOperands, MI->Operands);
209 // Don't call ~MachineInstr() which must be trivial anyway because
210 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their
212 InstructionRecycler.Deallocate(Allocator, MI);
215 /// Allocate a new MachineBasicBlock. Use this instead of
216 /// `new MachineBasicBlock'.
218 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) {
219 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator))
220 MachineBasicBlock(*this, bb);
223 /// Delete the given MachineBasicBlock.
225 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) {
226 assert(MBB->getParent() == this && "MBB parent mismatch!");
227 MBB->~MachineBasicBlock();
228 BasicBlockRecycler.Deallocate(Allocator, MBB);
232 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f,
233 uint64_t s, unsigned base_alignment,
234 const AAMDNodes &AAInfo,
235 const MDNode *Ranges) {
236 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment,
241 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO,
242 int64_t Offset, uint64_t Size) {
244 return new (Allocator)
245 MachineMemOperand(MachinePointerInfo(MMO->getValue(),
246 MMO->getOffset()+Offset),
247 MMO->getFlags(), Size,
248 MMO->getBaseAlignment());
249 return new (Allocator)
250 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(),
251 MMO->getOffset()+Offset),
252 MMO->getFlags(), Size,
253 MMO->getBaseAlignment());
256 MachineInstr::mmo_iterator
257 MachineFunction::allocateMemRefsArray(unsigned long Num) {
258 return Allocator.Allocate<MachineMemOperand *>(Num);
261 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
262 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin,
263 MachineInstr::mmo_iterator End) {
264 // Count the number of load mem refs.
266 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
270 // Allocate a new array and populate it with the load information.
271 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
273 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
274 if ((*I)->isLoad()) {
275 if (!(*I)->isStore())
279 // Clone the MMO and unset the store flag.
280 MachineMemOperand *JustLoad =
281 getMachineMemOperand((*I)->getPointerInfo(),
282 (*I)->getFlags() & ~MachineMemOperand::MOStore,
283 (*I)->getSize(), (*I)->getBaseAlignment(),
285 Result[Index] = JustLoad;
290 return std::make_pair(Result, Result + Num);
293 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator>
294 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin,
295 MachineInstr::mmo_iterator End) {
296 // Count the number of load mem refs.
298 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I)
302 // Allocate a new array and populate it with the store information.
303 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num);
305 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) {
306 if ((*I)->isStore()) {
311 // Clone the MMO and unset the load flag.
312 MachineMemOperand *JustStore =
313 getMachineMemOperand((*I)->getPointerInfo(),
314 (*I)->getFlags() & ~MachineMemOperand::MOLoad,
315 (*I)->getSize(), (*I)->getBaseAlignment(),
317 Result[Index] = JustStore;
322 return std::make_pair(Result, Result + Num);
325 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
326 void MachineFunction::dump() const {
331 StringRef MachineFunction::getName() const {
332 assert(getFunction() && "No function!");
333 return getFunction()->getName();
336 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const {
337 OS << "# Machine code for function " << getName() << ": ";
339 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA");
340 if (!RegInfo->tracksLiveness())
341 OS << ", not tracking liveness";
345 // Print Frame Information
346 FrameInfo->print(*this, OS);
348 // Print JumpTable Information
350 JumpTableInfo->print(OS);
352 // Print Constant Pool
353 ConstantPool->print(OS);
355 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo();
357 if (RegInfo && !RegInfo->livein_empty()) {
358 OS << "Function Live Ins: ";
359 for (MachineRegisterInfo::livein_iterator
360 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) {
361 OS << PrintReg(I->first, TRI);
363 OS << " in " << PrintReg(I->second, TRI);
364 if (std::next(I) != E)
370 ModuleSlotTracker MST(getFunction()->getParent());
371 MST.incorporateFunction(*getFunction());
372 for (const auto &BB : *this) {
374 BB.print(OS, MST, Indexes);
377 OS << "\n# End machine code for function " << getName() << ".\n\n";
382 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits {
384 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}
386 static std::string getGraphName(const MachineFunction *F) {
387 return ("CFG for '" + F->getName() + "' function").str();
390 std::string getNodeLabel(const MachineBasicBlock *Node,
391 const MachineFunction *Graph) {
394 raw_string_ostream OSS(OutStr);
397 OSS << "BB#" << Node->getNumber();
398 if (const BasicBlock *BB = Node->getBasicBlock())
399 OSS << ": " << BB->getName();
404 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
406 // Process string output to make it nicer...
407 for (unsigned i = 0; i != OutStr.length(); ++i)
408 if (OutStr[i] == '\n') { // Left justify
410 OutStr.insert(OutStr.begin()+i+1, 'l');
417 void MachineFunction::viewCFG() const
420 ViewGraph(this, "mf" + getName());
422 errs() << "MachineFunction::viewCFG is only available in debug builds on "
423 << "systems with Graphviz or gv!\n";
427 void MachineFunction::viewCFGOnly() const
430 ViewGraph(this, "mf" + getName(), true);
432 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on "
433 << "systems with Graphviz or gv!\n";
437 /// Add the specified physical register as a live-in value and
438 /// create a corresponding virtual register for it.
439 unsigned MachineFunction::addLiveIn(unsigned PReg,
440 const TargetRegisterClass *RC) {
441 MachineRegisterInfo &MRI = getRegInfo();
442 unsigned VReg = MRI.getLiveInVirtReg(PReg);
444 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg);
446 // A physical register can be added several times.
447 // Between two calls, the register class of the related virtual register
448 // may have been constrained to match some operation constraints.
449 // In that case, check that the current register class includes the
450 // physical register and is a sub class of the specified RC.
451 assert((VRegRC == RC || (VRegRC->contains(PReg) &&
452 RC->hasSubClassEq(VRegRC))) &&
453 "Register class mismatch!");
456 VReg = MRI.createVirtualRegister(RC);
457 MRI.addLiveIn(PReg, VReg);
461 /// Return the MCSymbol for the specified non-empty jump table.
462 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
463 /// normal 'L' label is returned.
464 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx,
465 bool isLinkerPrivate) const {
466 const DataLayout &DL = getDataLayout();
467 assert(JumpTableInfo && "No jump tables");
468 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!");
470 const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix()
471 : DL.getPrivateGlobalPrefix();
472 SmallString<60> Name;
473 raw_svector_ostream(Name)
474 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI;
475 return Ctx.getOrCreateSymbol(Name);
478 /// Return a function-local symbol to represent the PIC base.
479 MCSymbol *MachineFunction::getPICBaseSymbol() const {
480 const DataLayout &DL = getDataLayout();
481 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
482 Twine(getFunctionNumber()) + "$pb");
485 //===----------------------------------------------------------------------===//
486 // MachineFrameInfo implementation
487 //===----------------------------------------------------------------------===//
489 /// Make sure the function is at least Align bytes aligned.
490 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) {
491 if (!StackRealignable || !RealignOption)
492 assert(Align <= StackAlignment &&
493 "For targets without stack realignment, Align is out of limit!");
494 if (MaxAlignment < Align) MaxAlignment = Align;
497 /// Clamp the alignment if requested and emit a warning.
498 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align,
499 unsigned StackAlign) {
500 if (!ShouldClamp || Align <= StackAlign)
502 DEBUG(dbgs() << "Warning: requested alignment " << Align
503 << " exceeds the stack alignment " << StackAlign
504 << " when stack realignment is off" << '\n');
508 /// Create a new statically sized stack object, returning a nonnegative
509 /// identifier to represent it.
510 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment,
511 bool isSS, const AllocaInst *Alloca) {
512 assert(Size != 0 && "Cannot allocate zero size stack objects!");
513 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
514 Alignment, StackAlignment);
515 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca,
517 int Index = (int)Objects.size() - NumFixedObjects - 1;
518 assert(Index >= 0 && "Bad frame index!");
519 ensureMaxAlignment(Alignment);
523 /// Create a new statically sized stack object that represents a spill slot,
524 /// returning a nonnegative identifier to represent it.
525 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size,
526 unsigned Alignment) {
527 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
528 Alignment, StackAlignment);
529 CreateStackObject(Size, Alignment, true);
530 int Index = (int)Objects.size() - NumFixedObjects - 1;
531 ensureMaxAlignment(Alignment);
535 /// Notify the MachineFrameInfo object that a variable sized object has been
536 /// created. This must be created whenever a variable sized object is created,
537 /// whether or not the index returned is actually used.
538 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment,
539 const AllocaInst *Alloca) {
540 HasVarSizedObjects = true;
541 Alignment = clampStackAlignment(!StackRealignable || !RealignOption,
542 Alignment, StackAlignment);
543 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true));
544 ensureMaxAlignment(Alignment);
545 return (int)Objects.size()-NumFixedObjects-1;
548 /// Create a new object at a fixed location on the stack.
549 /// All fixed objects should be created before other objects are created for
550 /// efficiency. By default, fixed objects are immutable. This returns an
551 /// index with a negative value.
552 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset,
553 bool Immutable, bool isAliased) {
554 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!");
555 // The alignment of the frame index can be determined from its offset from
556 // the incoming frame position. If the frame object is at offset 32 and
557 // the stack is guaranteed to be 16-byte aligned, then we know that the
558 // object is 16-byte aligned.
559 unsigned Align = MinAlign(SPOffset, StackAlignment);
560 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
562 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable,
564 /*Alloca*/ nullptr, isAliased));
565 return -++NumFixedObjects;
568 /// Create a spill slot at a fixed location on the stack.
569 /// Returns an index with a negative value.
570 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size,
572 unsigned Align = MinAlign(SPOffset, StackAlignment);
573 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align,
575 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset,
579 /*isAliased*/ false));
580 return -++NumFixedObjects;
583 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const {
584 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
585 BitVector BV(TRI->getNumRegs());
587 // Before CSI is calculated, no registers are considered pristine. They can be
588 // freely used and PEI will make sure they are saved.
589 if (!isCalleeSavedInfoValid())
592 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR)
595 // Saved CSRs are not pristine.
596 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo();
597 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(),
598 E = CSI.end(); I != E; ++I)
599 BV.reset(I->getReg());
604 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const {
605 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
606 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
607 unsigned MaxAlign = getMaxAlignment();
610 // This code is very, very similar to PEI::calculateFrameObjectOffsets().
611 // It really should be refactored to share code. Until then, changes
612 // should keep in mind that there's tight coupling between the two.
614 for (int i = getObjectIndexBegin(); i != 0; ++i) {
615 int FixedOff = -getObjectOffset(i);
616 if (FixedOff > Offset) Offset = FixedOff;
618 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) {
619 if (isDeadObjectIndex(i))
621 Offset += getObjectSize(i);
622 unsigned Align = getObjectAlignment(i);
623 // Adjust to alignment boundary
624 Offset = (Offset+Align-1)/Align*Align;
626 MaxAlign = std::max(Align, MaxAlign);
629 if (adjustsStack() && TFI->hasReservedCallFrame(MF))
630 Offset += getMaxCallFrameSize();
632 // Round up the size to a multiple of the alignment. If the function has
633 // any calls or alloca's, align to the target's StackAlignment value to
634 // ensure that the callee's frame or the alloca data is suitably aligned;
635 // otherwise, for leaf functions, align to the TransientStackAlignment
638 if (adjustsStack() || hasVarSizedObjects() ||
639 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0))
640 StackAlign = TFI->getStackAlignment();
642 StackAlign = TFI->getTransientStackAlignment();
644 // If the frame pointer is eliminated, all frame offsets will be relative to
645 // SP not FP. Align to MaxAlign so this works.
646 StackAlign = std::max(StackAlign, MaxAlign);
647 unsigned AlignMask = StackAlign - 1;
648 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask);
650 return (unsigned)Offset;
653 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{
654 if (Objects.empty()) return;
656 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering();
657 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0);
659 OS << "Frame Objects:\n";
661 for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
662 const StackObject &SO = Objects[i];
663 OS << " fi#" << (int)(i-NumFixedObjects) << ": ";
664 if (SO.Size == ~0ULL) {
669 OS << "variable sized";
671 OS << "size=" << SO.Size;
672 OS << ", align=" << SO.Alignment;
674 if (i < NumFixedObjects)
676 if (i < NumFixedObjects || SO.SPOffset != -1) {
677 int64_t Off = SO.SPOffset - ValOffset;
678 OS << ", at location [SP";
689 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
690 void MachineFrameInfo::dump(const MachineFunction &MF) const {
695 //===----------------------------------------------------------------------===//
696 // MachineJumpTableInfo implementation
697 //===----------------------------------------------------------------------===//
699 /// Return the size of each entry in the jump table.
700 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const {
701 // The size of a jump table entry is 4 bytes unless the entry is just the
702 // address of a block, in which case it is the pointer size.
703 switch (getEntryKind()) {
704 case MachineJumpTableInfo::EK_BlockAddress:
705 return TD.getPointerSize();
706 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
708 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
709 case MachineJumpTableInfo::EK_LabelDifference32:
710 case MachineJumpTableInfo::EK_Custom32:
712 case MachineJumpTableInfo::EK_Inline:
715 llvm_unreachable("Unknown jump table encoding!");
718 /// Return the alignment of each entry in the jump table.
719 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const {
720 // The alignment of a jump table entry is the alignment of int32 unless the
721 // entry is just the address of a block, in which case it is the pointer
723 switch (getEntryKind()) {
724 case MachineJumpTableInfo::EK_BlockAddress:
725 return TD.getPointerABIAlignment();
726 case MachineJumpTableInfo::EK_GPRel64BlockAddress:
727 return TD.getABIIntegerTypeAlignment(64);
728 case MachineJumpTableInfo::EK_GPRel32BlockAddress:
729 case MachineJumpTableInfo::EK_LabelDifference32:
730 case MachineJumpTableInfo::EK_Custom32:
731 return TD.getABIIntegerTypeAlignment(32);
732 case MachineJumpTableInfo::EK_Inline:
735 llvm_unreachable("Unknown jump table encoding!");
738 /// Create a new jump table entry in the jump table info.
739 unsigned MachineJumpTableInfo::createJumpTableIndex(
740 const std::vector<MachineBasicBlock*> &DestBBs) {
741 assert(!DestBBs.empty() && "Cannot create an empty jump table!");
742 JumpTables.push_back(MachineJumpTableEntry(DestBBs));
743 return JumpTables.size()-1;
746 /// If Old is the target of any jump tables, update the jump tables to branch
748 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old,
749 MachineBasicBlock *New) {
750 assert(Old != New && "Not making a change?");
751 bool MadeChange = false;
752 for (size_t i = 0, e = JumpTables.size(); i != e; ++i)
753 ReplaceMBBInJumpTable(i, Old, New);
757 /// If Old is a target of the jump tables, update the jump table to branch to
759 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx,
760 MachineBasicBlock *Old,
761 MachineBasicBlock *New) {
762 assert(Old != New && "Not making a change?");
763 bool MadeChange = false;
764 MachineJumpTableEntry &JTE = JumpTables[Idx];
765 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j)
766 if (JTE.MBBs[j] == Old) {
773 void MachineJumpTableInfo::print(raw_ostream &OS) const {
774 if (JumpTables.empty()) return;
776 OS << "Jump Tables:\n";
778 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) {
779 OS << " jt#" << i << ": ";
780 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j)
781 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber();
787 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
788 void MachineJumpTableInfo::dump() const { print(dbgs()); }
792 //===----------------------------------------------------------------------===//
793 // MachineConstantPool implementation
794 //===----------------------------------------------------------------------===//
796 void MachineConstantPoolValue::anchor() { }
798 Type *MachineConstantPoolEntry::getType() const {
799 if (isMachineConstantPoolEntry())
800 return Val.MachineCPVal->getType();
801 return Val.ConstVal->getType();
805 unsigned MachineConstantPoolEntry::getRelocationInfo() const {
806 if (isMachineConstantPoolEntry())
807 return Val.MachineCPVal->getRelocationInfo();
808 return Val.ConstVal->getRelocationInfo();
812 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const {
814 switch (getRelocationInfo()) {
816 llvm_unreachable("Unknown section kind");
817 case Constant::GlobalRelocations:
818 Kind = SectionKind::getReadOnlyWithRel();
820 case Constant::LocalRelocation:
821 Kind = SectionKind::getReadOnlyWithRelLocal();
823 case Constant::NoRelocation:
824 switch (DL->getTypeAllocSize(getType())) {
826 Kind = SectionKind::getMergeableConst4();
829 Kind = SectionKind::getMergeableConst8();
832 Kind = SectionKind::getMergeableConst16();
835 Kind = SectionKind::getReadOnly();
842 MachineConstantPool::~MachineConstantPool() {
843 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
844 if (Constants[i].isMachineConstantPoolEntry())
845 delete Constants[i].Val.MachineCPVal;
846 for (DenseSet<MachineConstantPoolValue*>::iterator I =
847 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end();
852 /// Test whether the given two constants can be allocated the same constant pool
854 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B,
855 const DataLayout &DL) {
856 // Handle the trivial case quickly.
857 if (A == B) return true;
859 // If they have the same type but weren't the same constant, quickly
861 if (A->getType() == B->getType()) return false;
863 // We can't handle structs or arrays.
864 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) ||
865 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType()))
868 // For now, only support constants with the same size.
869 uint64_t StoreSize = DL.getTypeStoreSize(A->getType());
870 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128)
873 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8);
875 // Try constant folding a bitcast of both instructions to an integer. If we
876 // get two identical ConstantInt's, then we are good to share them. We use
877 // the constant folding APIs to do this so that we get the benefit of
879 if (isa<PointerType>(A->getType()))
880 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
881 const_cast<Constant *>(A), DL);
882 else if (A->getType() != IntTy)
883 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
884 const_cast<Constant *>(A), DL);
885 if (isa<PointerType>(B->getType()))
886 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy,
887 const_cast<Constant *>(B), DL);
888 else if (B->getType() != IntTy)
889 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy,
890 const_cast<Constant *>(B), DL);
895 /// Create a new entry in the constant pool or return an existing one.
896 /// User must specify the log2 of the minimum required alignment for the object.
897 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C,
898 unsigned Alignment) {
899 assert(Alignment && "Alignment must be specified!");
900 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
902 // Check to see if we already have this constant.
904 // FIXME, this could be made much more efficient for large constant pools.
905 for (unsigned i = 0, e = Constants.size(); i != e; ++i)
906 if (!Constants[i].isMachineConstantPoolEntry() &&
907 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) {
908 if ((unsigned)Constants[i].getAlignment() < Alignment)
909 Constants[i].Alignment = Alignment;
913 Constants.push_back(MachineConstantPoolEntry(C, Alignment));
914 return Constants.size()-1;
917 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V,
918 unsigned Alignment) {
919 assert(Alignment && "Alignment must be specified!");
920 if (Alignment > PoolAlignment) PoolAlignment = Alignment;
922 // Check to see if we already have this constant.
924 // FIXME, this could be made much more efficient for large constant pools.
925 int Idx = V->getExistingMachineCPValue(this, Alignment);
927 MachineCPVsSharingEntries.insert(V);
928 return (unsigned)Idx;
931 Constants.push_back(MachineConstantPoolEntry(V, Alignment));
932 return Constants.size()-1;
935 void MachineConstantPool::print(raw_ostream &OS) const {
936 if (Constants.empty()) return;
938 OS << "Constant Pool:\n";
939 for (unsigned i = 0, e = Constants.size(); i != e; ++i) {
940 OS << " cp#" << i << ": ";
941 if (Constants[i].isMachineConstantPoolEntry())
942 Constants[i].Val.MachineCPVal->print(OS);
944 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false);
945 OS << ", align=" << Constants[i].getAlignment();
950 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
951 void MachineConstantPool::dump() const { print(dbgs()); }